1
0
mirror of https://github.com/musix-org/musix-oss synced 2025-06-17 13:56:01 +00:00
This commit is contained in:
MatteZ02
2020-03-03 22:30:50 +02:00
parent edfcc6f474
commit 30022c7634
11800 changed files with 1984416 additions and 1 deletions

View File

@ -0,0 +1,31 @@
export interface BackoffOptions {
initialDelay?: number;
multiplier?: number;
jitter?: number;
maxDelay?: number;
}
export declare class BackoffTimeout {
private callback;
private initialDelay;
private multiplier;
private maxDelay;
private jitter;
private nextDelay;
private timerId;
private running;
constructor(callback: () => void, options?: BackoffOptions);
/**
* Call the callback after the current amount of delay time
*/
runOnce(): void;
/**
* Stop the timer. The callback will not be called until `runOnce` is called
* again.
*/
stop(): void;
/**
* Reset the delay time to its initial value.
*/
reset(): void;
isRunning(): boolean;
}

View File

@ -0,0 +1,90 @@
"use strict";
/*
* Copyright 2019 gRPC authors.
*
* 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.
*
*/
Object.defineProperty(exports, "__esModule", { value: true });
const INITIAL_BACKOFF_MS = 1000;
const BACKOFF_MULTIPLIER = 1.6;
const MAX_BACKOFF_MS = 120000;
const BACKOFF_JITTER = 0.2;
/**
* Get a number uniformly at random in the range [min, max)
* @param min
* @param max
*/
function uniformRandom(min, max) {
return Math.random() * (max - min) + min;
}
class BackoffTimeout {
constructor(callback, options) {
this.callback = callback;
this.initialDelay = INITIAL_BACKOFF_MS;
this.multiplier = BACKOFF_MULTIPLIER;
this.maxDelay = MAX_BACKOFF_MS;
this.jitter = BACKOFF_JITTER;
this.running = false;
if (options) {
if (options.initialDelay) {
this.initialDelay = options.initialDelay;
}
if (options.multiplier) {
this.multiplier = options.multiplier;
}
if (options.jitter) {
this.jitter = options.jitter;
}
if (options.maxDelay) {
this.maxDelay = options.maxDelay;
}
}
this.nextDelay = this.initialDelay;
this.timerId = setTimeout(() => { }, 0);
clearTimeout(this.timerId);
}
/**
* Call the callback after the current amount of delay time
*/
runOnce() {
this.running = true;
this.timerId = setTimeout(() => {
this.callback();
this.running = false;
}, this.nextDelay);
const nextBackoff = Math.min(this.nextDelay * this.multiplier, this.maxDelay);
const jitterMagnitude = nextBackoff * this.jitter;
this.nextDelay =
nextBackoff + uniformRandom(-jitterMagnitude, jitterMagnitude);
}
/**
* Stop the timer. The callback will not be called until `runOnce` is called
* again.
*/
stop() {
clearTimeout(this.timerId);
this.running = false;
}
/**
* Reset the delay time to its initial value.
*/
reset() {
this.nextDelay = this.initialDelay;
}
isRunning() {
return this.running;
}
}
exports.BackoffTimeout = BackoffTimeout;
//# sourceMappingURL=backoff-timeout.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"backoff-timeout.js","sourceRoot":"","sources":["../../src/backoff-timeout.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;AAEH,MAAM,kBAAkB,GAAG,IAAI,CAAC;AAChC,MAAM,kBAAkB,GAAG,GAAG,CAAC;AAC/B,MAAM,cAAc,GAAG,MAAM,CAAC;AAC9B,MAAM,cAAc,GAAG,GAAG,CAAC;AAE3B;;;;GAIG;AACH,SAAS,aAAa,CAAC,GAAW,EAAE,GAAW;IAC7C,OAAO,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,GAAG,GAAG,CAAC,GAAG,GAAG,CAAC;AAC3C,CAAC;AASD,MAAa,cAAc;IASzB,YAAoB,QAAoB,EAAE,OAAwB;QAA9C,aAAQ,GAAR,QAAQ,CAAY;QARhC,iBAAY,GAAW,kBAAkB,CAAC;QAC1C,eAAU,GAAW,kBAAkB,CAAC;QACxC,aAAQ,GAAW,cAAc,CAAC;QAClC,WAAM,GAAW,cAAc,CAAC;QAGhC,YAAO,GAAG,KAAK,CAAC;QAGtB,IAAI,O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AAC,OAAO,GAAG,KAAK,CAAC;IACvB,CAAC;IAED;;OAEG;IACH,KAAK;QACH,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,YAAY,CAAC;IACrC,CAAC;IAED,SAAS;QACP,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;CACF;AAlED,wCAkEC"}

View File

@ -0,0 +1,16 @@
import { Call } from './call-stream';
import { Channel } from './channel';
import { BaseFilter, Filter, FilterFactory } from './filter';
import { Metadata } from './metadata';
export declare class CallCredentialsFilter extends BaseFilter implements Filter {
private readonly channel;
private readonly stream;
private serviceUrl;
constructor(channel: Channel, stream: Call);
sendMetadata(metadata: Promise<Metadata>): Promise<Metadata>;
}
export declare class CallCredentialsFilterFactory implements FilterFactory<CallCredentialsFilter> {
private readonly channel;
constructor(channel: Channel);
createFilter(callStream: Call): CallCredentialsFilter;
}

View File

@ -0,0 +1,60 @@
"use strict";
/*
* Copyright 2019 gRPC authors.
*
* 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.
*
*/
Object.defineProperty(exports, "__esModule", { value: true });
const filter_1 = require("./filter");
class CallCredentialsFilter extends filter_1.BaseFilter {
constructor(channel, stream) {
super();
this.channel = channel;
this.stream = stream;
this.channel = channel;
this.stream = stream;
const splitPath = stream.getMethod().split('/');
let serviceName = '';
/* The standard path format is "/{serviceName}/{methodName}", so if we split
* by '/', the first item should be empty and the second should be the
* service name */
if (splitPath.length >= 2) {
serviceName = splitPath[1];
}
/* Currently, call credentials are only allowed on HTTPS connections, so we
* can assume that the scheme is "https" */
this.serviceUrl = `https://${stream.getHost()}/${serviceName}`;
}
async sendMetadata(metadata) {
const credentials = this.stream.getCredentials();
const credsMetadata = credentials.generateMetadata({
service_url: this.serviceUrl,
});
const resultMetadata = await metadata;
resultMetadata.merge(await credsMetadata);
return resultMetadata;
}
}
exports.CallCredentialsFilter = CallCredentialsFilter;
class CallCredentialsFilterFactory {
constructor(channel) {
this.channel = channel;
this.channel = channel;
}
createFilter(callStream) {
return new CallCredentialsFilter(this.channel, callStream);
}
}
exports.CallCredentialsFilterFactory = CallCredentialsFilterFactory;
//# sourceMappingURL=call-credentials-filter.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"call-credentials-filter.js","sourceRoot":"","sources":["../../src/call-credentials-filter.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;AAKH,qCAA6D;AAG7D,MAAa,qBAAsB,SAAQ,mBAAU;IAEnD,YACmB,OAAgB,EAChB,MAAY;QAE7B,KAAK,EAAE,CAAC;QAHS,YAAO,GAAP,OAAO,CAAS;QAChB,WAAM,GAAN,MAAM,CAAM;QAG7B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,MAAM,SAAS,GAAa,MAAM,CAAC,SAAS,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QAC1D,IAAI,WAAW,GAAG,EAAE,CAAC;QACrB;;0BAEkB;QAClB,IAAI,SAAS,CAAC,MAAM,IAAI,CAAC,EAAE;YACzB,WAAW,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC;SAC5B;QACD;mDAC2C;QAC3C,IAAI,CAAC,UAAU,GAAG,WAAW,MAAM,CAAC,OAAO,EAAE,IAAI,WAAW,EAAE,CAAC;IACjE,CAAC;IAED,KAAK,CAAC,YAAY,CAAC,QAA2B;QAC5C,MAAM,WAAW,GAAG,IAAI,CAAC,MAAM,CAAC,cAAc,EAAE,CAAC;QACjD,MAAM,aAAa,GAAG,WAAW,CAAC,gBAAgB,CAAC;YACjD,WAAW,EAAE,IAAI,CAAC,UAAU;SAC7B,CAAC,CAAC;QACH,MAAM,cAAc,GAAG,MAAM,QAAQ,CAAC;QACtC,cAAc,CAAC,KAAK,CAAC,MAAM,aAAa,CAAC,CAAC;QAC1C,OAAO,cAAc,CAAC;IACxB,CAAC;CACF;AA/BD,sDA+BC;AAED,MAAa,4BAA4B;IAEvC,YAA6B,OAAgB;QAAhB,YAAO,GAAP,OAAO,CAAS;QAC3C,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;IAED,YAAY,CAAC,UAAgB;QAC3B,OAAO,IAAI,qBAAqB,CAAC,IAAI,CAAC,OAAO,EAAE,UAAU,CAAC,CAAC;IAC7D,CAAC;CACF;AATD,oEASC"}

View File

@ -0,0 +1,39 @@
import { Metadata } from './metadata';
export interface CallMetadataOptions {
service_url: string;
}
export declare type CallMetadataGenerator = (options: CallMetadataOptions, cb: (err: Error | null, metadata?: Metadata) => void) => void;
/**
* A class that represents a generic method of adding authentication-related
* metadata on a per-request basis.
*/
export declare abstract class CallCredentials {
/**
* Asynchronously generates a new Metadata object.
* @param options Options used in generating the Metadata object.
*/
abstract generateMetadata(options: CallMetadataOptions): Promise<Metadata>;
/**
* Creates a new CallCredentials object from properties of both this and
* another CallCredentials object. This object's metadata generator will be
* called first.
* @param callCredentials The other CallCredentials object.
*/
abstract compose(callCredentials: CallCredentials): CallCredentials;
/**
* Check whether two call credentials objects are equal. Separate
* SingleCallCredentials with identical metadata generator functions are
* equal.
* @param other The other CallCredentials object to compare with.
*/
abstract _equals(other: CallCredentials): boolean;
/**
* Creates a new CallCredentials object from a given function that generates
* Metadata objects.
* @param metadataGenerator A function that accepts a set of options, and
* generates a Metadata object based on these options, which is passed back
* to the caller via a supplied (err, metadata) callback.
*/
static createFromMetadataGenerator(metadataGenerator: CallMetadataGenerator): CallCredentials;
static createEmpty(): CallCredentials;
}

View File

@ -0,0 +1,111 @@
"use strict";
/*
* Copyright 2019 gRPC authors.
*
* 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.
*
*/
Object.defineProperty(exports, "__esModule", { value: true });
const metadata_1 = require("./metadata");
/**
* A class that represents a generic method of adding authentication-related
* metadata on a per-request basis.
*/
class CallCredentials {
/**
* Creates a new CallCredentials object from a given function that generates
* Metadata objects.
* @param metadataGenerator A function that accepts a set of options, and
* generates a Metadata object based on these options, which is passed back
* to the caller via a supplied (err, metadata) callback.
*/
static createFromMetadataGenerator(metadataGenerator) {
return new SingleCallCredentials(metadataGenerator);
}
static createEmpty() {
return new EmptyCallCredentials();
}
}
exports.CallCredentials = CallCredentials;
class ComposedCallCredentials extends CallCredentials {
constructor(creds) {
super();
this.creds = creds;
}
async generateMetadata(options) {
const base = new metadata_1.Metadata();
const generated = await Promise.all(this.creds.map(cred => cred.generateMetadata(options)));
for (const gen of generated) {
base.merge(gen);
}
return base;
}
compose(other) {
return new ComposedCallCredentials(this.creds.concat([other]));
}
_equals(other) {
if (this === other) {
return true;
}
if (other instanceof ComposedCallCredentials) {
return this.creds.every((value, index) => value._equals(other.creds[index]));
}
else {
return false;
}
}
}
class SingleCallCredentials extends CallCredentials {
constructor(metadataGenerator) {
super();
this.metadataGenerator = metadataGenerator;
}
generateMetadata(options) {
return new Promise((resolve, reject) => {
this.metadataGenerator(options, (err, metadata) => {
if (metadata !== undefined) {
resolve(metadata);
}
else {
reject(err);
}
});
});
}
compose(other) {
return new ComposedCallCredentials([this, other]);
}
_equals(other) {
if (this === other) {
return true;
}
if (other instanceof SingleCallCredentials) {
return this.metadataGenerator === other.metadataGenerator;
}
else {
return false;
}
}
}
class EmptyCallCredentials extends CallCredentials {
generateMetadata(options) {
return Promise.resolve(new metadata_1.Metadata());
}
compose(other) {
return other;
}
_equals(other) {
return other instanceof EmptyCallCredentials;
}
}
//# sourceMappingURL=call-credentials.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"call-credentials.js","sourceRoot":"","sources":["../../src/call-credentials.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;AAEH,yCAAsC;AAYtC;;;GAGG;AACH,MAAsB,eAAe;IAsBnC;;;;;;OAMG;IACH,MAAM,CAAC,2BAA2B,CAChC,iBAAwC;QAExC,OAAO,IAAI,qBAAqB,CAAC,iBAAiB,CAAC,CAAC;IACtD,CAAC;IAED,MAAM,CAAC,WAAW;QAChB,OAAO,IAAI,oBAAoB,EAAE,CAAC;IACpC,CAAC;CACF;AAtCD,0CAsCC;AAED,MAAM,uBAAwB,SAAQ,eAAe;IACnD,YAAoB,KAAwB;QAC1C,KAAK,EAAE,CAAC;QADU,UAAK,GAAL,KAAK,CAAmB;IAE5C,CAAC;IAED,KAAK,CAAC,gBAAgB,CAAC,OAA4B;QACjD,MAAM,IAAI,GAAa,IAAI,mBAAQ,EAAE,CAAC;QACtC,MAAM,SAAS,GAAe,MAAM,OAAO,CAAC,GAAG,CAC7C,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC,CACvD,CAAC;QACF,KAAK,MAAM,GAAG,IAAI,SAAS,EAAE;YAC3B,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;SACjB;QACD,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO,CAAC,KAAsB;QAC5B,OAAO,IAAI,uBAAuB,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IACjE,CAAC;IAED,OAAO,CAAC,KAAsB;QAC5B,IAAI,IAAI,KAAK,KAAK,EAAE;YAClB,OAAO,IAAI,CAAC;SACb;QACD,IAAI,KAAK,YAAY,uBAAuB,EAAE;YAC5C,OAAO,IAAI,CAA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,OAAO,KAAK,CAAC;IACf,CAAC;IAED,OAAO,CAAC,KAAsB;QAC5B,OAAO,KAAK,YAAY,oBAAoB,CAAC;IAC/C,CAAC;CACF"}

101
node_modules/@grpc/grpc-js/build/src/call-stream.d.ts generated vendored Normal file
View File

@ -0,0 +1,101 @@
/// <reference types="node" />
import * as http2 from 'http2';
import { Duplex } from 'stream';
import { CallCredentials } from './call-credentials';
import { Status } from './constants';
import { EmitterAugmentation1 } from './events';
import { Filter } from './filter';
import { FilterStackFactory } from './filter-stack';
import { Metadata } from './metadata';
import { ObjectDuplex, WriteCallback } from './object-stream';
import { ChannelImplementation } from './channel';
import { Subchannel } from './subchannel';
export declare type Deadline = Date | number;
export interface CallStreamOptions {
deadline: Deadline;
flags: number;
host: string;
parentCall: Call | null;
}
export declare type PartialCallStreamOptions = Partial<CallStreamOptions>;
export interface StatusObject {
code: Status;
details: string;
metadata: Metadata;
}
export declare const enum WriteFlags {
BufferHint = 1,
NoCompress = 2,
WriteThrough = 4
}
export interface WriteObject {
message: Buffer;
flags?: number;
}
/**
* This interface represents a duplex stream associated with a single gRPC call.
*/
export declare type Call = {
cancelWithStatus(status: Status, details: string): void;
getPeer(): string;
sendMetadata(metadata: Metadata): void;
getDeadline(): Deadline;
getCredentials(): CallCredentials;
setCredentials(credentials: CallCredentials): void;
getStatus(): StatusObject | null;
getMethod(): string;
getHost(): string;
} & EmitterAugmentation1<'metadata', Metadata> & EmitterAugmentation1<'status', StatusObject> & ObjectDuplex<WriteObject, Buffer>;
export declare class Http2CallStream extends Duplex implements Call {
private readonly methodName;
private readonly channel;
private readonly options;
private readonly channelCallCredentials;
private readonly callNumber;
credentials: CallCredentials;
filterStack: Filter;
private http2Stream;
private pendingRead;
private pendingWrite;
private pendingWriteCallback;
private pendingFinalCallback;
private decoder;
private isReadFilterPending;
private canPush;
private unpushedReadMessages;
private unfilteredReadMessages;
private mappedStatusCode;
private handlingHeaders;
private handlingTrailers;
private finalStatus;
private subchannel;
private disconnectListener;
constructor(methodName: string, channel: ChannelImplementation, options: CallStreamOptions, filterStackFactory: FilterStackFactory, channelCallCredentials: CallCredentials, callNumber: number);
private trace;
push(chunk: any, encoding?: string): boolean;
/**
* On first call, emits a 'status' event with the given StatusObject.
* Subsequent calls are no-ops.
* @param status The status of the call.
*/
private endCall;
private handleFilterError;
private handleFilteredRead;
private filterReceivedMessage;
private tryPush;
private handleTrailers;
attachHttp2Stream(stream: http2.ClientHttp2Stream, subchannel: Subchannel): void;
sendMetadata(metadata: Metadata): void;
private destroyHttp2Stream;
cancelWithStatus(status: Status, details: string): void;
getDeadline(): Deadline;
getCredentials(): CallCredentials;
setCredentials(credentials: CallCredentials): void;
getStatus(): StatusObject | null;
getPeer(): string;
getMethod(): string;
getHost(): string;
_read(size: number): void;
_write(chunk: WriteObject, encoding: string, cb: WriteCallback): void;
_final(cb: Function): void;
}

426
node_modules/@grpc/grpc-js/build/src/call-stream.js generated vendored Normal file
View File

@ -0,0 +1,426 @@
"use strict";
/*
* Copyright 2019 gRPC authors.
*
* 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.
*
*/
Object.defineProperty(exports, "__esModule", { value: true });
const http2 = require("http2");
const stream_1 = require("stream");
const constants_1 = require("./constants");
const metadata_1 = require("./metadata");
const stream_decoder_1 = require("./stream-decoder");
const logging = require("./logging");
const constants_2 = require("./constants");
const TRACER_NAME = 'call_stream';
const { HTTP2_HEADER_STATUS, HTTP2_HEADER_CONTENT_TYPE, NGHTTP2_CANCEL, } = http2.constants;
class Http2CallStream extends stream_1.Duplex {
constructor(methodName, channel, options, filterStackFactory, channelCallCredentials, callNumber) {
super({ objectMode: true });
this.methodName = methodName;
this.channel = channel;
this.options = options;
this.channelCallCredentials = channelCallCredentials;
this.callNumber = callNumber;
this.http2Stream = null;
this.pendingRead = false;
this.pendingWrite = null;
this.pendingWriteCallback = null;
this.pendingFinalCallback = null;
this.decoder = new stream_decoder_1.StreamDecoder();
this.isReadFilterPending = false;
this.canPush = false;
this.unpushedReadMessages = [];
this.unfilteredReadMessages = [];
// Status code mapped from :status. To be used if grpc-status is not received
this.mappedStatusCode = constants_1.Status.UNKNOWN;
// Promise objects that are re-assigned to resolving promises when headers
// or trailers received. Processing headers/trailers is asynchronous, so we
// can use these objects to await their completion. This helps us establish
// order of precedence when obtaining the status of the call.
this.handlingHeaders = Promise.resolve();
this.handlingTrailers = Promise.resolve();
// This is populated (non-null) if and only if the call has ended
this.finalStatus = null;
this.subchannel = null;
this.filterStack = filterStackFactory.createFilter(this);
this.credentials = channelCallCredentials;
this.disconnectListener = () => {
this.endCall({
code: constants_1.Status.UNAVAILABLE,
details: 'Connection dropped',
metadata: new metadata_1.Metadata(),
});
};
}
trace(text) {
logging.trace(constants_2.LogVerbosity.DEBUG, TRACER_NAME, '[' + this.callNumber + '] ' + text);
}
// tslint:disable-next-line:no-any
push(chunk, encoding) {
this.trace('pushing to reader message of length ' +
(chunk instanceof Buffer ? chunk.length : null));
return super.push(chunk);
}
/**
* On first call, emits a 'status' event with the given StatusObject.
* Subsequent calls are no-ops.
* @param status The status of the call.
*/
endCall(status) {
if (this.finalStatus === null) {
this.trace('ended with status: code=' +
status.code +
' details="' +
status.details +
'"');
this.finalStatus = status;
/* We do this asynchronously to ensure that no async function is in the
* call stack when we return control to the application. If an async
* function is in the call stack, any exception thrown by the application
* (or our tests) will bubble up and turn into promise rejection, which
* will result in an UnhandledPromiseRejectionWarning. Because that is
* a warning, the error will be effectively swallowed and execution will
* continue */
process.nextTick(() => {
this.emit('status', status);
});
if (this.subchannel) {
this.subchannel.callUnref();
this.subchannel.removeDisconnectListener(this.disconnectListener);
}
}
}
handleFilterError(error) {
this.cancelWithStatus(constants_1.Status.INTERNAL, error.message);
}
handleFilteredRead(message) {
/* If we the call has already ended, we don't want to do anything with
* this message. Dropping it on the floor is correct behavior */
if (this.finalStatus !== null) {
return;
}
this.isReadFilterPending = false;
if (this.canPush) {
if (!this.push(message)) {
this.canPush = false;
this.http2Stream.pause();
}
}
else {
this.trace('unpushedReadMessages.push message of length ' + message.length);
this.unpushedReadMessages.push(message);
}
if (this.unfilteredReadMessages.length > 0) {
/* nextMessage is guaranteed not to be undefined because
unfilteredReadMessages is non-empty */
const nextMessage = this.unfilteredReadMessages.shift();
this.filterReceivedMessage(nextMessage);
}
}
filterReceivedMessage(framedMessage) {
/* If we the call has already ended, we don't want to do anything with
* this message. Dropping it on the floor is correct behavior */
if (this.finalStatus !== null) {
return;
}
if (framedMessage === null) {
if (this.canPush) {
this.push(null);
}
else {
this.unpushedReadMessages.push(null);
}
return;
}
this.trace('filterReceivedMessage of length ' + framedMessage.length);
this.isReadFilterPending = true;
this.filterStack
.receiveMessage(Promise.resolve(framedMessage))
.then(this.handleFilteredRead.bind(this), this.handleFilterError.bind(this));
}
tryPush(messageBytes) {
if (this.isReadFilterPending) {
this.trace('[' +
this.callNumber +
'] unfilteredReadMessages.push message of length ' +
(messageBytes && messageBytes.length));
this.unfilteredReadMessages.push(messageBytes);
}
else {
this.filterReceivedMessage(messageBytes);
}
}
handleTrailers(headers) {
this.trace('received HTTP/2 trailing headers frame');
const code = this.mappedStatusCode;
const details = '';
let metadata;
try {
metadata = metadata_1.Metadata.fromHttp2Headers(headers);
}
catch (e) {
metadata = new metadata_1.Metadata();
}
const status = { code, details, metadata };
this.handlingTrailers = (async () => {
let finalStatus;
try {
// Attempt to assign final status.
finalStatus = await this.filterStack.receiveTrailers(Promise.resolve(status));
}
catch (error) {
await this.handlingHeaders;
// This is a no-op if the call was already ended when handling headers.
this.endCall({
code: constants_1.Status.INTERNAL,
details: 'Failed to process received status',
metadata: new metadata_1.Metadata(),
});
return;
}
// It's possible that headers were received but not fully handled yet.
// Give the headers handler an opportunity to end the call first,
// if an error occurred.
await this.handlingHeaders;
// This is a no-op if the call was already ended when handling headers.
this.endCall(finalStatus);
})();
}
attachHttp2Stream(stream, subchannel) {
if (this.finalStatus !== null) {
stream.close(NGHTTP2_CANCEL);
}
else {
this.trace('attachHttp2Stream from subchannel ' + subchannel.getAddress());
this.http2Stream = stream;
this.subchannel = subchannel;
subchannel.addDisconnectListener(this.disconnectListener);
subchannel.callRef();
stream.on('response', (headers, flags) => {
this.trace('received HTTP/2 headers frame');
switch (headers[':status']) {
// TODO(murgatroid99): handle 100 and 101
case 400:
this.mappedStatusCode = constants_1.Status.INTERNAL;
break;
case 401:
this.mappedStatusCode = constants_1.Status.UNAUTHENTICATED;
break;
case 403:
this.mappedStatusCode = constants_1.Status.PERMISSION_DENIED;
break;
case 404:
this.mappedStatusCode = constants_1.Status.UNIMPLEMENTED;
break;
case 429:
case 502:
case 503:
case 504:
this.mappedStatusCode = constants_1.Status.UNAVAILABLE;
break;
default:
this.mappedStatusCode = constants_1.Status.UNKNOWN;
}
if (flags & http2.constants.NGHTTP2_FLAG_END_STREAM) {
this.handleTrailers(headers);
}
else {
let metadata;
try {
metadata = metadata_1.Metadata.fromHttp2Headers(headers);
}
catch (error) {
this.endCall({
code: constants_1.Status.UNKNOWN,
details: error.message,
metadata: new metadata_1.Metadata(),
});
return;
}
this.handlingHeaders = this.filterStack
.receiveMetadata(Promise.resolve(metadata))
.then(finalMetadata => {
this.emit('metadata', finalMetadata);
})
.catch(error => {
this.destroyHttp2Stream();
this.endCall({
code: constants_1.Status.UNKNOWN,
details: error.message,
metadata: new metadata_1.Metadata(),
});
});
}
});
stream.on('trailers', this.handleTrailers.bind(this));
stream.on('data', (data) => {
this.trace('receive HTTP/2 data frame of length ' + data.length);
const messages = this.decoder.write(data);
for (const message of messages) {
this.trace('parsed message of length ' + message.length);
this.tryPush(message);
}
});
stream.on('end', () => {
this.trace('received HTTP/2 end of data flag');
this.tryPush(null);
});
stream.on('close', async () => {
this.trace('HTTP/2 stream closed with code ' + stream.rstCode);
let code;
let details = '';
switch (stream.rstCode) {
case http2.constants.NGHTTP2_REFUSED_STREAM:
code = constants_1.Status.UNAVAILABLE;
details = 'Stream refused by server';
break;
case http2.constants.NGHTTP2_CANCEL:
code = constants_1.Status.CANCELLED;
details = 'Call cancelled';
break;
case http2.constants.NGHTTP2_ENHANCE_YOUR_CALM:
code = constants_1.Status.RESOURCE_EXHAUSTED;
details = 'Bandwidth exhausted';
break;
case http2.constants.NGHTTP2_INADEQUATE_SECURITY:
code = constants_1.Status.PERMISSION_DENIED;
details = 'Protocol not secure enough';
break;
default:
code = constants_1.Status.INTERNAL;
}
// This guarantees that if trailers were received, the value of the
// 'grpc-status' header takes precedence for emitted status data.
await this.handlingTrailers;
// This is a no-op if trailers were received at all.
// This is OK, because status codes emitted here correspond to more
// catastrophic issues that prevent us from receiving trailers in the
// first place.
this.endCall({ code, details, metadata: new metadata_1.Metadata() });
});
stream.on('error', (err) => {
/* We need an error handler here to stop "Uncaught Error" exceptions
* from bubbling up. However, errors here should all correspond to
* "close" events, where we will handle the error more granularly */
});
if (!this.pendingRead) {
stream.pause();
}
if (this.pendingWrite) {
if (!this.pendingWriteCallback) {
throw new Error('Invalid state in write handling code');
}
stream.write(this.pendingWrite, this.pendingWriteCallback);
}
if (this.pendingFinalCallback) {
this.trace('calling end() on HTTP/2 stream');
stream.end(this.pendingFinalCallback);
}
}
}
sendMetadata(metadata) {
this.trace('Sending metadata');
this.channel._startCallStream(this, metadata);
}
destroyHttp2Stream() {
// The http2 stream could already have been destroyed if cancelWithStatus
// is called in response to an internal http2 error.
if (this.http2Stream !== null && !this.http2Stream.destroyed) {
/* TODO(murgatroid99): Determine if we want to send different RST_STREAM
* codes based on the status code */
this.http2Stream.close(NGHTTP2_CANCEL);
}
}
cancelWithStatus(status, details) {
this.destroyHttp2Stream();
(async () => {
// If trailers are currently being processed, the call should be ended
// by handleTrailers instead.
await this.handlingTrailers;
this.endCall({ code: status, details, metadata: new metadata_1.Metadata() });
})();
}
getDeadline() {
return this.options.deadline;
}
getCredentials() {
return this.credentials;
}
setCredentials(credentials) {
this.credentials = this.channelCallCredentials.compose(credentials);
}
getStatus() {
return this.finalStatus;
}
getPeer() {
throw new Error('Not yet implemented');
}
getMethod() {
return this.methodName;
}
getHost() {
return this.options.host;
}
_read(size) {
/* If we have already emitted a status, we should not emit any more
* messages and we should communicate that the stream has ended */
if (this.finalStatus !== null) {
this.push(null);
return;
}
this.canPush = true;
if (this.http2Stream === null) {
this.pendingRead = true;
}
else {
while (this.unpushedReadMessages.length > 0) {
const nextMessage = this.unpushedReadMessages.shift();
this.canPush = this.push(nextMessage);
if (nextMessage === null || !this.canPush) {
this.canPush = false;
return;
}
}
/* Only resume reading from the http2Stream if we don't have any pending
* messages to emit, and we haven't gotten the signal to stop pushing
* messages */
this.http2Stream.resume();
}
}
_write(chunk, encoding, cb) {
this.trace('write() called with message of length ' + chunk.message.length);
this.filterStack.sendMessage(Promise.resolve(chunk)).then(message => {
if (this.http2Stream === null) {
this.pendingWrite = message.message;
this.pendingWriteCallback = cb;
}
else {
this.http2Stream.write(message.message, cb);
}
}, this.handleFilterError.bind(this));
}
_final(cb) {
this.trace('end() called');
if (this.http2Stream === null) {
this.pendingFinalCallback = cb;
}
else {
this.trace('calling end() on HTTP/2 stream');
this.http2Stream.end(cb);
}
}
}
exports.Http2CallStream = Http2CallStream;
//# sourceMappingURL=call-stream.js.map

File diff suppressed because one or more lines are too long

79
node_modules/@grpc/grpc-js/build/src/call.d.ts generated vendored Normal file
View File

@ -0,0 +1,79 @@
/// <reference types="node" />
import { EventEmitter } from 'events';
import { Duplex, Readable, Writable } from 'stream';
import { Call, StatusObject } from './call-stream';
import { EmitterAugmentation1 } from './events';
import { Metadata } from './metadata';
import { ObjectReadable, ObjectWritable } from './object-stream';
/**
* A type extending the built-in Error object with additional fields.
*/
export declare type ServiceError = StatusObject & Error;
/**
* A base type for all user-facing values returned by client-side method calls.
*/
export declare type SurfaceCall = {
cancel(): void;
getPeer(): string;
} & EmitterAugmentation1<'metadata', Metadata> & EmitterAugmentation1<'status', StatusObject> & EventEmitter;
/**
* A type representing the return value of a unary method call.
*/
export declare type ClientUnaryCall = SurfaceCall;
/**
* A type representing the return value of a server stream method call.
*/
export declare type ClientReadableStream<ResponseType> = {
deserialize: (chunk: Buffer) => ResponseType;
} & SurfaceCall & ObjectReadable<ResponseType>;
/**
* A type representing the return value of a client stream method call.
*/
export declare type ClientWritableStream<RequestType> = {
serialize: (value: RequestType) => Buffer;
} & SurfaceCall & ObjectWritable<RequestType>;
/**
* A type representing the return value of a bidirectional stream method call.
*/
export declare type ClientDuplexStream<RequestType, ResponseType> = ClientWritableStream<RequestType> & ClientReadableStream<ResponseType>;
/**
* Construct a ServiceError from a StatusObject. This function exists primarily
* as an attempt to make the error stack trace clearly communicate that the
* error is not necessarily a problem in gRPC itself.
* @param status
*/
export declare function callErrorFromStatus(status: StatusObject): ServiceError;
export declare class ClientUnaryCallImpl extends EventEmitter implements ClientUnaryCall {
private readonly call;
constructor(call: Call);
cancel(): void;
getPeer(): string;
}
export declare class ClientReadableStreamImpl<ResponseType> extends Readable implements ClientReadableStream<ResponseType> {
private readonly call;
readonly deserialize: (chunk: Buffer) => ResponseType;
constructor(call: Call, deserialize: (chunk: Buffer) => ResponseType);
cancel(): void;
getPeer(): string;
_read(_size: number): void;
}
export declare class ClientWritableStreamImpl<RequestType> extends Writable implements ClientWritableStream<RequestType> {
private readonly call;
readonly serialize: (value: RequestType) => Buffer;
constructor(call: Call, serialize: (value: RequestType) => Buffer);
cancel(): void;
getPeer(): string;
_write(chunk: RequestType, encoding: string, cb: Function): void;
_final(cb: Function): void;
}
export declare class ClientDuplexStreamImpl<RequestType, ResponseType> extends Duplex implements ClientDuplexStream<RequestType, ResponseType> {
private readonly call;
readonly serialize: (value: RequestType) => Buffer;
readonly deserialize: (chunk: Buffer) => ResponseType;
constructor(call: Call, serialize: (value: RequestType) => Buffer, deserialize: (chunk: Buffer) => ResponseType);
cancel(): void;
getPeer(): string;
_read(_size: number): void;
_write(chunk: RequestType, encoding: string, cb: Function): void;
_final(cb: Function): void;
}

180
node_modules/@grpc/grpc-js/build/src/call.js generated vendored Normal file
View File

@ -0,0 +1,180 @@
"use strict";
/*
* Copyright 2019 gRPC authors.
*
* 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.
*
*/
Object.defineProperty(exports, "__esModule", { value: true });
const events_1 = require("events");
const stream_1 = require("stream");
const constants_1 = require("./constants");
/**
* Construct a ServiceError from a StatusObject. This function exists primarily
* as an attempt to make the error stack trace clearly communicate that the
* error is not necessarily a problem in gRPC itself.
* @param status
*/
function callErrorFromStatus(status) {
const message = `${status.code} ${constants_1.Status[status.code]}: ${status.details}`;
return Object.assign(new Error(message), status);
}
exports.callErrorFromStatus = callErrorFromStatus;
class ClientUnaryCallImpl extends events_1.EventEmitter {
constructor(call) {
super();
this.call = call;
call.on('metadata', (metadata) => {
this.emit('metadata', metadata);
});
call.on('status', (status) => {
this.emit('status', status);
});
}
cancel() {
this.call.cancelWithStatus(constants_1.Status.CANCELLED, 'Cancelled on client');
}
getPeer() {
return this.call.getPeer();
}
}
exports.ClientUnaryCallImpl = ClientUnaryCallImpl;
function setUpReadableStream(stream, call, deserialize) {
let statusEmitted = false;
call.on('data', (data) => {
let deserialized;
try {
deserialized = deserialize(data);
}
catch (e) {
call.cancelWithStatus(constants_1.Status.INTERNAL, 'Failed to parse server response');
return;
}
if (!stream.push(deserialized)) {
call.pause();
}
});
call.on('end', () => {
if (statusEmitted) {
stream.push(null);
}
else {
call.once('status', () => {
stream.push(null);
});
}
});
call.on('status', (status) => {
if (status.code !== constants_1.Status.OK) {
stream.emit('error', callErrorFromStatus(status));
}
stream.emit('status', status);
statusEmitted = true;
});
call.pause();
}
class ClientReadableStreamImpl extends stream_1.Readable {
constructor(call, deserialize) {
super({ objectMode: true });
this.call = call;
this.deserialize = deserialize;
call.on('metadata', (metadata) => {
this.emit('metadata', metadata);
});
setUpReadableStream(this, call, deserialize);
}
cancel() {
this.call.cancelWithStatus(constants_1.Status.CANCELLED, 'Cancelled on client');
}
getPeer() {
return this.call.getPeer();
}
_read(_size) {
this.call.resume();
}
}
exports.ClientReadableStreamImpl = ClientReadableStreamImpl;
function tryWrite(call, serialize, chunk, encoding, cb) {
let message;
const flags = Number(encoding);
try {
message = serialize(chunk);
}
catch (e) {
call.cancelWithStatus(constants_1.Status.INTERNAL, 'Serialization failure');
cb(e);
return;
}
const writeObj = { message };
if (!Number.isNaN(flags)) {
writeObj.flags = flags;
}
call.write(writeObj, cb);
}
class ClientWritableStreamImpl extends stream_1.Writable {
constructor(call, serialize) {
super({ objectMode: true });
this.call = call;
this.serialize = serialize;
call.on('metadata', (metadata) => {
this.emit('metadata', metadata);
});
call.on('status', (status) => {
this.emit('status', status);
});
}
cancel() {
this.call.cancelWithStatus(constants_1.Status.CANCELLED, 'Cancelled on client');
}
getPeer() {
return this.call.getPeer();
}
_write(chunk, encoding, cb) {
tryWrite(this.call, this.serialize, chunk, encoding, cb);
}
_final(cb) {
this.call.end();
cb();
}
}
exports.ClientWritableStreamImpl = ClientWritableStreamImpl;
class ClientDuplexStreamImpl extends stream_1.Duplex {
constructor(call, serialize, deserialize) {
super({ objectMode: true });
this.call = call;
this.serialize = serialize;
this.deserialize = deserialize;
call.on('metadata', (metadata) => {
this.emit('metadata', metadata);
});
setUpReadableStream(this, call, deserialize);
}
cancel() {
this.call.cancelWithStatus(constants_1.Status.CANCELLED, 'Cancelled on client');
}
getPeer() {
return this.call.getPeer();
}
_read(_size) {
this.call.resume();
}
_write(chunk, encoding, cb) {
tryWrite(this.call, this.serialize, chunk, encoding, cb);
}
_final(cb) {
this.call.end();
cb();
}
}
exports.ClientDuplexStreamImpl = ClientDuplexStreamImpl;
//# sourceMappingURL=call.js.map

1
node_modules/@grpc/grpc-js/build/src/call.js.map generated vendored Normal file
View File

@ -0,0 +1 @@
{"version":3,"file":"call.js","sourceRoot":"","sources":["../../src/call.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;AAEH,mCAAsC;AACtC,mCAAoD;AAGpD,2CAAqC;AAiDrC;;;;;GAKG;AACH,SAAgB,mBAAmB,CAAC,MAAoB;IACtD,MAAM,OAAO,GAAG,GAAG,MAAM,CAAC,IAAI,IAAI,kBAAM,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,MAAM,CAAC,OAAO,EAAE,CAAC;IAC3E,OAAO,MAAM,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC,CAAC;AACnD,CAAC;AAHD,kDAGC;AAED,MAAa,mBAAoB,SAAQ,qBAAY;IAEnD,YAA6B,IAAU;QACrC,KAAK,EAAE,CAAC;QADmB,SAAI,GAAJ,IAAI,CAAM;QAErC,IAAI,CAAC,EAAE,CAAC,UAAU,EAAE,CAAC,QAAkB,EAAE,EAAE;YACzC,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;QAClC,CAAC,CAAC,CAAC;QACH,IAAI,CAAC,EAAE,CAAC,QAAQ,EAAE,CAAC,MAAoB,EAAE,EAAE;YACzC,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;QAC9B,CAAC,CAAC,CAAC;IACL,CAAC;IAED,MAAM;QACJ,IAAI,CAAC,IAAI,CAAC,gBAAgB,CAAC,kBAAM,CAAC,SAAS,EAAE,qBAAqB,CAAC,CAAC;IACtE,CAAC;IAED,OAAO;QACL,OAAO,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;IAC7B,CAAC;CACF;AAnBD,kDAmBC;AAED,SA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BAAW,GAAX,WAAW,CAAiC;QAGrD,IAAI,CAAC,EAAE,CAAC,UAAU,EAAE,CAAC,QAAkB,EAAE,EAAE;YACzC,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;QAClC,CAAC,CAAC,CAAC;QACH,mBAAmB,CAAe,IAAI,EAAE,IAAI,EAAE,WAAW,CAAC,CAAC;IAC7D,CAAC;IAED,MAAM;QACJ,IAAI,CAAC,IAAI,CAAC,gBAAgB,CAAC,kBAAM,CAAC,SAAS,EAAE,qBAAqB,CAAC,CAAC;IACtE,CAAC;IAED,OAAO;QACL,OAAO,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;IAC7B,CAAC;IAED,KAAK,CAAC,KAAa;QACjB,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;IACrB,CAAC;IAED,MAAM,CAAC,KAAkB,EAAE,QAAgB,EAAE,EAAY;QACvD,QAAQ,CAAc,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,SAAS,EAAE,KAAK,EAAE,QAAQ,EAAE,EAAE,CAAC,CAAC;IACxE,CAAC;IAED,MAAM,CAAC,EAAY;QACjB,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC;QAChB,EAAE,EAAE,CAAC;IACP,CAAC;CACF;AAlCD,wDAkCC"}

View File

@ -0,0 +1,79 @@
/// <reference types="node" />
import { ConnectionOptions } from 'tls';
import { CallCredentials } from './call-credentials';
/**
* A certificate as received by the checkServerIdentity callback.
*/
export interface Certificate {
/**
* The raw certificate in DER form.
*/
raw: Buffer;
}
/**
* A callback that will receive the expected hostname and presented peer
* certificate as parameters. The callback should return an error to
* indicate that the presented certificate is considered invalid and
* otherwise returned undefined.
*/
export declare type CheckServerIdentityCallback = (hostname: string, cert: Certificate) => Error | undefined;
/**
* Additional peer verification options that can be set when creating
* SSL credentials.
*/
export interface VerifyOptions {
/**
* If set, this callback will be invoked after the usual hostname verification
* has been performed on the peer certificate.
*/
checkServerIdentity?: CheckServerIdentityCallback;
}
/**
* A class that contains credentials for communicating over a channel, as well
* as a set of per-call credentials, which are applied to every method call made
* over a channel initialized with an instance of this class.
*/
export declare abstract class ChannelCredentials {
protected callCredentials: CallCredentials;
protected constructor(callCredentials?: CallCredentials);
/**
* Returns a copy of this object with the included set of per-call credentials
* expanded to include callCredentials.
* @param callCredentials A CallCredentials object to associate with this
* instance.
*/
abstract compose(callCredentials: CallCredentials): ChannelCredentials;
/**
* Gets the set of per-call credentials associated with this instance.
*/
_getCallCredentials(): CallCredentials;
/**
* Gets a SecureContext object generated from input parameters if this
* instance was created with createSsl, or null if this instance was created
* with createInsecure.
*/
abstract _getConnectionOptions(): ConnectionOptions | null;
/**
* Indicates whether this credentials object creates a secure channel.
*/
abstract _isSecure(): boolean;
/**
* Check whether two channel credentials objects are equal. Two secure
* credentials are equal if they were constructed with the same parameters.
* @param other The other ChannelCredentials Object
*/
abstract _equals(other: ChannelCredentials): boolean;
/**
* Return a new ChannelCredentials instance with a given set of credentials.
* The resulting instance can be used to construct a Channel that communicates
* over TLS.
* @param rootCerts The root certificate data.
* @param privateKey The client certificate private key, if available.
* @param certChain The client certificate key chain, if available.
*/
static createSsl(rootCerts?: Buffer | null, privateKey?: Buffer | null, certChain?: Buffer | null, verifyOptions?: VerifyOptions): ChannelCredentials;
/**
* Return a new ChannelCredentials instance with no credentials.
*/
static createInsecure(): ChannelCredentials;
}

View File

@ -0,0 +1,176 @@
"use strict";
/*
* Copyright 2019 gRPC authors.
*
* 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.
*
*/
Object.defineProperty(exports, "__esModule", { value: true });
const tls_1 = require("tls");
const call_credentials_1 = require("./call-credentials");
const tls_helpers_1 = require("./tls-helpers");
// tslint:disable-next-line:no-any
function verifyIsBufferOrNull(obj, friendlyName) {
if (obj && !(obj instanceof Buffer)) {
throw new TypeError(`${friendlyName}, if provided, must be a Buffer.`);
}
}
function bufferOrNullEqual(buf1, buf2) {
if (buf1 === null && buf2 === null) {
return true;
}
else {
return buf1 !== null && buf2 !== null && buf1.equals(buf2);
}
}
/**
* A class that contains credentials for communicating over a channel, as well
* as a set of per-call credentials, which are applied to every method call made
* over a channel initialized with an instance of this class.
*/
class ChannelCredentials {
constructor(callCredentials) {
this.callCredentials = callCredentials || call_credentials_1.CallCredentials.createEmpty();
}
/**
* Gets the set of per-call credentials associated with this instance.
*/
_getCallCredentials() {
return this.callCredentials;
}
/**
* Return a new ChannelCredentials instance with a given set of credentials.
* The resulting instance can be used to construct a Channel that communicates
* over TLS.
* @param rootCerts The root certificate data.
* @param privateKey The client certificate private key, if available.
* @param certChain The client certificate key chain, if available.
*/
static createSsl(rootCerts, privateKey, certChain, verifyOptions) {
verifyIsBufferOrNull(rootCerts, 'Root certificate');
verifyIsBufferOrNull(privateKey, 'Private key');
verifyIsBufferOrNull(certChain, 'Certificate chain');
if (privateKey && !certChain) {
throw new Error('Private key must be given with accompanying certificate chain');
}
if (!privateKey && certChain) {
throw new Error('Certificate chain must be given with accompanying private key');
}
return new SecureChannelCredentialsImpl(rootCerts || tls_helpers_1.getDefaultRootsData(), privateKey || null, certChain || null, verifyOptions || {});
}
/**
* Return a new ChannelCredentials instance with no credentials.
*/
static createInsecure() {
return new InsecureChannelCredentialsImpl();
}
}
exports.ChannelCredentials = ChannelCredentials;
class InsecureChannelCredentialsImpl extends ChannelCredentials {
constructor(callCredentials) {
super(callCredentials);
}
compose(callCredentials) {
throw new Error('Cannot compose insecure credentials');
}
_getConnectionOptions() {
return null;
}
_isSecure() {
return false;
}
_equals(other) {
return other instanceof InsecureChannelCredentialsImpl;
}
}
class SecureChannelCredentialsImpl extends ChannelCredentials {
constructor(rootCerts, privateKey, certChain, verifyOptions) {
super();
this.rootCerts = rootCerts;
this.privateKey = privateKey;
this.certChain = certChain;
this.verifyOptions = verifyOptions;
const secureContext = tls_1.createSecureContext({
ca: rootCerts || undefined,
key: privateKey || undefined,
cert: certChain || undefined,
ciphers: tls_helpers_1.CIPHER_SUITES
});
this.connectionOptions = { secureContext };
if (verifyOptions && verifyOptions.checkServerIdentity) {
this.connectionOptions.checkServerIdentity = (host, cert) => {
return verifyOptions.checkServerIdentity(host, { raw: cert.raw });
};
}
}
compose(callCredentials) {
const combinedCallCredentials = this.callCredentials.compose(callCredentials);
return new ComposedChannelCredentialsImpl(this, combinedCallCredentials);
}
_getConnectionOptions() {
return this.connectionOptions;
}
_isSecure() {
return true;
}
_equals(other) {
if (this === other) {
return true;
}
if (other instanceof SecureChannelCredentialsImpl) {
if (!bufferOrNullEqual(this.rootCerts, other.rootCerts)) {
return false;
}
if (!bufferOrNullEqual(this.privateKey, other.privateKey)) {
return false;
}
if (!bufferOrNullEqual(this.certChain, other.certChain)) {
return false;
}
return (this.verifyOptions.checkServerIdentity ===
other.verifyOptions.checkServerIdentity);
}
else {
return false;
}
}
}
class ComposedChannelCredentialsImpl extends ChannelCredentials {
constructor(channelCredentials, callCreds) {
super(callCreds);
this.channelCredentials = channelCredentials;
}
compose(callCredentials) {
const combinedCallCredentials = this.callCredentials.compose(callCredentials);
return new ComposedChannelCredentialsImpl(this.channelCredentials, combinedCallCredentials);
}
_getConnectionOptions() {
return this.channelCredentials._getConnectionOptions();
}
_isSecure() {
return true;
}
_equals(other) {
if (this === other) {
return true;
}
if (other instanceof ComposedChannelCredentialsImpl) {
return (this.channelCredentials._equals(other.channelCredentials) &&
this.callCredentials._equals(other.callCredentials));
}
else {
return false;
}
}
}
//# sourceMappingURL=channel-credentials.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"channel-credentials.js","sourceRoot":"","sources":["../../src/channel-credentials.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GA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uB,GAAG,IAAI,CAAC,eAAe,CAAC,OAAO,CAC1D,eAAe,CAChB,CAAC;QACF,OAAO,IAAI,8BAA8B,CACvC,IAAI,CAAC,kBAAkB,EACvB,uBAAuB,CACxB,CAAC;IACJ,CAAC;IAED,qBAAqB;QACnB,OAAO,IAAI,CAAC,kBAAkB,CAAC,qBAAqB,EAAE,CAAC;IACzD,CAAC;IACD,SAAS;QACP,OAAO,IAAI,CAAC;IACd,CAAC;IACD,OAAO,CAAC,KAAyB;QAC/B,IAAI,IAAI,KAAK,KAAK,EAAE;YAClB,OAAO,IAAI,CAAC;SACb;QACD,IAAI,KAAK,YAAY,8BAA8B,EAAE;YACnD,OAAO,CACL,IAAI,CAAC,kBAAkB,CAAC,OAAO,CAAC,KAAK,CAAC,kBAAkB,CAAC;gBACzD,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,KAAK,CAAC,eAAe,CAAC,CACpD,CAAC;SACH;aAAM;YACL,OAAO,KAAK,CAAC;SACd;IACH,CAAC;CACF"}

View File

@ -0,0 +1,35 @@
/**
* An interface that contains options used when initializing a Channel instance.
*/
export interface ChannelOptions {
'grpc.ssl_target_name_override'?: string;
'grpc.primary_user_agent'?: string;
'grpc.secondary_user_agent'?: string;
'grpc.default_authority'?: string;
'grpc.keepalive_time_ms'?: number;
'grpc.keepalive_timeout_ms'?: number;
'grpc.service_config'?: string;
'grpc.max_concurrent_streams'?: number;
'grpc.initial_reconnect_backoff_ms'?: number;
'grpc.max_reconnect_backoff_ms'?: number;
'grpc.use_local_subchannel_pool'?: number;
[key: string]: string | number | undefined;
}
/**
* This is for checking provided options at runtime. This is an object for
* easier membership checking.
*/
export declare const recognizedOptions: {
'grpc.ssl_target_name_override': boolean;
'grpc.primary_user_agent': boolean;
'grpc.secondary_user_agent': boolean;
'grpc.default_authority': boolean;
'grpc.keepalive_time_ms': boolean;
'grpc.keepalive_timeout_ms': boolean;
'grpc.service_config': boolean;
'grpc.max_concurrent_streams': boolean;
'grpc.initial_reconnect_backoff_ms': boolean;
'grpc.max_reconnect_backoff_ms': boolean;
'grpc.use_local_subchannel_pool': boolean;
};
export declare function channelOptionsEqual(options1: ChannelOptions, options2: ChannelOptions): boolean;

View File

@ -0,0 +1,53 @@
"use strict";
/*
* Copyright 2019 gRPC authors.
*
* 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.
*
*/
Object.defineProperty(exports, "__esModule", { value: true });
/**
* This is for checking provided options at runtime. This is an object for
* easier membership checking.
*/
exports.recognizedOptions = {
'grpc.ssl_target_name_override': true,
'grpc.primary_user_agent': true,
'grpc.secondary_user_agent': true,
'grpc.default_authority': true,
'grpc.keepalive_time_ms': true,
'grpc.keepalive_timeout_ms': true,
'grpc.service_config': true,
'grpc.max_concurrent_streams': true,
'grpc.initial_reconnect_backoff_ms': true,
'grpc.max_reconnect_backoff_ms': true,
'grpc.use_local_subchannel_pool': true,
};
function channelOptionsEqual(options1, options2) {
const keys1 = Object.keys(options1).sort();
const keys2 = Object.keys(options2).sort();
if (keys1.length !== keys2.length) {
return false;
}
for (let i = 0; i < keys1.length; i += 1) {
if (keys1[i] !== keys2[i]) {
return false;
}
if (options1[keys1[i]] !== options2[keys2[i]]) {
return false;
}
}
return true;
}
exports.channelOptionsEqual = channelOptionsEqual;
//# sourceMappingURL=channel-options.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"channel-options.js","sourceRoot":"","sources":["../../src/channel-options.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;AAoBH;;;GAGG;AACU,QAAA,iBAAiB,GAAG;IAC/B,+BAA+B,EAAE,IAAI;IACrC,yBAAyB,EAAE,IAAI;IAC/B,2BAA2B,EAAE,IAAI;IACjC,wBAAwB,EAAE,IAAI;IAC9B,wBAAwB,EAAE,IAAI;IAC9B,2BAA2B,EAAE,IAAI;IACjC,qBAAqB,EAAE,IAAI;IAC3B,6BAA6B,EAAE,IAAI;IACnC,mCAAmC,EAAE,IAAI;IACzC,+BAA+B,EAAE,IAAI;IACrC,gCAAgC,EAAE,IAAI;CACvC,CAAC;AAEF,SAAgB,mBAAmB,CACjC,QAAwB,EACxB,QAAwB;IAExB,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,IAAI,EAAE,CAAC;IAC3C,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,IAAI,EAAE,CAAC;IAC3C,IAAI,KAAK,CAAC,MAAM,KAAK,KAAK,CAAC,MAAM,EAAE;QACjC,OAAO,KAAK,CAAC;KACd;IACD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE;QACxC,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,KAAK,CAAC,CAAC,CAAC,EAAE;YACzB,OAAO,KAAK,CAAC;SACd;QACD,IAAI,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE;YAC7C,OAAO,KAAK,CAAC;SACd;KACF;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAlBD,kDAkBC"}

89
node_modules/@grpc/grpc-js/build/src/channel.d.ts generated vendored Normal file
View File

@ -0,0 +1,89 @@
import { Deadline, Call, Http2CallStream } from './call-stream';
import { ChannelCredentials } from './channel-credentials';
import { ChannelOptions } from './channel-options';
import { Metadata } from './metadata';
export declare enum ConnectivityState {
CONNECTING = 0,
READY = 1,
TRANSIENT_FAILURE = 2,
IDLE = 3,
SHUTDOWN = 4
}
/**
* An interface that represents a communication channel to a server specified
* by a given address.
*/
export interface Channel {
/**
* Close the channel. This has the same functionality as the existing
* grpc.Client.prototype.close
*/
close(): void;
/**
* Return the target that this channel connects to
*/
getTarget(): string;
/**
* Get the channel's current connectivity state. This method is here mainly
* because it is in the existing internal Channel class, and there isn't
* another good place to put it.
* @param tryToConnect If true, the channel will start connecting if it is
* idle. Otherwise, idle channels will only start connecting when a
* call starts.
*/
getConnectivityState(tryToConnect: boolean): ConnectivityState;
/**
* Watch for connectivity state changes. This is also here mainly because
* it is in the existing external Channel class.
* @param currentState The state to watch for transitions from. This should
* always be populated by calling getConnectivityState immediately
* before.
* @param deadline A deadline for waiting for a state change
* @param callback Called with no error when a state change, or with an
* error if the deadline passes without a state change.
*/
watchConnectivityState(currentState: ConnectivityState, deadline: Date | number, callback: (error?: Error) => void): void;
/**
* Create a call object. Call is an opaque type that is used by the Client
* class. This function is called by the gRPC library when starting a
* request. Implementers should return an instance of Call that is returned
* from calling createCall on an instance of the provided Channel class.
* @param method The full method string to request.
* @param deadline The call deadline
* @param host A host string override for making the request
* @param parentCall A server call to propagate some information from
* @param propagateFlags A bitwise combination of elements of grpc.propagate
* that indicates what information to propagate from parentCall.
*/
createCall(method: string, deadline: Deadline | null | undefined, host: string | null | undefined, parentCall: Call | null | undefined, propagateFlags: number | null | undefined): Call;
}
export declare class ChannelImplementation implements Channel {
private target;
private readonly credentials;
private readonly options;
private resolvingLoadBalancer;
private subchannelPool;
private connectivityState;
private currentPicker;
private pickQueue;
private connectivityStateWatchers;
private defaultAuthority;
private filterStackFactory;
constructor(target: string, credentials: ChannelCredentials, options: ChannelOptions);
/**
* Check the picker output for the given call and corresponding metadata,
* and take any relevant actions. Should not be called while iterating
* over pickQueue.
* @param callStream
* @param callMetadata
*/
private tryPick;
private removeConnectivityStateWatcher;
private updateState;
_startCallStream(stream: Http2CallStream, metadata: Metadata): void;
close(): void;
getTarget(): string;
getConnectivityState(tryToConnect: boolean): ConnectivityState;
watchConnectivityState(currentState: ConnectivityState, deadline: Date | number, callback: (error?: Error) => void): void;
createCall(method: string, deadline: Deadline | null | undefined, host: string | null | undefined, parentCall: Call | null | undefined, propagateFlags: number | null | undefined): Call;
}

237
node_modules/@grpc/grpc-js/build/src/channel.js generated vendored Normal file
View File

@ -0,0 +1,237 @@
"use strict";
/*
* Copyright 2019 gRPC authors.
*
* 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.
*
*/
Object.defineProperty(exports, "__esModule", { value: true });
const call_stream_1 = require("./call-stream");
const resolving_load_balancer_1 = require("./resolving-load-balancer");
const subchannel_pool_1 = require("./subchannel-pool");
const picker_1 = require("./picker");
const constants_1 = require("./constants");
const filter_stack_1 = require("./filter-stack");
const call_credentials_filter_1 = require("./call-credentials-filter");
const deadline_filter_1 = require("./deadline-filter");
const metadata_status_filter_1 = require("./metadata-status-filter");
const compression_filter_1 = require("./compression-filter");
const resolver_1 = require("./resolver");
const service_config_1 = require("./service-config");
const logging_1 = require("./logging");
var ConnectivityState;
(function (ConnectivityState) {
ConnectivityState[ConnectivityState["CONNECTING"] = 0] = "CONNECTING";
ConnectivityState[ConnectivityState["READY"] = 1] = "READY";
ConnectivityState[ConnectivityState["TRANSIENT_FAILURE"] = 2] = "TRANSIENT_FAILURE";
ConnectivityState[ConnectivityState["IDLE"] = 3] = "IDLE";
ConnectivityState[ConnectivityState["SHUTDOWN"] = 4] = "SHUTDOWN";
})(ConnectivityState = exports.ConnectivityState || (exports.ConnectivityState = {}));
let nextCallNumber = 0;
function getNewCallNumber() {
const callNumber = nextCallNumber;
nextCallNumber += 1;
if (nextCallNumber >= Number.MAX_SAFE_INTEGER) {
nextCallNumber = 0;
}
return callNumber;
}
class ChannelImplementation {
constructor(target, credentials, options) {
var _a;
this.target = target;
this.credentials = credentials;
this.options = options;
this.connectivityState = ConnectivityState.IDLE;
this.currentPicker = new picker_1.UnavailablePicker();
this.pickQueue = [];
this.connectivityStateWatchers = [];
/* The global boolean parameter to getSubchannelPool has the inverse meaning to what
* the grpc.use_local_subchannel_pool channel option means. */
this.subchannelPool = subchannel_pool_1.getSubchannelPool((_a = options['grpc.use_local_subchannel_pool'], (_a !== null && _a !== void 0 ? _a : 0)) === 0);
const channelControlHelper = {
createSubchannel: (subchannelAddress, subchannelArgs) => {
return this.subchannelPool.getOrCreateSubchannel(this.target, subchannelAddress, Object.assign({}, this.options, subchannelArgs), this.credentials);
},
updateState: (connectivityState, picker) => {
this.currentPicker = picker;
const queueCopy = this.pickQueue.slice();
this.pickQueue = [];
for (const { callStream, callMetadata } of queueCopy) {
this.tryPick(callStream, callMetadata);
}
this.updateState(connectivityState);
},
requestReresolution: () => {
// This should never be called.
throw new Error('Resolving load balancer should never call requestReresolution');
},
};
// TODO(murgatroid99): check channel arg for default service config
let defaultServiceConfig = {
loadBalancingConfig: [],
methodConfig: [],
};
if (options['grpc.service_config']) {
defaultServiceConfig = service_config_1.validateServiceConfig(JSON.parse(options['grpc.service_config']));
}
this.resolvingLoadBalancer = new resolving_load_balancer_1.ResolvingLoadBalancer(target, channelControlHelper, defaultServiceConfig);
this.filterStackFactory = new filter_stack_1.FilterStackFactory([
new call_credentials_filter_1.CallCredentialsFilterFactory(this),
new deadline_filter_1.DeadlineFilterFactory(this),
new metadata_status_filter_1.MetadataStatusFilterFactory(this),
new compression_filter_1.CompressionFilterFactory(this),
]);
// TODO(murgatroid99): Add more centralized handling of channel options
if (this.options['grpc.default_authority']) {
this.defaultAuthority = this.options['grpc.default_authority'];
}
else {
this.defaultAuthority = resolver_1.getDefaultAuthority(target);
}
}
/**
* Check the picker output for the given call and corresponding metadata,
* and take any relevant actions. Should not be called while iterating
* over pickQueue.
* @param callStream
* @param callMetadata
*/
tryPick(callStream, callMetadata) {
const pickResult = this.currentPicker.pick({ metadata: callMetadata });
switch (pickResult.pickResultType) {
case picker_1.PickResultType.COMPLETE:
if (pickResult.subchannel === null) {
callStream.cancelWithStatus(constants_1.Status.UNAVAILABLE, 'Request dropped by load balancing policy');
// End the call with an error
}
else {
/* If the subchannel disconnects between calling pick and getting
* the filter stack metadata, the call will end with an error. */
callStream.filterStack
.sendMetadata(Promise.resolve(callMetadata))
.then(finalMetadata => {
if (pickResult.subchannel.getConnectivityState() ===
ConnectivityState.READY) {
try {
pickResult.subchannel.startCallStream(finalMetadata, callStream);
}
catch (error) {
callStream.cancelWithStatus(constants_1.Status.UNAVAILABLE, 'Failed to start call on picked subchannel');
}
}
else {
callStream.cancelWithStatus(constants_1.Status.UNAVAILABLE, 'Connection dropped while starting call');
}
}, (error) => {
// We assume the error code isn't 0 (Status.OK)
callStream.cancelWithStatus(error.code || constants_1.Status.UNKNOWN, `Getting metadata from plugin failed with error: ${error.message}`);
});
}
break;
case picker_1.PickResultType.QUEUE:
this.pickQueue.push({ callStream, callMetadata });
break;
case picker_1.PickResultType.TRANSIENT_FAILURE:
if (callMetadata.getOptions().waitForReady) {
this.pickQueue.push({ callStream, callMetadata });
}
else {
callStream.cancelWithStatus(pickResult.status.code, pickResult.status.details);
}
break;
default:
throw new Error(`Invalid state: unknown pickResultType ${pickResult.pickResultType}`);
}
}
removeConnectivityStateWatcher(watcherObject) {
const watcherIndex = this.connectivityStateWatchers.findIndex(value => value === watcherObject);
if (watcherIndex >= 0) {
this.connectivityStateWatchers.splice(watcherIndex, 1);
}
}
updateState(newState) {
logging_1.trace(constants_1.LogVerbosity.DEBUG, 'connectivity_state', this.target +
' ' +
ConnectivityState[this.connectivityState] +
' -> ' +
ConnectivityState[newState]);
this.connectivityState = newState;
const watchersCopy = this.connectivityStateWatchers.slice();
for (const watcherObject of watchersCopy) {
if (newState !== watcherObject.currentState) {
watcherObject.callback();
clearTimeout(watcherObject.timer);
this.removeConnectivityStateWatcher(watcherObject);
}
}
}
_startCallStream(stream, metadata) {
this.tryPick(stream, metadata.clone());
}
close() {
this.resolvingLoadBalancer.destroy();
this.updateState(ConnectivityState.SHUTDOWN);
this.subchannelPool.unrefUnusedSubchannels();
}
getTarget() {
return this.target;
}
getConnectivityState(tryToConnect) {
const connectivityState = this.connectivityState;
if (tryToConnect) {
this.resolvingLoadBalancer.exitIdle();
}
return connectivityState;
}
watchConnectivityState(currentState, deadline, callback) {
const deadlineDate = deadline instanceof Date ? deadline : new Date(deadline);
const now = new Date();
if (deadlineDate <= now) {
process.nextTick(callback, new Error('Deadline passed without connectivity state change'));
return;
}
const watcherObject = {
currentState,
callback,
timer: setTimeout(() => {
this.removeConnectivityStateWatcher(watcherObject);
callback(new Error('Deadline passed without connectivity state change'));
}, deadlineDate.getTime() - now.getTime()),
};
this.connectivityStateWatchers.push(watcherObject);
}
createCall(method, deadline, host, parentCall, propagateFlags) {
if (this.connectivityState === ConnectivityState.SHUTDOWN) {
throw new Error('Channel has been shut down');
}
const callNumber = getNewCallNumber();
logging_1.trace(constants_1.LogVerbosity.DEBUG, 'channel', this.target +
' createCall [' +
callNumber +
'] method="' +
method +
'", deadline=' +
deadline);
const finalOptions = {
deadline: deadline === null || deadline === undefined ? Infinity : deadline,
flags: propagateFlags || 0,
host: host || this.defaultAuthority,
parentCall: parentCall || null,
};
const stream = new call_stream_1.Http2CallStream(method, this, finalOptions, this.filterStackFactory, this.credentials._getCallCredentials(), callNumber);
return stream;
}
}
exports.ChannelImplementation = ChannelImplementation;
//# sourceMappingURL=channel.js.map

1
node_modules/@grpc/grpc-js/build/src/channel.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,111 @@
import { Metadata } from './metadata';
import { Listener, MetadataListener, MessageListener, StatusListener, InterceptingListener, MessageContext } from './call-stream';
import { Status } from './constants';
import { Channel } from './channel';
import { CallOptions } from './client';
import { CallCredentials } from './call-credentials';
import { ClientMethodDefinition } from './make-client';
/**
* Error class associated with passing both interceptors and interceptor
* providers to a client constructor or as call options.
*/
export declare class InterceptorConfigurationError extends Error {
constructor(message: string);
}
export interface MetadataRequester {
(metadata: Metadata, listener: InterceptingListener, next: (metadata: Metadata, listener: InterceptingListener | Listener) => void): void;
}
export interface MessageRequester {
(message: any, next: (message: any) => void): void;
}
export interface CloseRequester {
(next: () => void): void;
}
export interface CancelRequester {
(next: () => void): void;
}
/**
* An object with methods for intercepting and modifying outgoing call operations.
*/
export interface FullRequester {
start: MetadataRequester;
sendMessage: MessageRequester;
halfClose: CloseRequester;
cancel: CancelRequester;
}
export declare type Requester = Partial<FullRequester>;
export declare class ListenerBuilder {
private metadata;
private message;
private status;
withOnReceiveMetadata(onReceiveMetadata: MetadataListener): this;
withOnReceiveMessage(onReceiveMessage: MessageListener): this;
withOnReceiveStatus(onReceiveStatus: StatusListener): this;
build(): Listener;
}
export declare class RequesterBuilder {
private start;
private message;
private halfClose;
private cancel;
withStart(start: MetadataRequester): this;
withSendMessage(sendMessage: MessageRequester): this;
withHalfClose(halfClose: CloseRequester): this;
withCancel(cancel: CancelRequester): this;
build(): Requester;
}
export interface InterceptorOptions extends CallOptions {
method_definition: ClientMethodDefinition<any, any>;
}
export interface InterceptingCallInterface {
cancelWithStatus(status: Status, details: string): void;
getPeer(): string;
start(metadata: Metadata, listener?: Partial<InterceptingListener>): void;
sendMessageWithContext(context: MessageContext, message: any): void;
sendMessage(message: any): void;
startRead(): void;
halfClose(): void;
setCredentials(credentials: CallCredentials): void;
}
export declare class InterceptingCall implements InterceptingCallInterface {
private nextCall;
/**
* The requester that this InterceptingCall uses to modify outgoing operations
*/
private requester;
/**
* Indicates that a message has been passed to the listener's onReceiveMessage
* method it has not been passed to the corresponding next callback
*/
private processingMessage;
/**
* Indicates that a status was received but could not be propagated because
* a message was still being processed.
*/
private pendingHalfClose;
constructor(nextCall: InterceptingCallInterface, requester?: Requester);
cancelWithStatus(status: Status, details: string): void;
getPeer(): string;
start(metadata: Metadata, interceptingListener?: Partial<InterceptingListener>): void;
sendMessageWithContext(context: MessageContext, message: any): void;
sendMessage(message: any): void;
startRead(): void;
halfClose(): void;
setCredentials(credentials: CallCredentials): void;
}
export interface NextCall {
(options: InterceptorOptions): InterceptingCallInterface;
}
export interface Interceptor {
(options: InterceptorOptions, nextCall: NextCall): InterceptingCall;
}
export interface InterceptorProvider {
(methodDefinition: ClientMethodDefinition<any, any>): Interceptor;
}
export interface InterceptorArguments {
clientInterceptors: Interceptor[];
clientInterceptorProviders: InterceptorProvider[];
callInterceptors: Interceptor[];
callInterceptorProviders: InterceptorProvider[];
}
export declare function getInterceptingCall(interceptorArgs: InterceptorArguments, methodDefinition: ClientMethodDefinition<any, any>, options: CallOptions, channel: Channel): InterceptingCallInterface;

View File

@ -0,0 +1,406 @@
"use strict";
/*
* Copyright 2019 gRPC authors.
*
* 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.
*
*/
Object.defineProperty(exports, "__esModule", { value: true });
const metadata_1 = require("./metadata");
const call_stream_1 = require("./call-stream");
const constants_1 = require("./constants");
/**
* Error class associated with passing both interceptors and interceptor
* providers to a client constructor or as call options.
*/
class InterceptorConfigurationError extends Error {
constructor(message) {
super(message);
this.name = 'InterceptorConfigurationError';
Error.captureStackTrace(this, InterceptorConfigurationError);
}
}
exports.InterceptorConfigurationError = InterceptorConfigurationError;
class ListenerBuilder {
constructor() {
this.metadata = undefined;
this.message = undefined;
this.status = undefined;
}
withOnReceiveMetadata(onReceiveMetadata) {
this.metadata = onReceiveMetadata;
return this;
}
withOnReceiveMessage(onReceiveMessage) {
this.message = onReceiveMessage;
return this;
}
withOnReceiveStatus(onReceiveStatus) {
this.status = onReceiveStatus;
return this;
}
build() {
return {
onReceiveMetadata: this.metadata,
onReceiveMessage: this.message,
onReceiveStatus: this.status,
};
}
}
exports.ListenerBuilder = ListenerBuilder;
class RequesterBuilder {
constructor() {
this.start = undefined;
this.message = undefined;
this.halfClose = undefined;
this.cancel = undefined;
}
withStart(start) {
this.start = start;
return this;
}
withSendMessage(sendMessage) {
this.message = sendMessage;
return this;
}
withHalfClose(halfClose) {
this.halfClose = halfClose;
return this;
}
withCancel(cancel) {
this.cancel = cancel;
return this;
}
build() {
return {
start: this.start,
sendMessage: this.message,
halfClose: this.halfClose,
cancel: this.cancel,
};
}
}
exports.RequesterBuilder = RequesterBuilder;
/**
* A Listener with a default pass-through implementation of each method. Used
* for filling out Listeners with some methods omitted.
*/
const defaultListener = {
onReceiveMetadata: (metadata, next) => {
next(metadata);
},
onReceiveMessage: (message, next) => {
next(message);
},
onReceiveStatus: (status, next) => {
next(status);
},
};
/**
* A Requester with a default pass-through implementation of each method. Used
* for filling out Requesters with some methods omitted.
*/
const defaultRequester = {
start: (metadata, listener, next) => {
next(metadata, listener);
},
sendMessage: (message, next) => {
next(message);
},
halfClose: next => {
next();
},
cancel: next => {
next();
},
};
class InterceptingCall {
constructor(nextCall, requester) {
var _a, _b, _c, _d;
this.nextCall = nextCall;
/**
* Indicates that a message has been passed to the listener's onReceiveMessage
* method it has not been passed to the corresponding next callback
*/
this.processingMessage = false;
/**
* Indicates that a status was received but could not be propagated because
* a message was still being processed.
*/
this.pendingHalfClose = false;
if (requester) {
this.requester = {
start: (_a = requester.start, (_a !== null && _a !== void 0 ? _a : defaultRequester.start)),
sendMessage: (_b = requester.sendMessage, (_b !== null && _b !== void 0 ? _b : defaultRequester.sendMessage)),
halfClose: (_c = requester.halfClose, (_c !== null && _c !== void 0 ? _c : defaultRequester.halfClose)),
cancel: (_d = requester.cancel, (_d !== null && _d !== void 0 ? _d : defaultRequester.cancel)),
};
}
else {
this.requester = defaultRequester;
}
}
cancelWithStatus(status, details) {
this.requester.cancel(() => {
this.nextCall.cancelWithStatus(status, details);
});
}
getPeer() {
return this.nextCall.getPeer();
}
start(metadata, interceptingListener) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j;
const fullInterceptingListener = {
onReceiveMetadata: (_c = (_b = (_a = interceptingListener) === null || _a === void 0 ? void 0 : _a.onReceiveMetadata) === null || _b === void 0 ? void 0 : _b.bind(interceptingListener), (_c !== null && _c !== void 0 ? _c : (metadata => { }))),
onReceiveMessage: (_f = (_e = (_d = interceptingListener) === null || _d === void 0 ? void 0 : _d.onReceiveMessage) === null || _e === void 0 ? void 0 : _e.bind(interceptingListener), (_f !== null && _f !== void 0 ? _f : (message => { }))),
onReceiveStatus: (_j = (_h = (_g = interceptingListener) === null || _g === void 0 ? void 0 : _g.onReceiveStatus) === null || _h === void 0 ? void 0 : _h.bind(interceptingListener), (_j !== null && _j !== void 0 ? _j : (status => { }))),
};
this.requester.start(metadata, fullInterceptingListener, (md, listener) => {
var _a, _b, _c;
let finalInterceptingListener;
if (call_stream_1.isInterceptingListener(listener)) {
finalInterceptingListener = listener;
}
else {
const fullListener = {
onReceiveMetadata: (_a = listener.onReceiveMetadata, (_a !== null && _a !== void 0 ? _a : defaultListener.onReceiveMetadata)),
onReceiveMessage: (_b = listener.onReceiveMessage, (_b !== null && _b !== void 0 ? _b : defaultListener.onReceiveMessage)),
onReceiveStatus: (_c = listener.onReceiveStatus, (_c !== null && _c !== void 0 ? _c : defaultListener.onReceiveStatus)),
};
finalInterceptingListener = new call_stream_1.InterceptingListenerImpl(fullListener, fullInterceptingListener);
}
this.nextCall.start(md, finalInterceptingListener);
});
}
// tslint:disable-next-line no-any
sendMessageWithContext(context, message) {
this.processingMessage = true;
this.requester.sendMessage(message, finalMessage => {
this.processingMessage = false;
this.nextCall.sendMessageWithContext(context, finalMessage);
if (this.pendingHalfClose) {
this.nextCall.halfClose();
}
});
}
// tslint:disable-next-line no-any
sendMessage(message) {
this.sendMessageWithContext({}, message);
}
startRead() {
this.nextCall.startRead();
}
halfClose() {
this.requester.halfClose(() => {
if (this.processingMessage) {
this.pendingHalfClose = true;
}
else {
this.nextCall.halfClose();
}
});
}
setCredentials(credentials) {
this.nextCall.setCredentials(credentials);
}
}
exports.InterceptingCall = InterceptingCall;
function getCall(channel, path, options) {
let deadline;
let host;
const parent = null;
let propagateFlags;
let credentials;
if (options) {
deadline = options.deadline;
host = options.host;
propagateFlags = options.propagate_flags;
credentials = options.credentials;
}
if (deadline === undefined) {
deadline = Infinity;
}
const call = channel.createCall(path, deadline, host, parent, propagateFlags);
if (credentials) {
call.setCredentials(credentials);
}
return call;
}
/**
* InterceptingCall implementation that directly owns the underlying Call
* object and handles serialization and deseraizliation.
*/
class BaseInterceptingCall {
// tslint:disable-next-line no-any
constructor(call, methodDefinition) {
this.call = call;
this.methodDefinition = methodDefinition;
}
cancelWithStatus(status, details) {
this.call.cancelWithStatus(status, details);
}
getPeer() {
return this.call.getPeer();
}
setCredentials(credentials) {
this.call.setCredentials(credentials);
}
// tslint:disable-next-line no-any
sendMessageWithContext(context, message) {
let serialized;
try {
serialized = this.methodDefinition.requestSerialize(message);
this.call.sendMessageWithContext(context, serialized);
}
catch (e) {
this.call.cancelWithStatus(constants_1.Status.INTERNAL, 'Serialization failure');
}
}
// tslint:disable-next-line no-any
sendMessage(message) {
this.sendMessageWithContext({}, message);
}
start(metadata, interceptingListener) {
let readError = null;
this.call.start(metadata, {
onReceiveMetadata: metadata => {
var _a, _b, _c;
(_c = (_a = interceptingListener) === null || _a === void 0 ? void 0 : (_b = _a).onReceiveMetadata) === null || _c === void 0 ? void 0 : _c.call(_b, metadata);
},
onReceiveMessage: message => {
var _a, _b, _c;
// tslint:disable-next-line no-any
let deserialized;
try {
deserialized = this.methodDefinition.responseDeserialize(message);
(_c = (_a = interceptingListener) === null || _a === void 0 ? void 0 : (_b = _a).onReceiveMessage) === null || _c === void 0 ? void 0 : _c.call(_b, deserialized);
}
catch (e) {
readError = {
code: constants_1.Status.INTERNAL,
details: 'Failed to parse server response',
metadata: new metadata_1.Metadata(),
};
this.call.cancelWithStatus(readError.code, readError.details);
}
},
onReceiveStatus: status => {
var _a, _b, _c, _d, _e, _f;
if (readError) {
(_c = (_a = interceptingListener) === null || _a === void 0 ? void 0 : (_b = _a).onReceiveStatus) === null || _c === void 0 ? void 0 : _c.call(_b, readError);
}
else {
(_f = (_d = interceptingListener) === null || _d === void 0 ? void 0 : (_e = _d).onReceiveStatus) === null || _f === void 0 ? void 0 : _f.call(_e, status);
}
},
});
}
startRead() {
this.call.startRead();
}
halfClose() {
this.call.halfClose();
}
}
/**
* BaseInterceptingCall with special-cased behavior for methods with unary
* responses.
*/
class BaseUnaryInterceptingCall extends BaseInterceptingCall {
// tslint:disable-next-line no-any
constructor(call, methodDefinition) {
super(call, methodDefinition);
}
start(metadata, listener) {
var _a, _b, _c;
let receivedMessage = false;
const wrapperListener = {
onReceiveMetadata: (_c = (_b = (_a = listener) === null || _a === void 0 ? void 0 : _a.onReceiveMetadata) === null || _b === void 0 ? void 0 : _b.bind(listener), (_c !== null && _c !== void 0 ? _c : (metadata => { }))),
// tslint:disable-next-line no-any
onReceiveMessage: (message) => {
var _a, _b, _c;
receivedMessage = true;
(_c = (_a = listener) === null || _a === void 0 ? void 0 : (_b = _a).onReceiveMessage) === null || _c === void 0 ? void 0 : _c.call(_b, message);
},
onReceiveStatus: (status) => {
var _a, _b, _c, _d, _e, _f;
if (!receivedMessage) {
(_c = (_a = listener) === null || _a === void 0 ? void 0 : (_b = _a).onReceiveMessage) === null || _c === void 0 ? void 0 : _c.call(_b, null);
}
(_f = (_d = listener) === null || _d === void 0 ? void 0 : (_e = _d).onReceiveStatus) === null || _f === void 0 ? void 0 : _f.call(_e, status);
},
};
super.start(metadata, wrapperListener);
this.call.startRead();
}
}
/**
* BaseInterceptingCall with special-cased behavior for methods with streaming
* responses.
*/
class BaseStreamingInterceptingCall extends BaseInterceptingCall {
}
// tslint:disable-next-line no-any
function getBottomInterceptingCall(channel, path, options, methodDefinition) {
const call = getCall(channel, path, options);
if (methodDefinition.responseStream) {
return new BaseStreamingInterceptingCall(call, methodDefinition);
}
else {
return new BaseUnaryInterceptingCall(call, methodDefinition);
}
}
// tslint:disable-next-line no-any
function getInterceptingCall(interceptorArgs, methodDefinition, options, channel) {
if (interceptorArgs.clientInterceptors.length > 0 &&
interceptorArgs.clientInterceptorProviders.length > 0) {
throw new InterceptorConfigurationError('Both interceptors and interceptor_providers were passed as options ' +
'to the client constructor. Only one of these is allowed.');
}
if (interceptorArgs.callInterceptors.length > 0 &&
interceptorArgs.callInterceptorProviders.length > 0) {
throw new InterceptorConfigurationError('Both interceptors and interceptor_providers were passed as call ' +
'options. Only one of these is allowed.');
}
let interceptors = [];
// Interceptors passed to the call override interceptors passed to the client constructor
if (interceptorArgs.callInterceptors.length > 0 ||
interceptorArgs.callInterceptorProviders.length > 0) {
interceptors = []
.concat(interceptorArgs.callInterceptors, interceptorArgs.callInterceptorProviders.map(provider => provider(methodDefinition)))
.filter(interceptor => interceptor);
// Filter out falsy values when providers return nothing
}
else {
interceptors = []
.concat(interceptorArgs.clientInterceptors, interceptorArgs.clientInterceptorProviders.map(provider => provider(methodDefinition)))
.filter(interceptor => interceptor);
// Filter out falsy values when providers return nothing
}
const interceptorOptions = Object.assign({}, options, {
method_definition: methodDefinition,
});
/* For each interceptor in the list, the nextCall function passed to it is
* based on the next interceptor in the list, using a nextCall function
* constructed with the following interceptor in the list, and so on. The
* initialValue, which is effectively at the end of the list, is a nextCall
* function that invokes getBottomInterceptingCall, the result of which
* handles (de)serialization and also gets the underlying call from the
* channel. */
const getCall = interceptors.reduceRight((nextCall, nextInterceptor) => {
return currentOptions => nextInterceptor(currentOptions, nextCall);
}, (finalOptions) => getBottomInterceptingCall(channel, methodDefinition.path, finalOptions, methodDefinition));
return getCall(interceptorOptions);
}
exports.getInterceptingCall = getInterceptingCall;
//# sourceMappingURL=client-interceptors.js.map

File diff suppressed because one or more lines are too long

49
node_modules/@grpc/grpc-js/build/src/client.d.ts generated vendored Normal file
View File

@ -0,0 +1,49 @@
/// <reference types="node" />
import { ClientDuplexStream, ClientReadableStream, ClientUnaryCall, ClientWritableStream, ServiceError } from './call';
import { CallCredentials } from './call-credentials';
import { Deadline } from './call-stream';
import { Channel } from './channel';
import { ChannelCredentials } from './channel-credentials';
import { ChannelOptions } from './channel-options';
import { Metadata } from './metadata';
declare const CHANNEL_SYMBOL: unique symbol;
export interface UnaryCallback<ResponseType> {
(err: ServiceError | null, value?: ResponseType): void;
}
export interface CallOptions {
deadline?: Deadline;
host?: string;
propagate_flags?: number;
credentials?: CallCredentials;
}
export declare type ClientOptions = Partial<ChannelOptions> & {
channelOverride?: Channel;
channelFactoryOverride?: (address: string, credentials: ChannelCredentials, options: ClientOptions) => Channel;
};
/**
* A generic gRPC client. Primarily useful as a base class for all generated
* clients.
*/
export declare class Client {
private readonly [CHANNEL_SYMBOL];
constructor(address: string, credentials: ChannelCredentials, options?: ClientOptions);
close(): void;
getChannel(): Channel;
waitForReady(deadline: Deadline, callback: (error?: Error) => void): void;
private handleUnaryResponse;
private checkOptionalUnaryResponseArguments;
makeUnaryRequest<RequestType, ResponseType>(method: string, serialize: (value: RequestType) => Buffer, deserialize: (value: Buffer) => ResponseType, argument: RequestType, metadata: Metadata, options: CallOptions, callback: UnaryCallback<ResponseType>): ClientUnaryCall;
makeUnaryRequest<RequestType, ResponseType>(method: string, serialize: (value: RequestType) => Buffer, deserialize: (value: Buffer) => ResponseType, argument: RequestType, metadata: Metadata, callback: UnaryCallback<ResponseType>): ClientUnaryCall;
makeUnaryRequest<RequestType, ResponseType>(method: string, serialize: (value: RequestType) => Buffer, deserialize: (value: Buffer) => ResponseType, argument: RequestType, options: CallOptions, callback: UnaryCallback<ResponseType>): ClientUnaryCall;
makeUnaryRequest<RequestType, ResponseType>(method: string, serialize: (value: RequestType) => Buffer, deserialize: (value: Buffer) => ResponseType, argument: RequestType, callback: UnaryCallback<ResponseType>): ClientUnaryCall;
makeClientStreamRequest<RequestType, ResponseType>(method: string, serialize: (value: RequestType) => Buffer, deserialize: (value: Buffer) => ResponseType, metadata: Metadata, options: CallOptions, callback: UnaryCallback<ResponseType>): ClientWritableStream<RequestType>;
makeClientStreamRequest<RequestType, ResponseType>(method: string, serialize: (value: RequestType) => Buffer, deserialize: (value: Buffer) => ResponseType, metadata: Metadata, callback: UnaryCallback<ResponseType>): ClientWritableStream<RequestType>;
makeClientStreamRequest<RequestType, ResponseType>(method: string, serialize: (value: RequestType) => Buffer, deserialize: (value: Buffer) => ResponseType, options: CallOptions, callback: UnaryCallback<ResponseType>): ClientWritableStream<RequestType>;
makeClientStreamRequest<RequestType, ResponseType>(method: string, serialize: (value: RequestType) => Buffer, deserialize: (value: Buffer) => ResponseType, callback: UnaryCallback<ResponseType>): ClientWritableStream<RequestType>;
private checkMetadataAndOptions;
makeServerStreamRequest<RequestType, ResponseType>(method: string, serialize: (value: RequestType) => Buffer, deserialize: (value: Buffer) => ResponseType, argument: RequestType, metadata: Metadata, options?: CallOptions): ClientReadableStream<ResponseType>;
makeServerStreamRequest<RequestType, ResponseType>(method: string, serialize: (value: RequestType) => Buffer, deserialize: (value: Buffer) => ResponseType, argument: RequestType, options?: CallOptions): ClientReadableStream<ResponseType>;
makeBidiStreamRequest<RequestType, ResponseType>(method: string, serialize: (value: RequestType) => Buffer, deserialize: (value: Buffer) => ResponseType, metadata: Metadata, options?: CallOptions): ClientDuplexStream<RequestType, ResponseType>;
makeBidiStreamRequest<RequestType, ResponseType>(method: string, serialize: (value: RequestType) => Buffer, deserialize: (value: Buffer) => ResponseType, options?: CallOptions): ClientDuplexStream<RequestType, ResponseType>;
}
export {};

192
node_modules/@grpc/grpc-js/build/src/client.js generated vendored Normal file
View File

@ -0,0 +1,192 @@
"use strict";
/*
* Copyright 2019 gRPC authors.
*
* 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.
*
*/
Object.defineProperty(exports, "__esModule", { value: true });
const call_1 = require("./call");
const channel_1 = require("./channel");
const constants_1 = require("./constants");
const metadata_1 = require("./metadata");
const CHANNEL_SYMBOL = Symbol();
/**
* A generic gRPC client. Primarily useful as a base class for all generated
* clients.
*/
class Client {
constructor(address, credentials, options = {}) {
if (options.channelOverride) {
this[CHANNEL_SYMBOL] = options.channelOverride;
}
else if (options.channelFactoryOverride) {
this[CHANNEL_SYMBOL] = options.channelFactoryOverride(address, credentials, options);
}
else {
this[CHANNEL_SYMBOL] = new channel_1.ChannelImplementation(address, credentials, options);
}
}
close() {
this[CHANNEL_SYMBOL].close();
}
getChannel() {
return this[CHANNEL_SYMBOL];
}
waitForReady(deadline, callback) {
const checkState = (err) => {
if (err) {
callback(new Error('Failed to connect before the deadline'));
return;
}
let newState;
try {
newState = this[CHANNEL_SYMBOL].getConnectivityState(true);
}
catch (e) {
callback(new Error('The channel has been closed'));
return;
}
if (newState === channel_1.ConnectivityState.READY) {
callback();
}
else {
try {
this[CHANNEL_SYMBOL].watchConnectivityState(newState, deadline, checkState);
}
catch (e) {
callback(new Error('The channel has been closed'));
}
}
};
setImmediate(checkState);
}
handleUnaryResponse(call, deserialize, callback) {
let responseMessage = null;
call.on('data', (data) => {
if (responseMessage != null) {
call.cancelWithStatus(constants_1.Status.INTERNAL, 'Too many responses received');
}
try {
responseMessage = deserialize(data);
}
catch (e) {
call.cancelWithStatus(constants_1.Status.INTERNAL, 'Failed to parse server response');
}
});
call.on('status', (status) => {
/* We assume that call emits status after it emits end, and that it
* accounts for any cancelWithStatus calls up until it emits status.
* Therefore, considering the above event handlers, status.code should be
* OK if and only if we have a non-null responseMessage */
if (status.code === constants_1.Status.OK) {
callback(null, responseMessage);
}
else {
callback(call_1.callErrorFromStatus(status));
}
});
}
checkOptionalUnaryResponseArguments(arg1, arg2, arg3) {
if (arg1 instanceof Function) {
return { metadata: new metadata_1.Metadata(), options: {}, callback: arg1 };
}
else if (arg2 instanceof Function) {
if (arg1 instanceof metadata_1.Metadata) {
return { metadata: arg1, options: {}, callback: arg2 };
}
else {
return { metadata: new metadata_1.Metadata(), options: arg1, callback: arg2 };
}
}
else {
if (!(arg1 instanceof metadata_1.Metadata &&
arg2 instanceof Object &&
arg3 instanceof Function)) {
throw new Error('Incorrect arguments passed');
}
return { metadata: arg1, options: arg2, callback: arg3 };
}
}
makeUnaryRequest(method, serialize, deserialize, argument, metadata, options, callback) {
({ metadata, options, callback } = this.checkOptionalUnaryResponseArguments(metadata, options, callback));
const call = this[CHANNEL_SYMBOL].createCall(method, options.deadline, options.host, null, options.propagate_flags);
if (options.credentials) {
call.setCredentials(options.credentials);
}
const message = serialize(argument);
const writeObj = { message };
call.sendMetadata(metadata);
call.write(writeObj);
call.end();
this.handleUnaryResponse(call, deserialize, callback);
return new call_1.ClientUnaryCallImpl(call);
}
makeClientStreamRequest(method, serialize, deserialize, metadata, options, callback) {
({ metadata, options, callback } = this.checkOptionalUnaryResponseArguments(metadata, options, callback));
const call = this[CHANNEL_SYMBOL].createCall(method, options.deadline, options.host, null, options.propagate_flags);
if (options.credentials) {
call.setCredentials(options.credentials);
}
call.sendMetadata(metadata);
this.handleUnaryResponse(call, deserialize, callback);
return new call_1.ClientWritableStreamImpl(call, serialize);
}
checkMetadataAndOptions(arg1, arg2) {
let metadata;
let options;
if (arg1 instanceof metadata_1.Metadata) {
metadata = arg1;
if (arg2) {
options = arg2;
}
else {
options = {};
}
}
else {
if (arg1) {
options = arg1;
}
else {
options = {};
}
metadata = new metadata_1.Metadata();
}
return { metadata, options };
}
makeServerStreamRequest(method, serialize, deserialize, argument, metadata, options) {
({ metadata, options } = this.checkMetadataAndOptions(metadata, options));
const call = this[CHANNEL_SYMBOL].createCall(method, options.deadline, options.host, null, options.propagate_flags);
if (options.credentials) {
call.setCredentials(options.credentials);
}
const message = serialize(argument);
const writeObj = { message };
call.sendMetadata(metadata);
call.write(writeObj);
call.end();
return new call_1.ClientReadableStreamImpl(call, deserialize);
}
makeBidiStreamRequest(method, serialize, deserialize, metadata, options) {
({ metadata, options } = this.checkMetadataAndOptions(metadata, options));
const call = this[CHANNEL_SYMBOL].createCall(method, options.deadline, options.host, null, options.propagate_flags);
if (options.credentials) {
call.setCredentials(options.credentials);
}
call.sendMetadata(metadata);
return new call_1.ClientDuplexStreamImpl(call, serialize, deserialize);
}
}
exports.Client = Client;
//# sourceMappingURL=client.js.map

1
node_modules/@grpc/grpc-js/build/src/client.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,18 @@
/// <reference types="node" />
import { Call, WriteObject } from './call-stream';
import { Channel } from './channel';
import { BaseFilter, Filter, FilterFactory } from './filter';
import { Metadata } from './metadata';
export declare class CompressionFilter extends BaseFilter implements Filter {
private sendCompression;
private receiveCompression;
sendMetadata(metadata: Promise<Metadata>): Promise<Metadata>;
receiveMetadata(metadata: Promise<Metadata>): Promise<Metadata>;
sendMessage(message: Promise<WriteObject>): Promise<WriteObject>;
receiveMessage(message: Promise<Buffer>): Promise<Buffer>;
}
export declare class CompressionFilterFactory implements FilterFactory<CompressionFilter> {
private readonly channel;
constructor(channel: Channel);
createFilter(callStream: Call): CompressionFilter;
}

View File

@ -0,0 +1,201 @@
"use strict";
/*
* Copyright 2019 gRPC authors.
*
* 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.
*
*/
Object.defineProperty(exports, "__esModule", { value: true });
const zlib = require("zlib");
const filter_1 = require("./filter");
class CompressionHandler {
/**
* @param message Raw uncompressed message bytes
* @param compress Indicates whether the message should be compressed
* @return Framed message, compressed if applicable
*/
async writeMessage(message, compress) {
let messageBuffer = message;
if (compress) {
messageBuffer = await this.compressMessage(messageBuffer);
}
const output = Buffer.allocUnsafe(messageBuffer.length + 5);
output.writeUInt8(compress ? 1 : 0, 0);
output.writeUInt32BE(messageBuffer.length, 1);
messageBuffer.copy(output, 5);
return output;
}
/**
* @param data Framed message, possibly compressed
* @return Uncompressed message
*/
async readMessage(data) {
const compressed = data.readUInt8(0) === 1;
let messageBuffer = data.slice(5);
if (compressed) {
messageBuffer = await this.decompressMessage(messageBuffer);
}
return messageBuffer;
}
}
class IdentityHandler extends CompressionHandler {
async compressMessage(message) {
return message;
}
async writeMessage(message, compress) {
const output = Buffer.allocUnsafe(message.length + 5);
/* With "identity" compression, messages should always be marked as
* uncompressed */
output.writeUInt8(0, 0);
output.writeUInt32BE(message.length, 1);
message.copy(output, 5);
return output;
}
decompressMessage(message) {
return Promise.reject(new Error('Received compressed message but "grpc-encoding" header was identity'));
}
}
class DeflateHandler extends CompressionHandler {
compressMessage(message) {
return new Promise((resolve, reject) => {
zlib.deflate(message, (err, output) => {
if (err) {
reject(err);
}
else {
resolve(output);
}
});
});
}
decompressMessage(message) {
return new Promise((resolve, reject) => {
zlib.inflate(message, (err, output) => {
if (err) {
reject(err);
}
else {
resolve(output);
}
});
});
}
}
class GzipHandler extends CompressionHandler {
compressMessage(message) {
return new Promise((resolve, reject) => {
zlib.gzip(message, (err, output) => {
if (err) {
reject(err);
}
else {
resolve(output);
}
});
});
}
decompressMessage(message) {
return new Promise((resolve, reject) => {
zlib.unzip(message, (err, output) => {
if (err) {
reject(err);
}
else {
resolve(output);
}
});
});
}
}
class UnknownHandler extends CompressionHandler {
constructor(compressionName) {
super();
this.compressionName = compressionName;
}
compressMessage(message) {
return Promise.reject(new Error(`Received message compressed with unsupported compression method ${this.compressionName}`));
}
decompressMessage(message) {
// This should be unreachable
return Promise.reject(new Error(`Compression method not supported: ${this.compressionName}`));
}
}
function getCompressionHandler(compressionName) {
switch (compressionName) {
case 'identity':
return new IdentityHandler();
case 'deflate':
return new DeflateHandler();
case 'gzip':
return new GzipHandler();
default:
return new UnknownHandler(compressionName);
}
}
class CompressionFilter extends filter_1.BaseFilter {
constructor() {
super(...arguments);
this.sendCompression = new IdentityHandler();
this.receiveCompression = new IdentityHandler();
}
async sendMetadata(metadata) {
const headers = await metadata;
headers.set('grpc-encoding', 'identity');
headers.set('grpc-accept-encoding', 'identity,deflate,gzip');
return headers;
}
async receiveMetadata(metadata) {
const headers = await metadata;
const receiveEncoding = headers.get('grpc-encoding');
if (receiveEncoding.length > 0) {
const encoding = receiveEncoding[0];
if (typeof encoding === 'string') {
this.receiveCompression = getCompressionHandler(encoding);
}
}
headers.remove('grpc-encoding');
headers.remove('grpc-accept-encoding');
return headers;
}
async sendMessage(message) {
/* This filter is special. The input message is the bare message bytes,
* and the output is a framed and possibly compressed message. For this
* reason, this filter should be at the bottom of the filter stack */
const resolvedMessage = await message;
const compress = resolvedMessage.flags === undefined
? false
: (resolvedMessage.flags & 2 /* NoCompress */) === 0;
return {
message: await this.sendCompression.writeMessage(resolvedMessage.message, compress),
flags: resolvedMessage.flags,
};
}
async receiveMessage(message) {
/* This filter is also special. The input message is framed and possibly
* compressed, and the output message is deframed and uncompressed. So
* this is another reason that this filter should be at the bottom of the
* filter stack. */
return this.receiveCompression.readMessage(await message);
}
}
exports.CompressionFilter = CompressionFilter;
class CompressionFilterFactory {
constructor(channel) {
this.channel = channel;
}
createFilter(callStream) {
return new CompressionFilter();
}
}
exports.CompressionFilterFactory = CompressionFilterFactory;
//# sourceMappingURL=compression-filter.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"compression-filter.js","sourceRoot":"","sources":["../../src/compression-filter.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;AAEH,6BAA6B;AAI7B,qCAA6D;AAG7D,MAAe,kBAAkB;IAG/B;;;;OAIG;IACH,KAAK,CAAC,YAAY,CAAC,OAAe,EAAE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KAAK;SAC7B,CAAC;IACJ,CAAC;IAED,KAAK,CAAC,cAAc,CAAC,OAAwB;QAC3C;;;2BAGmB;QACnB,OAAO,IAAI,CAAC,kBAAkB,CAAC,WAAW,CAAC,MAAM,OAAO,CAAC,CAAC;IAC5D,CAAC;CACF;AAjDD,8CAiDC;AAED,MAAa,wBAAwB;IAEnC,YAA6B,OAAgB;QAAhB,YAAO,GAAP,OAAO,CAAS;IAAG,CAAC;IACjD,YAAY,CAAC,UAAgB;QAC3B,OAAO,IAAI,iBAAiB,EAAE,CAAC;IACjC,CAAC;CACF;AAND,4DAMC"}

24
node_modules/@grpc/grpc-js/build/src/constants.d.ts generated vendored Normal file
View File

@ -0,0 +1,24 @@
export declare enum Status {
OK = 0,
CANCELLED = 1,
UNKNOWN = 2,
INVALID_ARGUMENT = 3,
DEADLINE_EXCEEDED = 4,
NOT_FOUND = 5,
ALREADY_EXISTS = 6,
PERMISSION_DENIED = 7,
RESOURCE_EXHAUSTED = 8,
FAILED_PRECONDITION = 9,
ABORTED = 10,
OUT_OF_RANGE = 11,
UNIMPLEMENTED = 12,
INTERNAL = 13,
UNAVAILABLE = 14,
DATA_LOSS = 15,
UNAUTHENTICATED = 16
}
export declare enum LogVerbosity {
DEBUG = 0,
INFO = 1,
ERROR = 2
}

45
node_modules/@grpc/grpc-js/build/src/constants.js generated vendored Normal file
View File

@ -0,0 +1,45 @@
"use strict";
/*
* Copyright 2019 gRPC authors.
*
* 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.
*
*/
Object.defineProperty(exports, "__esModule", { value: true });
var Status;
(function (Status) {
Status[Status["OK"] = 0] = "OK";
Status[Status["CANCELLED"] = 1] = "CANCELLED";
Status[Status["UNKNOWN"] = 2] = "UNKNOWN";
Status[Status["INVALID_ARGUMENT"] = 3] = "INVALID_ARGUMENT";
Status[Status["DEADLINE_EXCEEDED"] = 4] = "DEADLINE_EXCEEDED";
Status[Status["NOT_FOUND"] = 5] = "NOT_FOUND";
Status[Status["ALREADY_EXISTS"] = 6] = "ALREADY_EXISTS";
Status[Status["PERMISSION_DENIED"] = 7] = "PERMISSION_DENIED";
Status[Status["RESOURCE_EXHAUSTED"] = 8] = "RESOURCE_EXHAUSTED";
Status[Status["FAILED_PRECONDITION"] = 9] = "FAILED_PRECONDITION";
Status[Status["ABORTED"] = 10] = "ABORTED";
Status[Status["OUT_OF_RANGE"] = 11] = "OUT_OF_RANGE";
Status[Status["UNIMPLEMENTED"] = 12] = "UNIMPLEMENTED";
Status[Status["INTERNAL"] = 13] = "INTERNAL";
Status[Status["UNAVAILABLE"] = 14] = "UNAVAILABLE";
Status[Status["DATA_LOSS"] = 15] = "DATA_LOSS";
Status[Status["UNAUTHENTICATED"] = 16] = "UNAUTHENTICATED";
})(Status = exports.Status || (exports.Status = {}));
var LogVerbosity;
(function (LogVerbosity) {
LogVerbosity[LogVerbosity["DEBUG"] = 0] = "DEBUG";
LogVerbosity[LogVerbosity["INFO"] = 1] = "INFO";
LogVerbosity[LogVerbosity["ERROR"] = 2] = "ERROR";
})(LogVerbosity = exports.LogVerbosity || (exports.LogVerbosity = {}));
//# sourceMappingURL=constants.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;AAEH,IAAY,MAkBX;AAlBD,WAAY,MAAM;IAChB,+BAAM,CAAA;IACN,6CAAS,CAAA;IACT,yCAAO,CAAA;IACP,2DAAgB,CAAA;IAChB,6DAAiB,CAAA;IACjB,6CAAS,CAAA;IACT,uDAAc,CAAA;IACd,6DAAiB,CAAA;IACjB,+DAAkB,CAAA;IAClB,iEAAmB,CAAA;IACnB,0CAAO,CAAA;IACP,oDAAY,CAAA;IACZ,sDAAa,CAAA;IACb,4CAAQ,CAAA;IACR,kDAAW,CAAA;IACX,8CAAS,CAAA;IACT,0DAAe,CAAA;AACjB,CAAC,EAlBW,MAAM,GAAN,cAAM,KAAN,cAAM,QAkBjB;AAED,IAAY,YAIX;AAJD,WAAY,YAAY;IACtB,iDAAS,CAAA;IACT,+CAAI,CAAA;IACJ,iDAAK,CAAA;AACP,CAAC,EAJW,YAAY,GAAZ,oBAAY,KAAZ,oBAAY,QAIvB"}

View File

@ -0,0 +1,17 @@
import { Call } from './call-stream';
import { Channel } from './channel';
import { BaseFilter, Filter, FilterFactory } from './filter';
import { Metadata } from './metadata';
export declare class DeadlineFilter extends BaseFilter implements Filter {
private readonly channel;
private readonly callStream;
private timer;
private deadline;
constructor(channel: Channel, callStream: Call);
sendMetadata(metadata: Promise<Metadata>): Promise<Metadata>;
}
export declare class DeadlineFilterFactory implements FilterFactory<DeadlineFilter> {
private readonly channel;
constructor(channel: Channel);
createFilter(callStream: Call): DeadlineFilter;
}

View File

@ -0,0 +1,86 @@
"use strict";
/*
* Copyright 2019 gRPC authors.
*
* 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.
*
*/
Object.defineProperty(exports, "__esModule", { value: true });
const constants_1 = require("./constants");
const filter_1 = require("./filter");
const units = [
['m', 1],
['S', 1000],
['M', 60 * 1000],
['H', 60 * 60 * 1000],
];
function getDeadline(deadline) {
const now = new Date().getTime();
const timeoutMs = Math.max(deadline - now, 0);
for (const [unit, factor] of units) {
const amount = timeoutMs / factor;
if (amount < 1e8) {
return String(Math.ceil(amount)) + unit;
}
}
throw new Error('Deadline is too far in the future');
}
class DeadlineFilter extends filter_1.BaseFilter {
constructor(channel, callStream) {
super();
this.channel = channel;
this.callStream = callStream;
this.timer = null;
const callDeadline = callStream.getDeadline();
if (callDeadline instanceof Date) {
this.deadline = callDeadline.getTime();
}
else {
this.deadline = callDeadline;
}
const now = new Date().getTime();
let timeout = this.deadline - now;
if (timeout < 0) {
timeout = 0;
}
if (this.deadline !== Infinity) {
this.timer = setTimeout(() => {
callStream.cancelWithStatus(constants_1.Status.DEADLINE_EXCEEDED, 'Deadline exceeded');
}, timeout);
callStream.on('status', () => clearTimeout(this.timer));
}
}
async sendMetadata(metadata) {
if (this.deadline === Infinity) {
return metadata;
}
/* The input metadata promise depends on the original channel.connect()
* promise, so when it is complete that implies that the channel is
* connected */
const finalMetadata = await metadata;
const timeoutString = getDeadline(this.deadline);
finalMetadata.set('grpc-timeout', timeoutString);
return finalMetadata;
}
}
exports.DeadlineFilter = DeadlineFilter;
class DeadlineFilterFactory {
constructor(channel) {
this.channel = channel;
}
createFilter(callStream) {
return new DeadlineFilter(this.channel, callStream);
}
}
exports.DeadlineFilterFactory = DeadlineFilterFactory;
//# sourceMappingURL=deadline-filter.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"deadline-filter.js","sourceRoot":"","sources":["../../src/deadline-filter.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;AAIH,2CAAqC;AACrC,qCAA6D;AAG7D,MAAM,KAAK,GAA4B;IACrC,CAAC,GAAG,EAAE,CAAC,CAAC;IACR,CAAC,GAAG,EAAE,IAAI,CAAC;IACX,CAAC,GAAG,EAAE,EAAE,GAAG,IAAI,CAAC;IAChB,CAAC,GAAG,EAAE,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;CACtB,CAAC;AAEF,SAAS,WAAW,CAAC,QAAgB;IACnC,MAAM,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE,CAAC;IACjC,MAAM,SAAS,GAAG,IAAI,CAA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G,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,KAAqB,CAAC,CAAC,CAAC;SACzE;IACH,CAAC;IAED,KAAK,CAAC,YAAY,CAAC,QAA2B;QAC5C,IAAI,IAAI,CAAC,QAAQ,KAAK,QAAQ,EAAE;YAC9B,OAAO,QAAQ,CAAC;SACjB;QACD;;uBAEe;QACf,MAAM,aAAa,GAAG,MAAM,QAAQ,CAAC;QACrC,MAAM,aAAa,GAAG,WAAW,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QACjD,aAAa,CAAC,GAAG,CAAC,cAAc,EAAE,aAAa,CAAC,CAAC;QACjD,OAAO,aAAa,CAAC;IACvB,CAAC;CACF;AA1CD,wCA0CC;AAED,MAAa,qBAAqB;IAChC,YAA6B,OAAgB;QAAhB,YAAO,GAAP,OAAO,CAAS;IAAG,CAAC;IAEjD,YAAY,CAAC,UAAgB;QAC3B,OAAO,IAAI,cAAc,CAAC,IAAI,CAAC,OAAO,EAAE,UAAU,CAAC,CAAC;IACtD,CAAC;CACF;AAND,sDAMC"}

9
node_modules/@grpc/grpc-js/build/src/events.d.ts generated vendored Normal file
View File

@ -0,0 +1,9 @@
export interface EmitterAugmentation1<Name extends string | symbol, Arg> {
addListener(event: Name, listener: (arg1: Arg) => void): this;
emit(event: Name, arg1: Arg): boolean;
on(event: Name, listener: (arg1: Arg) => void): this;
once(event: Name, listener: (arg1: Arg) => void): this;
prependListener(event: Name, listener: (arg1: Arg) => void): this;
prependOnceListener(event: Name, listener: (arg1: Arg) => void): this;
removeListener(event: Name, listener: (arg1: Arg) => void): this;
}

19
node_modules/@grpc/grpc-js/build/src/events.js generated vendored Normal file
View File

@ -0,0 +1,19 @@
"use strict";
/*
* Copyright 2019 gRPC authors.
*
* 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.
*
*/
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=events.js.map

1
node_modules/@grpc/grpc-js/build/src/events.js.map generated vendored Normal file
View File

@ -0,0 +1 @@
{"version":3,"file":"events.js","sourceRoot":"","sources":["../../src/events.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG"}

18
node_modules/@grpc/grpc-js/build/src/filter-stack.d.ts generated vendored Normal file
View File

@ -0,0 +1,18 @@
/// <reference types="node" />
import { Call, StatusObject, WriteObject } from './call-stream';
import { Filter, FilterFactory } from './filter';
import { Metadata } from './metadata';
export declare class FilterStack implements Filter {
private readonly filters;
constructor(filters: Filter[]);
sendMetadata(metadata: Promise<Metadata>): Promise<Metadata>;
receiveMetadata(metadata: Promise<Metadata>): Promise<Metadata>;
sendMessage(message: Promise<WriteObject>): Promise<WriteObject>;
receiveMessage(message: Promise<Buffer>): Promise<Buffer>;
receiveTrailers(status: Promise<StatusObject>): Promise<StatusObject>;
}
export declare class FilterStackFactory implements FilterFactory<FilterStack> {
private readonly factories;
constructor(factories: Array<FilterFactory<Filter>>);
createFilter(callStream: Call): FilterStack;
}

69
node_modules/@grpc/grpc-js/build/src/filter-stack.js generated vendored Normal file
View File

@ -0,0 +1,69 @@
"use strict";
/*
* Copyright 2019 gRPC authors.
*
* 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.
*
*/
Object.defineProperty(exports, "__esModule", { value: true });
class FilterStack {
constructor(filters) {
this.filters = filters;
}
sendMetadata(metadata) {
let result = metadata;
for (let i = 0; i < this.filters.length; i++) {
result = this.filters[i].sendMetadata(result);
}
return result;
}
receiveMetadata(metadata) {
let result = metadata;
for (let i = this.filters.length - 1; i >= 0; i--) {
result = this.filters[i].receiveMetadata(result);
}
return result;
}
sendMessage(message) {
let result = message;
for (let i = 0; i < this.filters.length; i++) {
result = this.filters[i].sendMessage(result);
}
return result;
}
receiveMessage(message) {
let result = message;
for (let i = this.filters.length - 1; i >= 0; i--) {
result = this.filters[i].receiveMessage(result);
}
return result;
}
receiveTrailers(status) {
let result = status;
for (let i = this.filters.length - 1; i >= 0; i--) {
result = this.filters[i].receiveTrailers(result);
}
return result;
}
}
exports.FilterStack = FilterStack;
class FilterStackFactory {
constructor(factories) {
this.factories = factories;
}
createFilter(callStream) {
return new FilterStack(this.factories.map(factory => factory.createFilter(callStream)));
}
}
exports.FilterStackFactory = FilterStackFactory;
//# sourceMappingURL=filter-stack.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"filter-stack.js","sourceRoot":"","sources":["../../src/filter-stack.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;AAMH,MAAa,WAAW;IACtB,YAA6B,OAAiB;QAAjB,YAAO,GAAP,OAAO,CAAU;IAAG,CAAC;IAElD,YAAY,CAAC,QAA2B;QACtC,IAAI,MAAM,GAAsB,QAAQ,CAAC;QAEzC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YAC5C,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC;SAC/C;QAED,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,eAAe,CAAC,QAA2B;QACzC,IAAI,MAAM,GAAsB,QAAQ,CAAC;QAEzC,KAAK,IAAI,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,EA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AI,CAAC,SAAS,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC,OAAO,CAAC,YAAY,CAAC,UAAU,CAAC,CAAC,CAChE,CAAC;IACJ,CAAC;CACF;AARD,gDAQC"}

24
node_modules/@grpc/grpc-js/build/src/filter.d.ts generated vendored Normal file
View File

@ -0,0 +1,24 @@
/// <reference types="node" />
import { Call, StatusObject, WriteObject } from './call-stream';
import { Metadata } from './metadata';
/**
* Filter classes represent related per-call logic and state that is primarily
* used to modify incoming and outgoing data
*/
export interface Filter {
sendMetadata(metadata: Promise<Metadata>): Promise<Metadata>;
receiveMetadata(metadata: Promise<Metadata>): Promise<Metadata>;
sendMessage(message: Promise<WriteObject>): Promise<WriteObject>;
receiveMessage(message: Promise<Buffer>): Promise<Buffer>;
receiveTrailers(status: Promise<StatusObject>): Promise<StatusObject>;
}
export declare abstract class BaseFilter {
sendMetadata(metadata: Promise<Metadata>): Promise<Metadata>;
receiveMetadata(metadata: Promise<Metadata>): Promise<Metadata>;
sendMessage(message: Promise<WriteObject>): Promise<WriteObject>;
receiveMessage(message: Promise<Buffer>): Promise<Buffer>;
receiveTrailers(status: Promise<StatusObject>): Promise<StatusObject>;
}
export interface FilterFactory<T extends Filter> {
createFilter(callStream: Call): T;
}

37
node_modules/@grpc/grpc-js/build/src/filter.js generated vendored Normal file
View File

@ -0,0 +1,37 @@
"use strict";
/*
* Copyright 2019 gRPC authors.
*
* 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.
*
*/
Object.defineProperty(exports, "__esModule", { value: true });
class BaseFilter {
async sendMetadata(metadata) {
return metadata;
}
async receiveMetadata(metadata) {
return metadata;
}
async sendMessage(message) {
return message;
}
async receiveMessage(message) {
return message;
}
async receiveTrailers(status) {
return status;
}
}
exports.BaseFilter = BaseFilter;
//# sourceMappingURL=filter.js.map

1
node_modules/@grpc/grpc-js/build/src/filter.js.map generated vendored Normal file
View File

@ -0,0 +1 @@
{"version":3,"file":"filter.js","sourceRoot":"","sources":["../../src/filter.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;AAqBH,MAAsB,UAAU;IAC9B,KAAK,CAAC,YAAY,CAAC,QAA2B;QAC5C,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,KAAK,CAAC,eAAe,CAAC,QAA2B;QAC/C,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,KAAK,CAAC,WAAW,CAAC,OAA6B;QAC7C,OAAO,OAAO,CAAC;IACjB,CAAC;IAED,KAAK,CAAC,cAAc,CAAC,OAAwB;QAC3C,OAAO,OAAO,CAAC;IACjB,CAAC;IAED,KAAK,CAAC,eAAe,CAAC,MAA6B;QACjD,OAAO,MAAM,CAAC;IAChB,CAAC;CACF;AApBD,gCAoBC"}

64
node_modules/@grpc/grpc-js/build/src/index.d.ts generated vendored Normal file
View File

@ -0,0 +1,64 @@
/// <reference types="node" />
import { ClientDuplexStream, ClientReadableStream, ClientUnaryCall, ClientWritableStream, ServiceError } from './call';
import { CallCredentials } from './call-credentials';
import { Deadline, StatusObject } from './call-stream';
import { Channel, ConnectivityState, ChannelImplementation } from './channel';
import { ChannelCredentials } from './channel-credentials';
import { CallOptions, Client } from './client';
import { LogVerbosity, Status } from './constants';
import { Deserialize, loadPackageDefinition, makeClientConstructor, Serialize, ServiceDefinition } from './make-client';
import { Metadata } from './metadata';
import { Server, UntypedHandleCall, UntypedServiceImplementation } from './server';
import { KeyCertPair, ServerCredentials } from './server-credentials';
import { StatusBuilder } from './status-builder';
import { handleBidiStreamingCall, handleServerStreamingCall, handleUnaryCall, ServerUnaryCall, ServerReadableStream, ServerWritableStream, ServerDuplexStream } from './server-call';
export interface OAuth2Client {
getRequestMetadata: (url: string, callback: (err: Error | null, headers?: {
[index: string]: string;
}) => void) => void;
getRequestHeaders: (url?: string) => Promise<{
[index: string]: string;
}>;
}
/**** Client Credentials ****/
export declare const credentials: {
[key: string]: Function;
};
/**** Metadata ****/
export { Metadata };
/**** Constants ****/
export { LogVerbosity as logVerbosity, Status as status, ConnectivityState as connectivityState, };
/**** Client ****/
export { Client, loadPackageDefinition, makeClientConstructor, makeClientConstructor as makeGenericClientConstructor, ChannelImplementation as Channel, };
/**
* Close a Client object.
* @param client The client to close.
*/
export declare const closeClient: (client: Client) => void;
export declare const waitForClientReady: (client: Client, deadline: number | Date, callback: (error?: Error | undefined) => void) => void;
export { ChannelCredentials, CallCredentials, Deadline, Serialize as serialize, Deserialize as deserialize, ClientUnaryCall, ClientReadableStream, ClientWritableStream, ClientDuplexStream, CallOptions, StatusObject, ServiceError, ServerUnaryCall, ServerReadableStream, ServerWritableStream, ServerDuplexStream, ServiceDefinition, UntypedHandleCall, UntypedServiceImplementation, };
/**** Server ****/
export { handleBidiStreamingCall, handleServerStreamingCall, handleUnaryCall };
export declare type Call = ClientUnaryCall | ClientReadableStream<any> | ClientWritableStream<any> | ClientDuplexStream<any, any>;
export declare type MetadataListener = (metadata: Metadata, next: Function) => void;
export declare type MessageListener = (message: any, next: Function) => void;
export declare type StatusListener = (status: StatusObject, next: Function) => void;
export interface Listener {
onReceiveMetadata?: MetadataListener;
onReceiveMessage?: MessageListener;
onReceiveStatus?: StatusListener;
}
/**** Unimplemented function stubs ****/
export declare const loadObject: (value: any, options: any) => never;
export declare const load: (filename: any, format: any, options: any) => never;
export declare const setLogger: (logger: Partial<Console>) => void;
export declare const setLogVerbosity: (verbosity: LogVerbosity) => void;
export { Server };
export { ServerCredentials };
export { KeyCertPair };
export declare const getClientChannel: (client: Client) => Channel;
export { StatusBuilder };
export declare const ListenerBuilder: () => never;
export declare const InterceptorBuilder: () => never;
export declare const InterceptingCall: () => never;
export { GrpcObject } from './make-client';

158
node_modules/@grpc/grpc-js/build/src/index.js generated vendored Normal file
View File

@ -0,0 +1,158 @@
"use strict";
/*
* Copyright 2019 gRPC authors.
*
* 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.
*
*/
Object.defineProperty(exports, "__esModule", { value: true });
const semver = require("semver");
const call_credentials_1 = require("./call-credentials");
exports.CallCredentials = call_credentials_1.CallCredentials;
const channel_1 = require("./channel");
exports.connectivityState = channel_1.ConnectivityState;
exports.Channel = channel_1.ChannelImplementation;
const channel_credentials_1 = require("./channel-credentials");
exports.ChannelCredentials = channel_credentials_1.ChannelCredentials;
const client_1 = require("./client");
exports.Client = client_1.Client;
const constants_1 = require("./constants");
exports.logVerbosity = constants_1.LogVerbosity;
exports.status = constants_1.Status;
const logging = require("./logging");
const make_client_1 = require("./make-client");
exports.loadPackageDefinition = make_client_1.loadPackageDefinition;
exports.makeClientConstructor = make_client_1.makeClientConstructor;
exports.makeGenericClientConstructor = make_client_1.makeClientConstructor;
const metadata_1 = require("./metadata");
exports.Metadata = metadata_1.Metadata;
const server_1 = require("./server");
exports.Server = server_1.Server;
const server_credentials_1 = require("./server-credentials");
exports.ServerCredentials = server_credentials_1.ServerCredentials;
const status_builder_1 = require("./status-builder");
exports.StatusBuilder = status_builder_1.StatusBuilder;
const supportedNodeVersions = require('../../package.json').engines.node;
if (!semver.satisfies(process.version, supportedNodeVersions)) {
throw new Error(`@grpc/grpc-js only works on Node ${supportedNodeVersions}`);
}
function mixin(...sources) {
const result = {};
for (const source of sources) {
for (const propName of Object.getOwnPropertyNames(source)) {
const property = source[propName]; // tslint:disable-line no-any
if (typeof property === 'function') {
result[propName] = property;
}
}
}
return result;
}
/**** Client Credentials ****/
// Using assign only copies enumerable properties, which is what we want
exports.credentials = mixin({
/**
* Create a gRPC credential from a Google credential object.
* @param googleCredentials The authentication client to use.
* @return The resulting CallCredentials object.
*/
createFromGoogleCredential: (googleCredentials) => {
return call_credentials_1.CallCredentials.createFromMetadataGenerator((options, callback) => {
// google-auth-library pre-v2.0.0 does not have getRequestHeaders
// but has getRequestMetadata, which is deprecated in v2.0.0
let getHeaders;
if (typeof googleCredentials.getRequestHeaders === 'function') {
getHeaders = googleCredentials.getRequestHeaders(options.service_url);
}
else {
getHeaders = new Promise((resolve, reject) => {
googleCredentials.getRequestMetadata(options.service_url, (err, headers) => {
if (err) {
reject(err);
return;
}
resolve(headers);
});
});
}
getHeaders.then(headers => {
const metadata = new metadata_1.Metadata();
for (const key of Object.keys(headers)) {
metadata.add(key, headers[key]);
}
callback(null, metadata);
}, err => {
callback(err);
});
});
},
/**
* Combine a ChannelCredentials with any number of CallCredentials into a
* single ChannelCredentials object.
* @param channelCredentials The ChannelCredentials object.
* @param callCredentials Any number of CallCredentials objects.
* @return The resulting ChannelCredentials object.
*/
combineChannelCredentials: (channelCredentials, ...callCredentials) => {
return callCredentials.reduce((acc, other) => acc.compose(other), channelCredentials);
},
/**
* Combine any number of CallCredentials into a single CallCredentials
* object.
* @param first The first CallCredentials object.
* @param additional Any number of additional CallCredentials objects.
* @return The resulting CallCredentials object.
*/
combineCallCredentials: (first, ...additional) => {
return additional.reduce((acc, other) => acc.compose(other), first);
},
}, channel_credentials_1.ChannelCredentials, call_credentials_1.CallCredentials);
/**
* Close a Client object.
* @param client The client to close.
*/
exports.closeClient = (client) => client.close();
exports.waitForClientReady = (client, deadline, callback) => client.waitForReady(deadline, callback);
/**** Unimplemented function stubs ****/
/* tslint:disable:no-any variable-name */
exports.loadObject = (value, options) => {
throw new Error('Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead');
};
exports.load = (filename, format, options) => {
throw new Error('Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead');
};
exports.setLogger = (logger) => {
logging.setLogger(logger);
};
exports.setLogVerbosity = (verbosity) => {
logging.setLoggerVerbosity(verbosity);
};
exports.getClientChannel = (client) => {
return client_1.Client.prototype.getChannel.call(client);
};
exports.ListenerBuilder = () => {
throw new Error('Not yet implemented');
};
exports.InterceptorBuilder = () => {
throw new Error('Not yet implemented');
};
exports.InterceptingCall = () => {
throw new Error('Not yet implemented');
};
const resolver = require("./resolver");
const load_balancer = require("./load-balancer");
(() => {
resolver.registerAll();
load_balancer.registerAll();
})();
//# sourceMappingURL=index.js.map

1
node_modules/@grpc/grpc-js/build/src/index.js.map generated vendored Normal file
View File

@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;AAEH,iCAAiC;AASjC,yDAAqD;AAkMnD,0BAlMO,kCAAe,CAkMP;AAhMjB,uCAA8E;AAkKvD,4BAlKL,2BAAiB,CAkKK;AAWb,kBA7KU,+BAAqB,CA6KxB;AA5KlC,+DAA2D;AA8LzD,6BA9LO,wCAAkB,CA8LP;AA7LpB,qCAA+C;AAuK7C,iBAvKoB,eAAM,CAuKpB;AAtKR,2CAAmD;AA6JjC,uBA7JT,wBAAY,CA6JS;AAClB,iBA9JW,kBAAM,CA8JX;AA7JlB,qCAAqC;AACrC,+CAMuB;AA+JrB,gCAnKA,mCAAqB,CAmKA;AACrB,gCAnKA,mCAAqB,CAmKA;AACI,uCApKzB,mCAAqB,CAoKgC;AAhKvD,yCAAsC;AA+I7B,mBA/IA,mBAAQ,CA+IA;AA9IjB,qCAIkB;AAoPT,iBAvPP,eAAM,CAuPO;AAnPf,6DAAsE;AAoP7D,4BApPa,sCAAiB,CAoPb;AAnP1B,qDAAiD;AA0PxC,wBA1PA,8BAAa,CA0PA;AA/OtB,MAAM,qBAAqB,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC;AACzE,IAAI,CAAC,MAAM,CAAC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lHelper } from './load-balancer';
import { LoadBalancingConfig } from './load-balancing-config';
export declare class PickFirstLoadBalancer implements LoadBalancer {
private channelControlHelper;
/**
* The list of backend addresses most recently passed to `updateAddressList`.
*/
private latestAddressList;
/**
* The list of subchannels this load balancer is currently attempting to
* connect to.
*/
private subchannels;
/**
* The current connectivity state of the load balancer.
*/
private currentState;
/**
* The index within the `subchannels` array of the subchannel with the most
* recently started connection attempt.
*/
private currentSubchannelIndex;
private subchannelStateCounts;
/**
* The currently picked subchannel used for making calls. Populated if
* and only if the load balancer's current state is READY. In that case,
* the subchannel's current state is also READY.
*/
private currentPick;
/**
* Listener callback attached to each subchannel in the `subchannels` list
* while establishing a connection.
*/
private subchannelStateListener;
/**
* Listener callback attached to the current picked subchannel.
*/
private pickedSubchannelStateListener;
/**
* Timer reference for the timer tracking when to start
*/
private connectionDelayTimeout;
private triedAllSubchannels;
/**
* Load balancer that attempts to connect to each backend in the address list
* in order, and picks the first one that connects, using it for every
* request.
* @param channelControlHelper `ChannelControlHelper` instance provided by
* this load balancer's owner.
*/
constructor(channelControlHelper: ChannelControlHelper);
private startNextSubchannelConnecting;
/**
* Have a single subchannel in the `subchannels` list start connecting.
* @param subchannelIndex The index into the `subchannels` list.
*/
private startConnecting;
private pickSubchannel;
private updateState;
private resetSubchannelList;
/**
* Start connecting to the address list most recently passed to
* `updateAddressList`.
*/
private connectToAddressList;
updateAddressList(addressList: string[], lbConfig: LoadBalancingConfig | null): void;
exitIdle(): void;
resetBackoff(): void;
destroy(): void;
getTypeName(): string;
replaceChannelControlHelper(channelControlHelper: ChannelControlHelper): void;
}
export declare function setup(): void;

View File

@ -0,0 +1,340 @@
"use strict";
/*
* Copyright 2019 gRPC authors.
*
* 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.
*
*/
Object.defineProperty(exports, "__esModule", { value: true });
const load_balancer_1 = require("./load-balancer");
const channel_1 = require("./channel");
const picker_1 = require("./picker");
const logging = require("./logging");
const constants_1 = require("./constants");
const TRACER_NAME = 'pick_first';
function trace(text) {
logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text);
}
const TYPE_NAME = 'pick_first';
/**
* Delay after starting a connection on a subchannel before starting a
* connection on the next subchannel in the list, for Happy Eyeballs algorithm.
*/
const CONNECTION_DELAY_INTERVAL_MS = 250;
/**
* Picker for a `PickFirstLoadBalancer` in the READY state. Always returns the
* picked subchannel.
*/
class PickFirstPicker {
constructor(subchannel) {
this.subchannel = subchannel;
}
pick(pickArgs) {
return {
pickResultType: picker_1.PickResultType.COMPLETE,
subchannel: this.subchannel,
status: null,
};
}
}
class PickFirstLoadBalancer {
/**
* Load balancer that attempts to connect to each backend in the address list
* in order, and picks the first one that connects, using it for every
* request.
* @param channelControlHelper `ChannelControlHelper` instance provided by
* this load balancer's owner.
*/
constructor(channelControlHelper) {
this.channelControlHelper = channelControlHelper;
/**
* The list of backend addresses most recently passed to `updateAddressList`.
*/
this.latestAddressList = [];
/**
* The list of subchannels this load balancer is currently attempting to
* connect to.
*/
this.subchannels = [];
/**
* The current connectivity state of the load balancer.
*/
this.currentState = channel_1.ConnectivityState.IDLE;
/**
* The index within the `subchannels` array of the subchannel with the most
* recently started connection attempt.
*/
this.currentSubchannelIndex = 0;
/**
* The currently picked subchannel used for making calls. Populated if
* and only if the load balancer's current state is READY. In that case,
* the subchannel's current state is also READY.
*/
this.currentPick = null;
this.triedAllSubchannels = false;
this.updateState(channel_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this));
this.subchannelStateCounts = {
[channel_1.ConnectivityState.CONNECTING]: 0,
[channel_1.ConnectivityState.IDLE]: 0,
[channel_1.ConnectivityState.READY]: 0,
[channel_1.ConnectivityState.SHUTDOWN]: 0,
[channel_1.ConnectivityState.TRANSIENT_FAILURE]: 0,
};
this.subchannelStateListener = (subchannel, previousState, newState) => {
this.subchannelStateCounts[previousState] -= 1;
this.subchannelStateCounts[newState] += 1;
/* If the subchannel we most recently attempted to start connecting
* to goes into TRANSIENT_FAILURE, immediately try to start
* connecting to the next one instead of waiting for the connection
* delay timer. */
if (subchannel === this.subchannels[this.currentSubchannelIndex] &&
newState === channel_1.ConnectivityState.TRANSIENT_FAILURE) {
this.startNextSubchannelConnecting();
}
if (newState === channel_1.ConnectivityState.READY) {
this.pickSubchannel(subchannel);
return;
}
else {
if (this.triedAllSubchannels &&
this.subchannelStateCounts[channel_1.ConnectivityState.IDLE] ===
this.subchannels.length) {
/* If all of the subchannels are IDLE we should go back to a
* basic IDLE state where there is no subchannel list to avoid
* holding unused resources */
this.resetSubchannelList();
}
if (this.currentPick === null) {
if (this.triedAllSubchannels) {
let newLBState;
if (this.subchannelStateCounts[channel_1.ConnectivityState.CONNECTING] > 0) {
newLBState = channel_1.ConnectivityState.CONNECTING;
}
else if (this.subchannelStateCounts[channel_1.ConnectivityState.TRANSIENT_FAILURE] >
0) {
newLBState = channel_1.ConnectivityState.TRANSIENT_FAILURE;
}
else {
newLBState = channel_1.ConnectivityState.IDLE;
}
if (newLBState !== this.currentState) {
if (newLBState === channel_1.ConnectivityState.TRANSIENT_FAILURE) {
this.updateState(newLBState, new picker_1.UnavailablePicker());
}
else {
this.updateState(newLBState, new picker_1.QueuePicker(this));
}
}
}
else {
this.updateState(channel_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this));
}
}
}
};
this.pickedSubchannelStateListener = (subchannel, previousState, newState) => {
if (newState !== channel_1.ConnectivityState.READY) {
this.currentPick = null;
subchannel.unref();
subchannel.removeConnectivityStateListener(this.pickedSubchannelStateListener);
if (this.subchannels.length > 0) {
if (this.triedAllSubchannels) {
let newLBState;
if (this.subchannelStateCounts[channel_1.ConnectivityState.CONNECTING] > 0) {
newLBState = channel_1.ConnectivityState.CONNECTING;
}
else if (this.subchannelStateCounts[channel_1.ConnectivityState.TRANSIENT_FAILURE] >
0) {
newLBState = channel_1.ConnectivityState.TRANSIENT_FAILURE;
}
else {
newLBState = channel_1.ConnectivityState.IDLE;
}
if (newLBState === channel_1.ConnectivityState.TRANSIENT_FAILURE) {
this.updateState(newLBState, new picker_1.UnavailablePicker());
}
else {
this.updateState(newLBState, new picker_1.QueuePicker(this));
}
}
else {
this.updateState(channel_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this));
}
}
else {
/* We don't need to backoff here because this only happens if a
* subchannel successfully connects then disconnects, so it will not
* create a loop of attempting to connect to an unreachable backend
*/
this.updateState(channel_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this));
}
}
};
this.connectionDelayTimeout = setTimeout(() => { }, 0);
clearTimeout(this.connectionDelayTimeout);
}
startNextSubchannelConnecting() {
if (this.triedAllSubchannels) {
return;
}
for (const [index, subchannel] of this.subchannels.entries()) {
if (index > this.currentSubchannelIndex) {
const subchannelState = subchannel.getConnectivityState();
if (subchannelState === channel_1.ConnectivityState.IDLE ||
subchannelState === channel_1.ConnectivityState.CONNECTING) {
this.startConnecting(index);
return;
}
}
}
this.triedAllSubchannels = true;
}
/**
* Have a single subchannel in the `subchannels` list start connecting.
* @param subchannelIndex The index into the `subchannels` list.
*/
startConnecting(subchannelIndex) {
clearTimeout(this.connectionDelayTimeout);
this.currentSubchannelIndex = subchannelIndex;
if (this.subchannels[subchannelIndex].getConnectivityState() ===
channel_1.ConnectivityState.IDLE) {
trace('Start connecting to subchannel with address ' +
this.subchannels[subchannelIndex].getAddress());
process.nextTick(() => {
this.subchannels[subchannelIndex].startConnecting();
});
}
this.connectionDelayTimeout = setTimeout(() => {
this.startNextSubchannelConnecting();
}, CONNECTION_DELAY_INTERVAL_MS);
}
pickSubchannel(subchannel) {
trace('Pick subchannel with address ' + subchannel.getAddress());
if (this.currentPick !== null) {
this.currentPick.unref();
this.currentPick.removeConnectivityStateListener(this.pickedSubchannelStateListener);
}
this.currentPick = subchannel;
this.updateState(channel_1.ConnectivityState.READY, new PickFirstPicker(subchannel));
subchannel.addConnectivityStateListener(this.pickedSubchannelStateListener);
subchannel.ref();
this.resetSubchannelList();
clearTimeout(this.connectionDelayTimeout);
}
updateState(newState, picker) {
trace(channel_1.ConnectivityState[this.currentState] +
' -> ' +
channel_1.ConnectivityState[newState]);
this.currentState = newState;
this.channelControlHelper.updateState(newState, picker);
}
resetSubchannelList() {
for (const subchannel of this.subchannels) {
subchannel.removeConnectivityStateListener(this.subchannelStateListener);
subchannel.unref();
}
this.currentSubchannelIndex = 0;
this.subchannelStateCounts = {
[channel_1.ConnectivityState.CONNECTING]: 0,
[channel_1.ConnectivityState.IDLE]: 0,
[channel_1.ConnectivityState.READY]: 0,
[channel_1.ConnectivityState.SHUTDOWN]: 0,
[channel_1.ConnectivityState.TRANSIENT_FAILURE]: 0,
};
this.subchannels = [];
this.triedAllSubchannels = false;
}
/**
* Start connecting to the address list most recently passed to
* `updateAddressList`.
*/
connectToAddressList() {
this.resetSubchannelList();
trace('Connect to address list ' + this.latestAddressList);
this.subchannels = this.latestAddressList.map(address => this.channelControlHelper.createSubchannel(address, {}));
for (const subchannel of this.subchannels) {
subchannel.ref();
}
for (const subchannel of this.subchannels) {
subchannel.addConnectivityStateListener(this.subchannelStateListener);
if (subchannel.getConnectivityState() === channel_1.ConnectivityState.READY) {
this.pickSubchannel(subchannel);
this.resetSubchannelList();
return;
}
}
for (const [index, subchannel] of this.subchannels.entries()) {
const subchannelState = subchannel.getConnectivityState();
if (subchannelState === channel_1.ConnectivityState.IDLE ||
subchannelState === channel_1.ConnectivityState.CONNECTING) {
this.startConnecting(index);
if (this.currentPick === null) {
this.updateState(channel_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this));
}
return;
}
}
// If the code reaches this point, every subchannel must be in TRANSIENT_FAILURE
if (this.currentPick === null) {
this.updateState(channel_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker());
}
}
updateAddressList(addressList, lbConfig) {
// lbConfig has no useful information for pick first load balancing
/* To avoid unnecessary churn, we only do something with this address list
* if we're not currently trying to establish a connection, or if the new
* address list is different from the existing one */
if (this.subchannels.length === 0 ||
!this.latestAddressList.every((value, index) => addressList[index] === value)) {
this.latestAddressList = addressList;
this.connectToAddressList();
}
}
exitIdle() {
for (const subchannel of this.subchannels) {
subchannel.startConnecting();
}
if (this.currentState === channel_1.ConnectivityState.IDLE) {
if (this.latestAddressList.length > 0) {
this.connectToAddressList();
}
}
if (this.currentState === channel_1.ConnectivityState.IDLE ||
this.triedAllSubchannels) {
this.channelControlHelper.requestReresolution();
}
}
resetBackoff() {
/* The pick first load balancer does not have a connection backoff, so this
* does nothing */
}
destroy() {
this.resetSubchannelList();
if (this.currentPick !== null) {
this.currentPick.unref();
this.currentPick.removeConnectivityStateListener(this.pickedSubchannelStateListener);
}
}
getTypeName() {
return TYPE_NAME;
}
replaceChannelControlHelper(channelControlHelper) {
this.channelControlHelper = channelControlHelper;
}
}
exports.PickFirstLoadBalancer = PickFirstLoadBalancer;
function setup() {
load_balancer_1.registerLoadBalancerType(TYPE_NAME, PickFirstLoadBalancer);
}
exports.setup = setup;
//# sourceMappingURL=load-balancer-pick-first.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,21 @@
import { LoadBalancer, ChannelControlHelper } from './load-balancer';
import { LoadBalancingConfig } from './load-balancing-config';
export declare class RoundRobinLoadBalancer implements LoadBalancer {
private channelControlHelper;
private subchannels;
private currentState;
private subchannelStateListener;
private subchannelStateCounts;
private currentReadyPicker;
constructor(channelControlHelper: ChannelControlHelper);
private calculateAndUpdateState;
private updateState;
private resetSubchannelList;
updateAddressList(addressList: string[], lbConfig: LoadBalancingConfig | null): void;
exitIdle(): void;
resetBackoff(): void;
destroy(): void;
getTypeName(): string;
replaceChannelControlHelper(channelControlHelper: ChannelControlHelper): void;
}
export declare function setup(): void;

View File

@ -0,0 +1,156 @@
"use strict";
/*
* Copyright 2019 gRPC authors.
*
* 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.
*
*/
Object.defineProperty(exports, "__esModule", { value: true });
const load_balancer_1 = require("./load-balancer");
const channel_1 = require("./channel");
const picker_1 = require("./picker");
const TYPE_NAME = 'round_robin';
class RoundRobinPicker {
constructor(subchannelList, nextIndex = 0) {
this.subchannelList = subchannelList;
this.nextIndex = nextIndex;
}
pick(pickArgs) {
const pickedSubchannel = this.subchannelList[this.nextIndex];
this.nextIndex = (this.nextIndex + 1) % this.subchannelList.length;
return {
pickResultType: picker_1.PickResultType.COMPLETE,
subchannel: pickedSubchannel,
status: null,
};
}
/**
* Check what the next subchannel returned would be. Used by the load
* balancer implementation to preserve this part of the picker state if
* possible when a subchannel connects or disconnects.
*/
peekNextSubchannel() {
return this.subchannelList[this.nextIndex];
}
}
class RoundRobinLoadBalancer {
constructor(channelControlHelper) {
this.channelControlHelper = channelControlHelper;
this.subchannels = [];
this.currentState = channel_1.ConnectivityState.IDLE;
this.currentReadyPicker = null;
this.updateState(channel_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this));
this.subchannelStateCounts = {
[channel_1.ConnectivityState.CONNECTING]: 0,
[channel_1.ConnectivityState.IDLE]: 0,
[channel_1.ConnectivityState.READY]: 0,
[channel_1.ConnectivityState.SHUTDOWN]: 0,
[channel_1.ConnectivityState.TRANSIENT_FAILURE]: 0,
};
this.subchannelStateListener = (subchannel, previousState, newState) => {
this.subchannelStateCounts[previousState] -= 1;
this.subchannelStateCounts[newState] += 1;
this.calculateAndUpdateState();
if (newState === channel_1.ConnectivityState.TRANSIENT_FAILURE) {
this.channelControlHelper.requestReresolution();
}
if (newState === channel_1.ConnectivityState.TRANSIENT_FAILURE ||
newState === channel_1.ConnectivityState.IDLE) {
subchannel.startConnecting();
}
};
}
calculateAndUpdateState() {
if (this.subchannelStateCounts[channel_1.ConnectivityState.READY] > 0) {
const readySubchannels = this.subchannels.filter(subchannel => subchannel.getConnectivityState() === channel_1.ConnectivityState.READY);
let index = 0;
if (this.currentReadyPicker !== null) {
index = readySubchannels.indexOf(this.currentReadyPicker.peekNextSubchannel());
if (index < 0) {
index = 0;
}
}
this.updateState(channel_1.ConnectivityState.READY, new RoundRobinPicker(readySubchannels, index));
}
else if (this.subchannelStateCounts[channel_1.ConnectivityState.CONNECTING] > 0) {
this.updateState(channel_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this));
}
else if (this.subchannelStateCounts[channel_1.ConnectivityState.TRANSIENT_FAILURE] > 0) {
this.updateState(channel_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker());
}
else {
this.updateState(channel_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this));
}
}
updateState(newState, picker) {
if (newState === channel_1.ConnectivityState.READY) {
this.currentReadyPicker = picker;
}
else {
this.currentReadyPicker = null;
}
this.currentState = newState;
this.channelControlHelper.updateState(newState, picker);
}
resetSubchannelList() {
for (const subchannel of this.subchannels) {
subchannel.removeConnectivityStateListener(this.subchannelStateListener);
subchannel.unref();
}
this.subchannelStateCounts = {
[channel_1.ConnectivityState.CONNECTING]: 0,
[channel_1.ConnectivityState.IDLE]: 0,
[channel_1.ConnectivityState.READY]: 0,
[channel_1.ConnectivityState.SHUTDOWN]: 0,
[channel_1.ConnectivityState.TRANSIENT_FAILURE]: 0,
};
this.subchannels = [];
}
updateAddressList(addressList, lbConfig) {
this.resetSubchannelList();
this.subchannels = addressList.map(address => this.channelControlHelper.createSubchannel(address, {}));
for (const subchannel of this.subchannels) {
const subchannelState = subchannel.getConnectivityState();
this.subchannelStateCounts[subchannelState] += 1;
if (subchannelState === channel_1.ConnectivityState.IDLE ||
subchannelState === channel_1.ConnectivityState.TRANSIENT_FAILURE) {
subchannel.startConnecting();
}
}
this.calculateAndUpdateState();
}
exitIdle() {
for (const subchannel of this.subchannels) {
subchannel.startConnecting();
}
}
resetBackoff() {
/* The pick first load balancer does not have a connection backoff, so this
* does nothing */
}
destroy() {
this.resetSubchannelList();
}
getTypeName() {
return TYPE_NAME;
}
replaceChannelControlHelper(channelControlHelper) {
this.channelControlHelper = channelControlHelper;
}
}
exports.RoundRobinLoadBalancer = RoundRobinLoadBalancer;
function setup() {
load_balancer_1.registerLoadBalancerType(TYPE_NAME, RoundRobinLoadBalancer);
}
exports.setup = setup;
//# sourceMappingURL=load-balancer-round-robin.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"load-balancer-round-robin.js","sourceRoot":"","sources":["../../src/load-balancer-round-robin.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;AAEH,mDAIyB;AACzB,uCAA8C;AAC9C,qCAOkB;AAIlB,MAAM,SAAS,GAAG,aAAa,CAAC;AAEhC,MAAM,gBAAgB;IACpB,YACmB,cAA4B,EACrC,YAAY,CAAC;QADJ,mBAAc,GAAd,cAAc,CAAc;QACrC,cAAS,GAAT,SAAS,CAAI;IACpB,CAAC;IAEJ,IAAI,CAAC,QAAkB;QACrB,MAAM,gBAAgB,GAAG,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QAC7D,IAAI,CAAC,SAAS,GAAG,CAAC,IAAI,CAAC,SAAS,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,cAAc,CAAC,MAAM,CAAC;QACnE,OAAO;YACL,cAAc,EAAE,uBAAc,CAAC,QAAQ;YACvC,UAAU,EAAE,gBAAgB;YAC5B,MAAM,EAAE,IAAI;SACb,CAAC;IACJ,CAAC;IAED;;;;OAIG;IACH,kBAAkB;QAChB,OAAO,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IAC7C,CAAC;CACF;AAUD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CAAC;IACjC,CAAC;IAED,QAAQ;QACN,KAAK,MAAM,UAAU,IAAI,IAAI,CAAC,WAAW,EAAE;YACzC,UAAU,CAAC,eAAe,EAAE,CAAC;SAC9B;IACH,CAAC;IACD,YAAY;QACV;0BACkB;IACpB,CAAC;IACD,OAAO;QACL,IAAI,CAAC,mBAAmB,EAAE,CAAC;IAC7B,CAAC;IACD,WAAW;QACT,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,2BAA2B,CACzB,oBAA0C;QAE1C,IAAI,CAAC,oBAAoB,GAAG,oBAAoB,CAAC;IACnD,CAAC;CACF;AA5ID,wDA4IC;AAED,SAAgB,KAAK;IACnB,wCAAwB,CAAC,SAAS,EAAE,sBAAsB,CAAC,CAAC;AAC9D,CAAC;AAFD,sBAEC"}

View File

@ -0,0 +1,78 @@
import { ChannelOptions } from './channel-options';
import { Subchannel } from './subchannel';
import { ConnectivityState } from './channel';
import { Picker } from './picker';
import { LoadBalancingConfig } from './load-balancing-config';
/**
* A collection of functions associated with a channel that a load balancer
* can call as necessary.
*/
export interface ChannelControlHelper {
/**
* Returns a subchannel connected to the specified address.
* @param subchannelAddress The address to connect to
* @param subchannelArgs Extra channel arguments specified by the load balancer
*/
createSubchannel(subchannelAddress: string, subchannelArgs: ChannelOptions): Subchannel;
/**
* Passes a new subchannel picker up to the channel. This is called if either
* the connectivity state changes or if a different picker is needed for any
* other reason.
* @param connectivityState New connectivity state
* @param picker New picker
*/
updateState(connectivityState: ConnectivityState, picker: Picker): void;
/**
* Request new data from the resolver.
*/
requestReresolution(): void;
}
/**
* Tracks one or more connected subchannels and determines which subchannel
* each request should use.
*/
export interface LoadBalancer {
/**
* Gives the load balancer a new list of addresses to start connecting to.
* The load balancer will start establishing connections with the new list,
* but will continue using any existing connections until the new connections
* are established
* @param addressList The new list of addresses to connect to
* @param lbConfig The load balancing config object from the service config,
* if one was provided
*/
updateAddressList(addressList: string[], lbConfig: LoadBalancingConfig | null): void;
/**
* If the load balancer is currently in the IDLE state, start connecting.
*/
exitIdle(): void;
/**
* If the load balancer is currently in the CONNECTING or TRANSIENT_FAILURE
* state, reset the current connection backoff timeout to its base value and
* transition to CONNECTING if in TRANSIENT_FAILURE.
*/
resetBackoff(): void;
/**
* The load balancer unrefs all of its subchannels and stops calling methods
* of its channel control helper.
*/
destroy(): void;
/**
* Get the type name for this load balancer type. Must be constant across an
* entire load balancer implementation class and must match the name that the
* balancer implementation class was registered with.
*/
getTypeName(): string;
/**
* Replace the existing ChannelControlHelper with a new one
* @param channelControlHelper The new ChannelControlHelper to use from now on
*/
replaceChannelControlHelper(channelControlHelper: ChannelControlHelper): void;
}
export interface LoadBalancerConstructor {
new (channelControlHelper: ChannelControlHelper): LoadBalancer;
}
export declare function registerLoadBalancerType(typeName: string, loadBalancerType: LoadBalancerConstructor): void;
export declare function createLoadBalancer(typeName: string, channelControlHelper: ChannelControlHelper): LoadBalancer | null;
export declare function isLoadBalancerNameRegistered(typeName: string): boolean;
export declare function registerAll(): void;

44
node_modules/@grpc/grpc-js/build/src/load-balancer.js generated vendored Normal file
View File

@ -0,0 +1,44 @@
"use strict";
/*
* Copyright 2019 gRPC authors.
*
* 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.
*
*/
Object.defineProperty(exports, "__esModule", { value: true });
const load_balancer_pick_first = require("./load-balancer-pick-first");
const load_balancer_round_robin = require("./load-balancer-round-robin");
const registeredLoadBalancerTypes = {};
function registerLoadBalancerType(typeName, loadBalancerType) {
registeredLoadBalancerTypes[typeName] = loadBalancerType;
}
exports.registerLoadBalancerType = registerLoadBalancerType;
function createLoadBalancer(typeName, channelControlHelper) {
if (typeName in registeredLoadBalancerTypes) {
return new registeredLoadBalancerTypes[typeName](channelControlHelper);
}
else {
return null;
}
}
exports.createLoadBalancer = createLoadBalancer;
function isLoadBalancerNameRegistered(typeName) {
return typeName in registeredLoadBalancerTypes;
}
exports.isLoadBalancerNameRegistered = isLoadBalancerNameRegistered;
function registerAll() {
load_balancer_pick_first.setup();
load_balancer_round_robin.setup();
}
exports.registerAll = registerAll;
//# sourceMappingURL=load-balancer.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"load-balancer.js","sourceRoot":"","sources":["../../src/load-balancer.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;AAOH,uEAAuE;AACvE,yEAAyE;AAgFzE,MAAM,2BAA2B,GAE7B,EAAE,CAAC;AAEP,SAAgB,wBAAwB,CACtC,QAAgB,EAChB,gBAAyC;IAEzC,2BAA2B,CAAC,QAAQ,CAAC,GAAG,gBAAgB,CAAC;AAC3D,CAAC;AALD,4DAKC;AAED,SAAgB,kBAAkB,CAChC,QAAgB,EAChB,oBAA0C;IAE1C,IAAI,QAAQ,IAAI,2BAA2B,EAAE;QAC3C,OAAO,IAAI,2BAA2B,CAAC,QAAQ,CAAC,CAAC,oBAAoB,CAAC,CAAC;KACxE;SAAM;QACL,OAAO,IAAI,CAAC;KACb;AACH,CAAC;AATD,gDASC;AAED,SAAgB,4BAA4B,CAAC,QAAgB;IAC3D,OAAO,QAAQ,IAAI,2BAA2B,CAAC;AACjD,CAAC;AAFD,oEAEC;AAED,SAAgB,WAAW;IACzB,wBAAwB,CAAC,KAAK,EAAE,CAAC;IACjC,yBAAyB,CAAC,KAAK,EAAE,CAAC;AACpC,CAAC;AAHD,kCAGC"}

View File

@ -0,0 +1,16 @@
export interface RoundRobinConfig {
}
export interface XdsConfig {
balancerName: string;
childPolicy: LoadBalancingConfig[];
fallbackPolicy: LoadBalancingConfig[];
}
export interface GrpcLbConfig {
childPolicy: LoadBalancingConfig[];
}
export interface LoadBalancingConfig {
round_robin?: RoundRobinConfig;
xds?: XdsConfig;
grpclb?: GrpcLbConfig;
}
export declare function validateConfig(obj: any): LoadBalancingConfig;

View File

@ -0,0 +1,84 @@
"use strict";
/*
* Copyright 2019 gRPC authors.
*
* 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.
*
*/
Object.defineProperty(exports, "__esModule", { value: true });
/* In these functions we assume the input came from a JSON object. Therefore we
* expect that the prototype is uninteresting and that `in` can be used
* effectively */
function validateXdsConfig(xds) {
if (!('balancerName' in xds) || typeof xds.balancerName !== 'string') {
throw new Error('Invalid xds config: invalid balancerName');
}
const xdsConfig = {
balancerName: xds.balancerName,
childPolicy: [],
fallbackPolicy: [],
};
if ('childPolicy' in xds) {
if (!Array.isArray(xds.childPolicy)) {
throw new Error('Invalid xds config: invalid childPolicy');
}
for (const policy of xds.childPolicy) {
xdsConfig.childPolicy.push(validateConfig(policy));
}
}
if ('fallbackPolicy' in xds) {
if (!Array.isArray(xds.fallbackPolicy)) {
throw new Error('Invalid xds config: invalid fallbackPolicy');
}
for (const policy of xds.fallbackPolicy) {
xdsConfig.fallbackPolicy.push(validateConfig(policy));
}
}
return xdsConfig;
}
function validateGrpcLbConfig(grpclb) {
const grpcLbConfig = {
childPolicy: [],
};
if ('childPolicy' in grpclb) {
if (!Array.isArray(grpclb.childPolicy)) {
throw new Error('Invalid xds config: invalid childPolicy');
}
for (const policy of grpclb.childPolicy) {
grpcLbConfig.childPolicy.push(validateConfig(policy));
}
}
return grpcLbConfig;
}
function validateConfig(obj) {
if ('round_robin' in obj) {
if ('xds' in obj || 'grpclb' in obj) {
throw new Error('Multiple load balancing policies configured');
}
if (obj['round_robin'] instanceof Object) {
return { round_robin: {} };
}
}
if ('xds' in obj) {
if ('grpclb' in obj) {
throw new Error('Multiple load balancing policies configured');
}
return { xds: validateXdsConfig(obj.xds) };
}
if ('grpclb' in obj) {
return { grpclb: validateGrpcLbConfig(obj.grpclb) };
}
throw new Error('No recognized load balancing policy configured');
}
exports.validateConfig = validateConfig;
//# sourceMappingURL=load-balancing-config.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"load-balancing-config.js","sourceRoot":"","sources":["../../src/load-balancing-config.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;AA+BH;;iBAEiB;AAEjB,SAAS,iBAAiB,CAAC,GAAQ;IACjC,IAAI,CAAC,CAAC,cAAc,IAAI,GAAG,CAAC,IAAI,OAAO,GAAG,CAAC,YAAY,KAAK,QAAQ,EAAE;QACpE,MAAM,IAAI,KAAK,CAAC,0CAA0C,CAAC,CAAC;KAC7D;IACD,MAAM,SAAS,GAAc;QAC3B,YAAY,EAAE,GAAG,CAAC,YAAY;QAC9B,WAAW,EAAE,EAAE;QACf,cAAc,EAAE,EAAE;KACnB,CAAC;IACF,IAAI,aAAa,IAAI,GAAG,EAAE;QACxB,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE;YACnC,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAC;SAC5D;QACD,KAAK,MAAM,MAAM,IAAI,GAAG,CAAC,WAAW,EAAE;YACpC,SAAS,CAAC,WAAW,CAAC,IAAI,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC,CAAC;SACpD;KACF;IACD,IAAI,gBAAgB,IAAI,GAAG,EAAE;QAC3B,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,EAAE;YACtC,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;SAC/D;QACD,KAAK,MAAM,MAAM,IAAI,GAAG,CAAC,cAAc,EAAE;YACvC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,cAAc,CAAC,MAAM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pc-js/build/src/logging.d.ts generated vendored Normal file
View File

@ -0,0 +1,7 @@
/// <reference types="node" />
import { LogVerbosity } from './constants';
export declare const getLogger: () => Partial<Console>;
export declare const setLogger: (logger: Partial<Console>) => void;
export declare const setLoggerVerbosity: (verbosity: LogVerbosity) => void;
export declare const log: (severity: LogVerbosity, ...args: any[]) => void;
export declare function trace(severity: LogVerbosity, tracer: string, text: string): void;

62
node_modules/@grpc/grpc-js/build/src/logging.js generated vendored Normal file
View File

@ -0,0 +1,62 @@
"use strict";
/*
* Copyright 2019 gRPC authors.
*
* 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.
*
*/
Object.defineProperty(exports, "__esModule", { value: true });
const constants_1 = require("./constants");
let _logger = console;
let _logVerbosity = constants_1.LogVerbosity.ERROR;
if (process.env.GRPC_VERBOSITY) {
switch (process.env.GRPC_VERBOSITY) {
case 'DEBUG':
_logVerbosity = constants_1.LogVerbosity.DEBUG;
break;
case 'INFO':
_logVerbosity = constants_1.LogVerbosity.INFO;
break;
case 'ERROR':
_logVerbosity = constants_1.LogVerbosity.ERROR;
break;
default:
// Ignore any other values
}
}
exports.getLogger = () => {
return _logger;
};
exports.setLogger = (logger) => {
_logger = logger;
};
exports.setLoggerVerbosity = (verbosity) => {
_logVerbosity = verbosity;
};
// tslint:disable-next-line no-any
exports.log = (severity, ...args) => {
if (severity >= _logVerbosity && typeof _logger.error === 'function') {
_logger.error(...args);
}
};
const enabledTracers = process.env.GRPC_TRACE
? process.env.GRPC_TRACE.split(',')
: [];
const allEnabled = enabledTracers.includes('all');
function trace(severity, tracer, text) {
if (allEnabled || enabledTracers.includes(tracer)) {
exports.log(severity, new Date().toISOString() + ' | ' + tracer + ' | ' + text);
}
}
exports.trace = trace;
//# sourceMappingURL=logging.js.map

1
node_modules/@grpc/grpc-js/build/src/logging.js.map generated vendored Normal file
View File

@ -0,0 +1 @@
{"version":3,"file":"logging.js","sourceRoot":"","sources":["../../src/logging.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;AAEH,2CAA2C;AAE3C,IAAI,OAAO,GAAqB,OAAO,CAAC;AACxC,IAAI,aAAa,GAAiB,wBAAY,CAAC,KAAK,CAAC;AAErD,IAAI,OAAO,CAAC,GAAG,CAAC,cAAc,EAAE;IAC9B,QAAQ,OAAO,CAAC,GAAG,CAAC,cAAc,EAAE;QAClC,KAAK,OAAO;YACV,aAAa,GAAG,wBAAY,CAAC,KAAK,CAAC;YACnC,MAAM;QACR,KAAK,MAAM;YACT,aAAa,GAAG,wBAAY,CAAC,IAAI,CAAC;YAClC,MAAM;QACR,KAAK,OAAO;YACV,aAAa,GAAG,wBAAY,CAAC,KAAK,CAAC;YACnC,MAAM;QACR,QAAQ;QACR,0BAA0B;KAC3B;CACF;AAEY,QAAA,SAAS,GAAG,GAAqB,EAAE;IAC9C,OAAO,OAAO,CAAC;AACjB,CAAC,CAAC;AAEW,QAAA,SAAS,GAAG,CAAC,MAAwB,EAAQ,EAAE;IAC1D,OAAO,GAAG,MAAM,CAAC;AACnB,CAAC,CAAC;AAEW,QAAA,kBAAkB,GAAG,CAAC,SAAuB,EAAQ,EAAE;IAClE,aAAa,GAAG,SAAS,CAAC;AAC5B,CAAC,CAAC;AAEF,kCAAkC;AACrB,QAAA,GAAG,GAAG,CAAC,QAAsB,EAAE,GAAG,IAAW,EAAQ,EAAE;IAClE,IAAI,QAAQ,IAAI,aAAa,IAAI,OAAO,OAAO,CAAC,KAAK,KAAK,UAAU,EAAE;QACpE,OAAO,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,CAAC;KACxB;AACH,CAAC,CAAC;AAEF,MAAM,cAAc,GAAG,OAAO,CAAC,GAAG,CAAC,UAAU;IAC3C,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,KAAK,CAAC,GAAG,CAAC;IACnC,CAAC,CAAC,EAAE,CAAC;AACP,MAAM,UAAU,GAAG,cAAc,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;AAElD,SAAgB,KAAK,CACnB,QAAsB,EACtB,MAAc,EACd,IAAY;IAEZ,IAAI,UAAU,IAAI,cAAc,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE;QACjD,WAAG,CAAC,QAAQ,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,GAAG,KAAK,GAAG,MAAM,GAAG,KAAK,GAAG,IAAI,CAAC,CAAC;KACzE;AACH,CAAC;AARD,sBAQC"}

62
node_modules/@grpc/grpc-js/build/src/make-client.d.ts generated vendored Normal file
View File

@ -0,0 +1,62 @@
/// <reference types="node" />
import { ChannelCredentials } from './channel-credentials';
import { ChannelOptions } from './channel-options';
import { Client } from './client';
export interface Serialize<T> {
(value: T): Buffer;
}
export interface Deserialize<T> {
(bytes: Buffer): T;
}
export interface MethodDefinition<RequestType, ResponseType> {
path: string;
requestStream: boolean;
responseStream: boolean;
requestSerialize: Serialize<RequestType>;
responseSerialize: Serialize<ResponseType>;
requestDeserialize: Deserialize<RequestType>;
responseDeserialize: Deserialize<ResponseType>;
originalName?: string;
}
export interface ServiceDefinition {
[index: string]: MethodDefinition<any, any>;
}
export interface ProtobufTypeDefinition {
format: string;
type: object;
fileDescriptorProtos: Buffer[];
}
export interface PackageDefinition {
[index: string]: ServiceDefinition | ProtobufTypeDefinition;
}
export interface ServiceClient extends Client {
[methodName: string]: Function;
}
export interface ServiceClientConstructor {
new (address: string, credentials: ChannelCredentials, options?: Partial<ChannelOptions>): ServiceClient;
service: ServiceDefinition;
}
/**
* Creates a constructor for a client with the given methods, as specified in
* the methods argument. The resulting class will have an instance method for
* each method in the service, which is a partial application of one of the
* [Client]{@link grpc.Client} request methods, depending on `requestSerialize`
* and `responseSerialize`, with the `method`, `serialize`, and `deserialize`
* arguments predefined.
* @param methods An object mapping method names to
* method attributes
* @param serviceName The fully qualified name of the service
* @param classOptions An options object.
* @return New client constructor, which is a subclass of
* {@link grpc.Client}, and has the same arguments as that constructor.
*/
export declare function makeClientConstructor(methods: ServiceDefinition, serviceName: string, classOptions?: {}): ServiceClientConstructor;
export interface GrpcObject {
[index: string]: GrpcObject | ServiceClientConstructor | ProtobufTypeDefinition;
}
/**
* Load a gRPC package definition as a gRPC object hierarchy.
* @param packageDef The package definition object.
* @return The resulting gRPC object.
*/
export declare function loadPackageDefinition(packageDef: PackageDefinition): GrpcObject;

128
node_modules/@grpc/grpc-js/build/src/make-client.js generated vendored Normal file
View File

@ -0,0 +1,128 @@
"use strict";
/*
* Copyright 2019 gRPC authors.
*
* 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.
*
*/
Object.defineProperty(exports, "__esModule", { value: true });
const client_1 = require("./client");
/**
* Map with short names for each of the requester maker functions. Used in
* makeClientConstructor
* @private
*/
const requesterFuncs = {
unary: client_1.Client.prototype.makeUnaryRequest,
server_stream: client_1.Client.prototype.makeServerStreamRequest,
client_stream: client_1.Client.prototype.makeClientStreamRequest,
bidi: client_1.Client.prototype.makeBidiStreamRequest,
};
/**
* Creates a constructor for a client with the given methods, as specified in
* the methods argument. The resulting class will have an instance method for
* each method in the service, which is a partial application of one of the
* [Client]{@link grpc.Client} request methods, depending on `requestSerialize`
* and `responseSerialize`, with the `method`, `serialize`, and `deserialize`
* arguments predefined.
* @param methods An object mapping method names to
* method attributes
* @param serviceName The fully qualified name of the service
* @param classOptions An options object.
* @return New client constructor, which is a subclass of
* {@link grpc.Client}, and has the same arguments as that constructor.
*/
function makeClientConstructor(methods, serviceName, classOptions) {
if (!classOptions) {
classOptions = {};
}
class ServiceClientImpl extends client_1.Client {
}
Object.keys(methods).forEach(name => {
const attrs = methods[name];
let methodType;
// TODO(murgatroid99): Verify that we don't need this anymore
if (typeof name === 'string' && name.charAt(0) === '$') {
throw new Error('Method names cannot start with $');
}
if (attrs.requestStream) {
if (attrs.responseStream) {
methodType = 'bidi';
}
else {
methodType = 'client_stream';
}
}
else {
if (attrs.responseStream) {
methodType = 'server_stream';
}
else {
methodType = 'unary';
}
}
const serialize = attrs.requestSerialize;
const deserialize = attrs.responseDeserialize;
const methodFunc = partial(requesterFuncs[methodType], attrs.path, serialize, deserialize);
ServiceClientImpl.prototype[name] = methodFunc;
// Associate all provided attributes with the method
Object.assign(ServiceClientImpl.prototype[name], attrs);
if (attrs.originalName) {
ServiceClientImpl.prototype[attrs.originalName] =
ServiceClientImpl.prototype[name];
}
});
ServiceClientImpl.service = methods;
return ServiceClientImpl;
}
exports.makeClientConstructor = makeClientConstructor;
function partial(fn, path, serialize, deserialize) {
// tslint:disable-next-line:no-any
return function (...args) {
return fn.call(this, path, serialize, deserialize, ...args);
};
}
function isProtobufTypeDefinition(obj) {
return 'format' in obj;
}
/**
* Load a gRPC package definition as a gRPC object hierarchy.
* @param packageDef The package definition object.
* @return The resulting gRPC object.
*/
function loadPackageDefinition(packageDef) {
const result = {};
for (const serviceFqn in packageDef) {
if (packageDef.hasOwnProperty(serviceFqn)) {
const service = packageDef[serviceFqn];
const nameComponents = serviceFqn.split('.');
const serviceName = nameComponents[nameComponents.length - 1];
let current = result;
for (const packageName of nameComponents.slice(0, -1)) {
if (!current[packageName]) {
current[packageName] = {};
}
current = current[packageName];
}
if (isProtobufTypeDefinition(service)) {
current[serviceName] = service;
}
else {
current[serviceName] = makeClientConstructor(service, serviceName, {});
}
}
}
return result;
}
exports.loadPackageDefinition = loadPackageDefinition;
//# sourceMappingURL=make-client.js.map

View File

@ -0,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C,GAAG,CAAC,CAAC;YAC7C,MAAM,WAAW,GAAG,cAAc,CAAC,cAAc,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;YAC9D,IAAI,OAAO,GAAG,MAAM,CAAC;YACrB,KAAK,MAAM,WAAW,IAAI,cAAc,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE;gBACrD,IAAI,CAAC,OAAO,CAAC,WAAW,CAAC,EAAE;oBACzB,OAAO,CAAC,WAAW,CAAC,GAAG,EAAE,CAAC;iBAC3B;gBACD,OAAO,GAAG,OAAO,CAAC,WAAW,CAAe,CAAC;aAC9C;YACD,IAAI,wBAAwB,CAAC,OAAO,CAAC,EAAE;gBACrC,OAAO,CAAC,WAAW,CAAC,GAAG,OAAO,CAAC;aAChC;iBAAM;gBACL,OAAO,CAAC,WAAW,CAAC,GAAG,qBAAqB,CAAC,OAAO,EAAE,WAAW,EAAE,EAAE,CAAC,CAAC;aACxE;SACF;KACF;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAxBD,sDAwBC"}

View File

@ -0,0 +1,12 @@
import { Call } from './call-stream';
import { StatusObject } from './call-stream';
import { Channel } from './channel';
import { BaseFilter, Filter, FilterFactory } from './filter';
export declare class MetadataStatusFilter extends BaseFilter implements Filter {
receiveTrailers(status: Promise<StatusObject>): Promise<StatusObject>;
}
export declare class MetadataStatusFilterFactory implements FilterFactory<MetadataStatusFilter> {
private readonly channel;
constructor(channel: Channel);
createFilter(callStream: Call): MetadataStatusFilter;
}

View File

@ -0,0 +1,54 @@
"use strict";
/*
* Copyright 2019 gRPC authors.
*
* 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.
*
*/
Object.defineProperty(exports, "__esModule", { value: true });
const constants_1 = require("./constants");
const filter_1 = require("./filter");
class MetadataStatusFilter extends filter_1.BaseFilter {
async receiveTrailers(status) {
// tslint:disable-next-line:prefer-const
let { code, details, metadata } = await status;
if (code !== constants_1.Status.UNKNOWN) {
// we already have a known status, so don't assign a new one.
return { code, details, metadata };
}
const metadataMap = metadata.getMap();
if (typeof metadataMap['grpc-status'] === 'string') {
const receivedCode = Number(metadataMap['grpc-status']);
if (receivedCode in constants_1.Status) {
code = receivedCode;
}
metadata.remove('grpc-status');
}
if (typeof metadataMap['grpc-message'] === 'string') {
details = decodeURI(metadataMap['grpc-message']);
metadata.remove('grpc-message');
}
return { code, details, metadata };
}
}
exports.MetadataStatusFilter = MetadataStatusFilter;
class MetadataStatusFilterFactory {
constructor(channel) {
this.channel = channel;
}
createFilter(callStream) {
return new MetadataStatusFilter();
}
}
exports.MetadataStatusFilterFactory = MetadataStatusFilterFactory;
//# sourceMappingURL=metadata-status-filter.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"metadata-status-filter.js","sourceRoot":"","sources":["../../src/metadata-status-filter.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;AAKH,2CAAqC;AACrC,qCAA6D;AAE7D,MAAa,oBAAqB,SAAQ,mBAAU;IAClD,KAAK,CAAC,eAAe,CAAC,MAA6B;QACjD,wCAAwC;QACxC,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,GAAG,MAAM,MAAM,CAAC;QAC/C,IAAI,IAAI,KAAK,kBAAM,CAAC,OAAO,EAAE;YAC3B,6DAA6D;YAC7D,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC;SACpC;QACD,MAAM,WAAW,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC;QACtC,IAAI,OAAO,WAAW,CAAC,aAAa,CAAC,KAAK,QAAQ,EAAE;YAClD,MAAM,YAAY,GAAG,MAAM,CAAC,WAAW,CAAC,aAAa,CAAC,CAAC,CAAC;YACxD,IAAI,YAAY,IAAI,kBAAM,EAAE;gBAC1B,IAAI,GAAG,YAAY,CAAC;aACrB;YACD,QAAQ,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;SAChC;QACD,IAAI,OAAO,WAAW,CAAC,cAAc,CAAC,KAAK,QAAQ,EAAE;YACnD,OAAO,GAAG,SAAS,CAAC,WAAW,CAAC,cAAc,CAAW,CAAC,CAAC;YAC3D,QAAQ,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC;SACjC;QACD,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC;IACrC,CAAC;CACF;AAtBD,oDAsBC;AAED,MAAa,2BAA2B;IAEtC,YAA6B,OAAgB;QAAhB,YAAO,GAAP,OAAO,CAAS;IAAG,CAAC;IACjD,YAAY,CAAC,UAAgB;QAC3B,OAAO,IAAI,oBAAoB,EAAE,CAAC;IACpC,CAAC;CACF;AAND,kEAMC"}

79
node_modules/@grpc/grpc-js/build/src/metadata.d.ts generated vendored Normal file
View File

@ -0,0 +1,79 @@
/// <reference types="node" />
import * as http2 from 'http2';
export declare type MetadataValue = string | Buffer;
export declare type MetadataObject = Map<string, MetadataValue[]>;
export interface MetadataOptions {
idempotentRequest?: boolean;
waitForReady?: boolean;
cacheableRequest?: boolean;
corked?: boolean;
}
/**
* A class for storing metadata. Keys are normalized to lowercase ASCII.
*/
export declare class Metadata {
protected internalRepr: MetadataObject;
private options;
constructor(options?: MetadataOptions);
/**
* Sets the given value for the given key by replacing any other values
* associated with that key. Normalizes the key.
* @param key The key to whose value should be set.
* @param value The value to set. Must be a buffer if and only
* if the normalized key ends with '-bin'.
*/
set(key: string, value: MetadataValue): void;
/**
* Adds the given value for the given key by appending to a list of previous
* values associated with that key. Normalizes the key.
* @param key The key for which a new value should be appended.
* @param value The value to add. Must be a buffer if and only
* if the normalized key ends with '-bin'.
*/
add(key: string, value: MetadataValue): void;
/**
* Removes the given key and any associated values. Normalizes the key.
* @param key The key whose values should be removed.
*/
remove(key: string): void;
/**
* Gets a list of all values associated with the key. Normalizes the key.
* @param key The key whose value should be retrieved.
* @return A list of values associated with the given key.
*/
get(key: string): MetadataValue[];
/**
* Gets a plain object mapping each key to the first value associated with it.
* This reflects the most common way that people will want to see metadata.
* @return A key/value mapping of the metadata.
*/
getMap(): {
[key: string]: MetadataValue;
};
/**
* Clones the metadata object.
* @return The newly cloned object.
*/
clone(): Metadata;
/**
* Merges all key-value pairs from a given Metadata object into this one.
* If both this object and the given object have values in the same key,
* values from the other Metadata object will be appended to this object's
* values.
* @param other A Metadata object.
*/
merge(other: Metadata): void;
setOptions(options: MetadataOptions): void;
getOptions(): MetadataOptions;
/**
* Creates an OutgoingHttpHeaders object that can be used with the http2 API.
*/
toHttp2Headers(): http2.OutgoingHttpHeaders;
private _getCoreRepresentation;
/**
* Returns a new Metadata object based fields in a given IncomingHttpHeaders
* object.
* @param headers An IncomingHttpHeaders object.
*/
static fromHttp2Headers(headers: http2.IncomingHttpHeaders): Metadata;
}

254
node_modules/@grpc/grpc-js/build/src/metadata.js generated vendored Normal file
View File

@ -0,0 +1,254 @@
"use strict";
/*
* Copyright 2019 gRPC authors.
*
* 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.
*
*/
Object.defineProperty(exports, "__esModule", { value: true });
const logging_1 = require("./logging");
const constants_1 = require("./constants");
const LEGAL_KEY_REGEX = /^[0-9a-z_.-]+$/;
const LEGAL_NON_BINARY_VALUE_REGEX = /^[ -~]*$/;
function isLegalKey(key) {
return LEGAL_KEY_REGEX.test(key);
}
function isLegalNonBinaryValue(value) {
return LEGAL_NON_BINARY_VALUE_REGEX.test(value);
}
function isBinaryKey(key) {
return key.endsWith('-bin');
}
function isCustomMetadata(key) {
return !key.startsWith('grpc-');
}
function normalizeKey(key) {
return key.toLowerCase();
}
function validate(key, value) {
if (!isLegalKey(key)) {
throw new Error('Metadata key "' + key + '" contains illegal characters');
}
if (value != null) {
if (isBinaryKey(key)) {
if (!(value instanceof Buffer)) {
throw new Error("keys that end with '-bin' must have Buffer values");
}
}
else {
if (value instanceof Buffer) {
throw new Error("keys that don't end with '-bin' must have String values");
}
if (!isLegalNonBinaryValue(value)) {
throw new Error('Metadata string value "' + value + '" contains illegal characters');
}
}
}
}
/**
* A class for storing metadata. Keys are normalized to lowercase ASCII.
*/
class Metadata {
constructor(options) {
this.internalRepr = new Map();
if (options === undefined) {
this.options = {};
}
else {
this.options = options;
}
}
/**
* Sets the given value for the given key by replacing any other values
* associated with that key. Normalizes the key.
* @param key The key to whose value should be set.
* @param value The value to set. Must be a buffer if and only
* if the normalized key ends with '-bin'.
*/
set(key, value) {
key = normalizeKey(key);
validate(key, value);
this.internalRepr.set(key, [value]);
}
/**
* Adds the given value for the given key by appending to a list of previous
* values associated with that key. Normalizes the key.
* @param key The key for which a new value should be appended.
* @param value The value to add. Must be a buffer if and only
* if the normalized key ends with '-bin'.
*/
add(key, value) {
key = normalizeKey(key);
validate(key, value);
const existingValue = this.internalRepr.get(key);
if (existingValue === undefined) {
this.internalRepr.set(key, [value]);
}
else {
existingValue.push(value);
}
}
/**
* Removes the given key and any associated values. Normalizes the key.
* @param key The key whose values should be removed.
*/
remove(key) {
key = normalizeKey(key);
validate(key);
this.internalRepr.delete(key);
}
/**
* Gets a list of all values associated with the key. Normalizes the key.
* @param key The key whose value should be retrieved.
* @return A list of values associated with the given key.
*/
get(key) {
key = normalizeKey(key);
validate(key);
return this.internalRepr.get(key) || [];
}
/**
* Gets a plain object mapping each key to the first value associated with it.
* This reflects the most common way that people will want to see metadata.
* @return A key/value mapping of the metadata.
*/
getMap() {
const result = {};
this.internalRepr.forEach((values, key) => {
if (values.length > 0) {
const v = values[0];
result[key] = v instanceof Buffer ? v.slice() : v;
}
});
return result;
}
/**
* Clones the metadata object.
* @return The newly cloned object.
*/
clone() {
const newMetadata = new Metadata();
const newInternalRepr = newMetadata.internalRepr;
this.internalRepr.forEach((value, key) => {
const clonedValue = value.map(v => {
if (v instanceof Buffer) {
return Buffer.from(v);
}
else {
return v;
}
});
newInternalRepr.set(key, clonedValue);
});
return newMetadata;
}
/**
* Merges all key-value pairs from a given Metadata object into this one.
* If both this object and the given object have values in the same key,
* values from the other Metadata object will be appended to this object's
* values.
* @param other A Metadata object.
*/
merge(other) {
other.internalRepr.forEach((values, key) => {
const mergedValue = (this.internalRepr.get(key) || []).concat(values);
this.internalRepr.set(key, mergedValue);
});
}
setOptions(options) {
this.options = options;
}
getOptions() {
return this.options;
}
/**
* Creates an OutgoingHttpHeaders object that can be used with the http2 API.
*/
toHttp2Headers() {
// NOTE: Node <8.9 formats http2 headers incorrectly.
const result = {};
this.internalRepr.forEach((values, key) => {
// We assume that the user's interaction with this object is limited to
// through its public API (i.e. keys and values are already validated).
result[key] = values.map(value => {
if (value instanceof Buffer) {
return value.toString('base64');
}
else {
return value;
}
});
});
return result;
}
// For compatibility with the other Metadata implementation
_getCoreRepresentation() {
return this.internalRepr;
}
/**
* Returns a new Metadata object based fields in a given IncomingHttpHeaders
* object.
* @param headers An IncomingHttpHeaders object.
*/
static fromHttp2Headers(headers) {
const result = new Metadata();
Object.keys(headers).forEach(key => {
// Reserved headers (beginning with `:`) are not valid keys.
if (key.charAt(0) === ':') {
return;
}
const values = headers[key];
try {
if (isBinaryKey(key)) {
if (Array.isArray(values)) {
values.forEach(value => {
result.add(key, Buffer.from(value, 'base64'));
});
}
else if (values !== undefined) {
if (isCustomMetadata(key)) {
values.split(',').forEach(v => {
result.add(key, Buffer.from(v.trim(), 'base64'));
});
}
else {
result.add(key, Buffer.from(values, 'base64'));
}
}
}
else {
if (Array.isArray(values)) {
values.forEach(value => {
result.add(key, value);
});
}
else if (values !== undefined) {
if (isCustomMetadata(key)) {
values.split(',').forEach(v => result.add(key, v.trim()));
}
else {
result.add(key, values);
}
}
}
}
catch (error) {
const message = `Failed to add metadata entry ${key}: ${values}. ${error.message}. For more information see https://github.com/grpc/grpc-node/issues/1173`;
logging_1.log(constants_1.LogVerbosity.ERROR, message);
}
});
return result;
}
}
exports.Metadata = Metadata;
//# sourceMappingURL=metadata.js.map

1
node_modules/@grpc/grpc-js/build/src/metadata.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,37 @@
/// <reference types="node" />
import { Duplex, Readable, Writable } from 'stream';
import { EmitterAugmentation1 } from './events';
export declare type WriteCallback = (error: Error | null | undefined) => void;
export interface IntermediateObjectReadable<T> extends Readable {
read(size?: number): any & T;
}
export declare type ObjectReadable<T> = {
read(size?: number): T;
} & EmitterAugmentation1<'data', T> & IntermediateObjectReadable<T>;
export interface IntermediateObjectWritable<T> extends Writable {
_write(chunk: any & T, encoding: string, callback: Function): void;
write(chunk: any & T, cb?: WriteCallback): boolean;
write(chunk: any & T, encoding?: any, cb?: WriteCallback): boolean;
setDefaultEncoding(encoding: string): this;
end(): void;
end(chunk: any & T, cb?: Function): void;
end(chunk: any & T, encoding?: any, cb?: Function): void;
}
export interface ObjectWritable<T> extends IntermediateObjectWritable<T> {
_write(chunk: T, encoding: string, callback: Function): void;
write(chunk: T, cb?: Function): boolean;
write(chunk: T, encoding?: any, cb?: Function): boolean;
setDefaultEncoding(encoding: string): this;
end(): void;
end(chunk: T, cb?: Function): void;
end(chunk: T, encoding?: any, cb?: Function): void;
}
export declare type ObjectDuplex<T, U> = {
read(size?: number): U;
_write(chunk: T, encoding: string, callback: Function): void;
write(chunk: T, cb?: Function): boolean;
write(chunk: T, encoding?: any, cb?: Function): boolean;
end(): void;
end(chunk: T, cb?: Function): void;
end(chunk: T, encoding?: any, cb?: Function): void;
} & Duplex & ObjectWritable<T> & ObjectReadable<U>;

19
node_modules/@grpc/grpc-js/build/src/object-stream.js generated vendored Normal file
View File

@ -0,0 +1,19 @@
"use strict";
/*
* Copyright 2019 gRPC authors.
*
* 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.
*
*/
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=object-stream.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"object-stream.js","sourceRoot":"","sources":["../../src/object-stream.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG"}

71
node_modules/@grpc/grpc-js/build/src/picker.d.ts generated vendored Normal file
View File

@ -0,0 +1,71 @@
import { Subchannel } from './subchannel';
import { StatusObject } from './call-stream';
import { Metadata } from './metadata';
import { LoadBalancer } from './load-balancer';
export declare enum PickResultType {
COMPLETE = 0,
QUEUE = 1,
TRANSIENT_FAILURE = 2
}
export interface PickResult {
pickResultType: PickResultType;
/**
* The subchannel to use as the transport for the call. Only meaningful if
* `pickResultType` is COMPLETE. If null, indicates that the call should be
* dropped.
*/
subchannel: Subchannel | null;
/**
* The status object to end the call with. Populated if and only if
* `pickResultType` is TRANSIENT_FAILURE.
*/
status: StatusObject | null;
}
export interface CompletePickResult extends PickResult {
pickResultType: PickResultType.COMPLETE;
subchannel: Subchannel | null;
status: null;
}
export interface QueuePickResult extends PickResult {
pickResultType: PickResultType.QUEUE;
subchannel: null;
status: null;
}
export interface TransientFailurePickResult extends PickResult {
pickResultType: PickResultType.TRANSIENT_FAILURE;
subchannel: null;
status: StatusObject;
}
export interface PickArgs {
metadata: Metadata;
}
/**
* A proxy object representing the momentary state of a load balancer. Picks
* subchannels or returns other information based on that state. Should be
* replaced every time the load balancer changes state.
*/
export interface Picker {
pick(pickArgs: PickArgs): PickResult;
}
/**
* A standard picker representing a load balancer in the TRANSIENT_FAILURE
* state. Always responds to every pick request with an UNAVAILABLE status.
*/
export declare class UnavailablePicker implements Picker {
private status;
constructor(status?: StatusObject);
pick(pickArgs: PickArgs): TransientFailurePickResult;
}
/**
* A standard picker representing a load balancer in the IDLE or CONNECTING
* state. Always responds to every pick request with a QUEUE pick result
* indicating that the pick should be tried again with the next `Picker`. Also
* reports back to the load balancer that a connection should be established
* once any pick is attempted.
*/
export declare class QueuePicker {
private loadBalancer;
private calledExitIdle;
constructor(loadBalancer: LoadBalancer);
pick(pickArgs: PickArgs): QueuePickResult;
}

81
node_modules/@grpc/grpc-js/build/src/picker.js generated vendored Normal file
View File

@ -0,0 +1,81 @@
"use strict";
/*
* Copyright 2019 gRPC authors.
*
* 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.
*
*/
Object.defineProperty(exports, "__esModule", { value: true });
const metadata_1 = require("./metadata");
const constants_1 = require("./constants");
var PickResultType;
(function (PickResultType) {
PickResultType[PickResultType["COMPLETE"] = 0] = "COMPLETE";
PickResultType[PickResultType["QUEUE"] = 1] = "QUEUE";
PickResultType[PickResultType["TRANSIENT_FAILURE"] = 2] = "TRANSIENT_FAILURE";
})(PickResultType = exports.PickResultType || (exports.PickResultType = {}));
/**
* A standard picker representing a load balancer in the TRANSIENT_FAILURE
* state. Always responds to every pick request with an UNAVAILABLE status.
*/
class UnavailablePicker {
constructor(status) {
if (status !== undefined) {
this.status = status;
}
else {
this.status = {
code: constants_1.Status.UNAVAILABLE,
details: 'No connection established',
metadata: new metadata_1.Metadata(),
};
}
}
pick(pickArgs) {
return {
pickResultType: PickResultType.TRANSIENT_FAILURE,
subchannel: null,
status: this.status,
};
}
}
exports.UnavailablePicker = UnavailablePicker;
/**
* A standard picker representing a load balancer in the IDLE or CONNECTING
* state. Always responds to every pick request with a QUEUE pick result
* indicating that the pick should be tried again with the next `Picker`. Also
* reports back to the load balancer that a connection should be established
* once any pick is attempted.
*/
class QueuePicker {
// Constructed with a load balancer. Calls exitIdle on it the first time pick is called
constructor(loadBalancer) {
this.loadBalancer = loadBalancer;
this.calledExitIdle = false;
}
pick(pickArgs) {
if (!this.calledExitIdle) {
process.nextTick(() => {
this.loadBalancer.exitIdle();
});
this.calledExitIdle = true;
}
return {
pickResultType: PickResultType.QUEUE,
subchannel: null,
status: null,
};
}
}
exports.QueuePicker = QueuePicker;
//# sourceMappingURL=picker.js.map

1
node_modules/@grpc/grpc-js/build/src/picker.js.map generated vendored Normal file
View File

@ -0,0 +1 @@
{"version":3,"file":"picker.js","sourceRoot":"","sources":["../../src/picker.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;AAIH,yCAAsC;AACtC,2CAAqC;AAGrC,IAAY,cAIX;AAJD,WAAY,cAAc;IACxB,2DAAQ,CAAA;IACR,qDAAK,CAAA;IACL,6EAAiB,CAAA;AACnB,CAAC,EAJW,cAAc,GAAd,sBAAc,KAAd,sBAAc,QAIzB;AAgDD;;;GAGG;AACH,MAAa,iBAAiB;IAE5B,YAAY,MAAqB;QAC/B,IAAI,MAAM,KAAK,SAAS,EAAE;YACxB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;SACtB;aAAM;YACL,IAAI,CAAC,MAAM,GAAG;gBACZ,IAAI,EAAE,kBAAM,CAAC,WAAW;gBACxB,OAAO,EAAE,2BAA2B;gBACpC,QAAQ,EAAE,IAAI,mBAAQ,EAAE;aACzB,CAAC;SACH;IACH,CAAC;IACD,IAAI,CAAC,QAAkB;QACrB,OAAO;YACL,cAAc,EAAE,cAAc,CAAC,iBAAiB;YAChD,UAAU,EAAE,IAAI;YAChB,MAAM,EAAE,IAAI,CAAC,MAAM;SACpB,CAAC;IACJ,CAAC;CACF;AApBD,8CAoBC;AAED;;;;;;GAMG;AACH,MAAa,WAAW;IAEtB,uFAAuF;IACvF,YAAoB,YAA0B;QAA1B,iBAAY,GAAZ,YAAY,CAAc;QAFtC,mBAAc,GAAG,KAAK,CAAC;IAEkB,CAAC;IAElD,IAAI,CAAC,QAAkB;QACrB,IAAI,CAAC,IAAI,CAAC,cAAc,EAAE;YACxB,OAAO,CAAC,QAAQ,CAAC,GAAG,EAAE;gBACpB,IAAI,CAAC,YAAY,CAAC,QAAQ,EAAE,CAAC;YAC/B,CAAC,CAAC,CAAC;YACH,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC;SAC5B;QACD,OAAO;YACL,cAAc,EAAE,cAAc,CAAC,KAAK;YACpC,UAAU,EAAE,IAAI;YAChB,MAAM,EAAE,IAAI;SACb,CAAC;IACJ,CAAC;CACF;AAlBD,kCAkBC"}

View File

@ -0,0 +1,5 @@
/**
* Set up the DNS resolver class by registering it as the handler for the
* "dns:" prefix and as the default resolver.
*/
export declare function setup(): void;

269
node_modules/@grpc/grpc-js/build/src/resolver-dns.js generated vendored Normal file
View File

@ -0,0 +1,269 @@
"use strict";
/*
* Copyright 2019 gRPC authors.
*
* 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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const resolver_1 = require("./resolver");
const dns = require("dns");
const semver = require("semver");
const util = require("util");
const service_config_1 = require("./service-config");
const constants_1 = require("./constants");
const metadata_1 = require("./metadata");
const logging = require("./logging");
const constants_2 = require("./constants");
const TRACER_NAME = 'dns_resolver';
function trace(text) {
logging.trace(constants_2.LogVerbosity.DEBUG, TRACER_NAME, text);
}
/* These regular expressions match IP addresses with optional ports in different
* formats. In each case, capture group 1 contains the address, and capture
* group 2 contains the port number, if present */
/**
* Matches 4 groups of up to 3 digits each, separated by periods, optionally
* followed by a colon and a number.
*/
const IPV4_REGEX = /^(\d{1,3}(?:\.\d{1,3}){3})(?::(\d+))?$/;
/**
* Matches any number of groups of up to 4 hex digits (case insensitive)
* separated by 1 or more colons. This variant does not match a port number.
*/
const IPV6_REGEX = /^([0-9a-f]{0,4}(?::{1,2}[0-9a-f]{0,4})+)$/i;
/**
* Matches the same as the IPv6_REGEX, surrounded by square brackets, and
* optionally followed by a colon and a number.
*/
const IPV6_BRACKET_REGEX = /^\[([0-9a-f]{0,4}(?::{1,2}[0-9a-f]{0,4})+)\](?::(\d+))?$/i;
/**
* Matches `[dns:][//authority/]host[:port]`, where `authority` and `host` are
* both arbitrary sequences of dot-separated strings of alphanumeric characters
* and `port` is a sequence of digits. Group 1 contains the hostname and group
* 2 contains the port number if provided.
*/
const DNS_REGEX = /^(?:dns:)?(?:\/\/(?:[a-zA-Z0-9-]+\.?)+\/)?((?:[a-zA-Z0-9-]+\.?)+)(?::(\d+))?$/;
/**
* The default TCP port to connect to if not explicitly specified in the target.
*/
const DEFAULT_PORT = '443';
/**
* The range of Node versions in which the Node issue
* https://github.com/nodejs/node/issues/28216 has been fixed. In other
* versions, IPv6 literal addresses cannot be used to establish HTTP/2
* connections.
*/
const IPV6_SUPPORT_RANGE = '>= 12.6';
/**
* Get a promise that always resolves with either the result of the function
* or the error if it failed.
* @param fn
*/
function resolvePromisify(fn) {
return arg => new Promise((resolve, reject) => {
fn(arg, (error, result) => {
if (error) {
resolve(error);
}
else {
resolve(result);
}
});
});
}
const resolveTxtPromise = resolvePromisify(dns.resolveTxt);
const dnsLookupPromise = util.promisify(dns.lookup);
/**
* Attempt to parse a target string as an IP address
* @param target
* @return An "IP:port" string in an array if parsing was successful, `null` otherwise
*/
function parseIP(target) {
/* These three regular expressions are all mutually exclusive, so we just
* want the first one that matches the target string, if any do. */
const ipv4Match = IPV4_REGEX.exec(target);
const match = ipv4Match || IPV6_REGEX.exec(target) || IPV6_BRACKET_REGEX.exec(target);
if (match === null) {
return null;
}
// ipv6 addresses should be bracketed
const addr = ipv4Match ? match[1] : `[${match[1]}]`;
let port;
if (match[2]) {
port = match[2];
}
else {
port = DEFAULT_PORT;
}
return [`${addr}:${port}`];
}
/**
* Merge any number of arrays into a single alternating array
* @param arrays
*/
function mergeArrays(...arrays) {
const result = [];
for (let i = 0; i <
Math.max.apply(null, arrays.map(array => array.length)); i++) {
for (const array of arrays) {
if (i < array.length) {
result.push(array[i]);
}
}
}
return result;
}
/**
* Resolver implementation that handles DNS names and IP addresses.
*/
class DnsResolver {
constructor(target, listener) {
this.target = target;
this.listener = listener;
/* The promise results here contain, in order, the A record, the AAAA record,
* and either the TXT record or an error if TXT resolution failed */
this.pendingResultPromise = null;
trace('Resolver constructed for target ' + target);
this.ipResult = parseIP(target);
const dnsMatch = DNS_REGEX.exec(target);
if (dnsMatch === null) {
this.dnsHostname = null;
this.port = null;
}
else {
this.dnsHostname = dnsMatch[1];
if (dnsMatch[2]) {
this.port = dnsMatch[2];
}
else {
this.port = DEFAULT_PORT;
}
}
this.percentage = Math.random() * 100;
this.defaultResolutionError = {
code: constants_1.Status.UNAVAILABLE,
details: `Name resolution failed for target ${this.target}`,
metadata: new metadata_1.Metadata(),
};
}
/**
* If the target is an IP address, just provide that address as a result.
* Otherwise, initiate A, AAAA, and TXT
*/
startResolution() {
if (this.ipResult !== null) {
trace('Returning IP address for target ' + this.target);
setImmediate(() => {
this.listener.onSuccessfulResolution(this.ipResult, null, null);
});
return;
}
if (this.dnsHostname !== null) {
const hostname = this.dnsHostname;
/* We lookup both address families here and then split them up later
* because when looking up a single family, dns.lookup outputs an error
* if the name exists but there are no records for that family, and that
* error is indistinguishable from other kinds of errors */
const addressResult = dnsLookupPromise(hostname, { all: true });
/* We handle the TXT query promise differently than the others because
* the name resolution attempt as a whole is a success even if the TXT
* lookup fails */
const txtResult = resolveTxtPromise(hostname);
this.pendingResultPromise = Promise.all([addressResult, txtResult]);
this.pendingResultPromise.then(([addressList, txtRecord]) => {
this.pendingResultPromise = null;
const ip4Addresses = addressList
.filter(addr => addr.family === 4)
.map(addr => `${addr.address}:${this.port}`);
let ip6Addresses;
if (semver.satisfies(process.version, IPV6_SUPPORT_RANGE)) {
ip6Addresses = addressList
.filter(addr => addr.family === 6)
.map(addr => `[${addr.address}]:${this.port}`);
}
else {
ip6Addresses = [];
}
const allAddresses = mergeArrays(ip4Addresses, ip6Addresses);
trace('Resolved addresses for target ' + this.target + ': ' + allAddresses);
if (allAddresses.length === 0) {
this.listener.onError(this.defaultResolutionError);
return;
}
let serviceConfig = null;
let serviceConfigError = null;
if (txtRecord instanceof Error) {
serviceConfigError = {
code: constants_1.Status.UNAVAILABLE,
details: 'TXT query failed',
metadata: new metadata_1.Metadata(),
};
}
else {
try {
serviceConfig = service_config_1.extractAndSelectServiceConfig(txtRecord, this.percentage);
}
catch (err) {
serviceConfigError = {
code: constants_1.Status.UNAVAILABLE,
details: 'Parsing service config failed',
metadata: new metadata_1.Metadata(),
};
}
}
this.listener.onSuccessfulResolution(allAddresses, serviceConfig, serviceConfigError);
}, err => {
trace('Resolution error for target ' +
this.target +
': ' +
err.message);
this.pendingResultPromise = null;
this.listener.onError(this.defaultResolutionError);
});
}
}
updateResolution() {
trace('Resolution update requested for target ' + this.target);
if (this.pendingResultPromise === null) {
this.startResolution();
}
}
/**
* Get the default authority for the given target. For IP targets, that is
* the IP address. For DNS targets, it is the hostname.
* @param target
*/
static getDefaultAuthority(target) {
const ipMatch = IPV4_REGEX.exec(target) ||
IPV6_REGEX.exec(target) ||
IPV6_BRACKET_REGEX.exec(target);
if (ipMatch) {
return ipMatch[1];
}
const dnsMatch = DNS_REGEX.exec(target);
if (dnsMatch) {
return dnsMatch[1];
}
throw new Error(`Failed to parse target ${target}`);
}
}
/**
* Set up the DNS resolver class by registering it as the handler for the
* "dns:" prefix and as the default resolver.
*/
function setup() {
resolver_1.registerResolver('dns:', DnsResolver);
resolver_1.registerDefaultResolver(DnsResolver);
}
exports.setup = setup;
//# sourceMappingURL=resolver-dns.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1 @@
export declare function setup(): void;

48
node_modules/@grpc/grpc-js/build/src/resolver-uds.js generated vendored Normal file
View File

@ -0,0 +1,48 @@
"use strict";
/*
* Copyright 2019 gRPC authors.
*
* 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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const resolver_1 = require("./resolver");
function getUdsName(target) {
/* Due to how this resolver is registered, it should only be constructed
* with strings that start with 'unix:'. Other strings may result in
* nonsensical output. If the string starts with 'unix://' that entire
* prefix needs to be ignored */
if (target.startsWith('unix://')) {
return target.substring(7);
}
else {
return target.substring(5);
}
}
class UdsResolver {
constructor(target, listener) {
this.listener = listener;
this.addresses = [];
this.addresses = [getUdsName(target)];
}
updateResolution() {
process.nextTick(this.listener.onSuccessfulResolution, this.addresses, null, null);
}
static getDefaultAuthority(target) {
return 'localhost';
}
}
function setup() {
resolver_1.registerResolver('unix:', UdsResolver);
}
exports.setup = setup;
//# sourceMappingURL=resolver-uds.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"resolver-uds.js","sourceRoot":"","sources":["../../src/resolver-uds.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;AAEH,yCAKoB;AAEpB,SAAS,UAAU,CAAC,MAAc;IAChC;;;oCAGgC;IAChC,IAAI,MAAM,CAAC,UAAU,CAAC,SAAS,CAAC,EAAE;QAChC,OAAO,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;KAC5B;SAAM;QACL,OAAO,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;KAC5B;AACH,CAAC;AAED,MAAM,WAAW;IAEf,YAAY,MAAc,EAAU,QAA0B;QAA1B,aAAQ,GAAR,QAAQ,CAAkB;QADtD,cAAS,GAAa,EAAE,CAAC;QAE/B,IAAI,CAAC,SAAS,GAAG,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC;IACxC,CAAC;IACD,gBAAgB;QACd,OAAO,CAAC,QAAQ,CACd,IAAI,CAAC,QAAQ,CAAC,sBAAsB,EACpC,IAAI,CAAC,SAAS,EACd,IAAI,EACJ,IAAI,CACL,CAAC;IACJ,CAAC;IAED,MAAM,CAAC,mBAAmB,CAAC,MAAc;QACvC,OAAO,WAAW,CAAC;IACrB,CAAC;CACF;AAED,SAAgB,KAAK;IACnB,2BAAgB,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC;AACzC,CAAC;AAFD,sBAEC"}

74
node_modules/@grpc/grpc-js/build/src/resolver.d.ts generated vendored Normal file
View File

@ -0,0 +1,74 @@
import { ServiceConfig } from './service-config';
import { StatusObject } from './call-stream';
/**
* A listener object passed to the resolver's constructor that provides name
* resolution updates back to the resolver's owner.
*/
export interface ResolverListener {
/**
* Called whenever the resolver has new name resolution results to report
* @param addressList The new list of backend addresses
* @param serviceConfig The new service configuration corresponding to the
* `addressList`. Will be `null` if no service configuration was
* retrieved or if the service configuration was invalid
* @param serviceConfigError If non-`null`, indicates that the retrieved
* service configuration was invalid
*/
onSuccessfulResolution(addressList: string[], serviceConfig: ServiceConfig | null, serviceConfigError: StatusObject | null): void;
/**
* Called whenever a name resolution attempt fails.
* @param error Describes how resolution failed
*/
onError(error: StatusObject): void;
}
/**
* A resolver class that handles one or more of the name syntax schemes defined
* in the [gRPC Name Resolution document](https://github.com/grpc/grpc/blob/master/doc/naming.md)
*/
export interface Resolver {
/**
* Indicates that the caller wants new name resolution data. Calling this
* function may eventually result in calling one of the `ResolverListener`
* functions, but that is not guaranteed. Those functions will never be
* called synchronously with the constructor or updateResolution.
*/
updateResolution(): void;
}
export interface ResolverConstructor {
new (target: string, listener: ResolverListener): Resolver;
/**
* Get the default authority for a target. This loosely corresponds to that
* target's hostname. Throws an error if this resolver class cannot parse the
* `target`.
* @param target
*/
getDefaultAuthority(target: string): string;
}
/**
* Register a resolver class to handle target names prefixed with the `prefix`
* string. This prefix should correspond to a URI scheme name listed in the
* [gRPC Name Resolution document](https://github.com/grpc/grpc/blob/master/doc/naming.md)
* @param prefix
* @param resolverClass
*/
export declare function registerResolver(prefix: string, resolverClass: ResolverConstructor): void;
/**
* Register a default resolver to handle target names that do not start with
* any registered prefix.
* @param resolverClass
*/
export declare function registerDefaultResolver(resolverClass: ResolverConstructor): void;
/**
* Create a name resolver for the specified target, if possible. Throws an
* error if no such name resolver can be created.
* @param target
* @param listener
*/
export declare function createResolver(target: string, listener: ResolverListener): Resolver;
/**
* Get the default authority for the specified target, if possible. Throws an
* error if no registered name resolver can parse that target string.
* @param target
*/
export declare function getDefaultAuthority(target: string): string;
export declare function registerAll(): void;

83
node_modules/@grpc/grpc-js/build/src/resolver.js generated vendored Normal file
View File

@ -0,0 +1,83 @@
"use strict";
/*
* Copyright 2019 gRPC authors.
*
* 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.
*
*/
Object.defineProperty(exports, "__esModule", { value: true });
const resolver_dns = require("./resolver-dns");
const resolver_uds = require("./resolver-uds");
const registeredResolvers = {};
let defaultResolver = null;
/**
* Register a resolver class to handle target names prefixed with the `prefix`
* string. This prefix should correspond to a URI scheme name listed in the
* [gRPC Name Resolution document](https://github.com/grpc/grpc/blob/master/doc/naming.md)
* @param prefix
* @param resolverClass
*/
function registerResolver(prefix, resolverClass) {
registeredResolvers[prefix] = resolverClass;
}
exports.registerResolver = registerResolver;
/**
* Register a default resolver to handle target names that do not start with
* any registered prefix.
* @param resolverClass
*/
function registerDefaultResolver(resolverClass) {
defaultResolver = resolverClass;
}
exports.registerDefaultResolver = registerDefaultResolver;
/**
* Create a name resolver for the specified target, if possible. Throws an
* error if no such name resolver can be created.
* @param target
* @param listener
*/
function createResolver(target, listener) {
for (const prefix of Object.keys(registeredResolvers)) {
if (target.startsWith(prefix)) {
return new registeredResolvers[prefix](target, listener);
}
}
if (defaultResolver !== null) {
return new defaultResolver(target, listener);
}
throw new Error(`No resolver could be created for target ${target}`);
}
exports.createResolver = createResolver;
/**
* Get the default authority for the specified target, if possible. Throws an
* error if no registered name resolver can parse that target string.
* @param target
*/
function getDefaultAuthority(target) {
for (const prefix of Object.keys(registeredResolvers)) {
if (target.startsWith(prefix)) {
return registeredResolvers[prefix].getDefaultAuthority(target);
}
}
if (defaultResolver !== null) {
return defaultResolver.getDefaultAuthority(target);
}
throw new Error(`Invalid target ${target}`);
}
exports.getDefaultAuthority = getDefaultAuthority;
function registerAll() {
resolver_dns.setup();
resolver_uds.setup();
}
exports.registerAll = registerAll;
//# sourceMappingURL=resolver.js.map

1
node_modules/@grpc/grpc-js/build/src/resolver.js.map generated vendored Normal file
View File

@ -0,0 +1 @@
{"version":3,"file":"resolver.js","sourceRoot":"","sources":["../../src/resolver.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;AAIH,+CAA+C;AAC/C,+CAA+C;AAsD/C,MAAM,mBAAmB,GAA8C,EAAE,CAAC;AAC1E,IAAI,eAAe,GAA+B,IAAI,CAAC;AAEvD;;;;;;GAMG;AACH,SAAgB,gBAAgB,CAC9B,MAAc,EACd,aAAkC;IAElC,mBAAmB,CAAC,MAAM,CAAC,GAAG,aAAa,CAAC;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ServiceConfig } from './service-config';
import { LoadBalancingConfig } from './load-balancing-config';
export declare class ResolvingLoadBalancer implements LoadBalancer {
private target;
private channelControlHelper;
private defaultServiceConfig;
/**
* The resolver class constructed for the target address.
*/
private innerResolver;
/**
* Current internal load balancer used for handling calls.
* Invariant: innerLoadBalancer === null => pendingReplacementLoadBalancer === null.
*/
private innerLoadBalancer;
/**
* The load balancer instance that will be used in place of the current
* `innerLoadBalancer` once either that load balancer loses its connection
* or this one establishes a connection. For use when a new name resolution
* result comes in with a different load balancing configuration, and the
* current `innerLoadBalancer` is still connected.
*/
private pendingReplacementLoadBalancer;
/**
* This resolving load balancer's current connectivity state.
*/
private currentState;
/**
* The service config object from the last successful resolution, if
* available. A value of undefined indicates that there has not yet
* been a successful resolution. A value of null indicates that the last
* successful resolution explicitly provided a null service config.
*/
private previousServiceConfig;
/**
* The most recently reported connectivity state of the `innerLoadBalancer`.
*/
private innerBalancerState;
private innerBalancerPicker;
/**
* The most recent reported state of the pendingReplacementLoadBalancer.
* Starts at IDLE for type simplicity. This should get updated as soon as the
* pendingReplacementLoadBalancer gets constructed.
*/
private replacementBalancerState;
/**
* The picker associated with the replacementBalancerState. Starts as an
* UnavailablePicker for type simplicity. This should get updated as soon as
* the pendingReplacementLoadBalancer gets constructed.
*/
private replacementBalancerPicker;
/**
* ChannelControlHelper for the innerLoadBalancer.
*/
private readonly innerChannelControlHelper;
/**
* ChannelControlHelper for the pendingReplacementLoadBalancer.
*/
private readonly replacementChannelControlHelper;
/**
* The backoff timer for handling name resolution failures.
*/
private readonly backoffTimeout;
/**
* Indicates whether we should attempt to resolve again after the backoff
* timer runs out.
*/
private continueResolving;
/**
* Wrapper class that behaves like a `LoadBalancer` and also handles name
* resolution internally.
* @param target The address of the backend to connect to.
* @param channelControlHelper `ChannelControlHelper` instance provided by
* this load balancer's owner.
* @param defaultServiceConfig The default service configuration to be used
* if none is provided by the name resolver. A `null` value indicates
* that the default behavior should be the default unconfigured behavior.
* In practice, that means using the "pick first" load balancer
* implmentation
*/
constructor(target: string, channelControlHelper: ChannelControlHelper, defaultServiceConfig: ServiceConfig | null);
private updateResolution;
private updateState;
/**
* Stop using the current innerLoadBalancer and replace it with the
* pendingReplacementLoadBalancer. Must only be called if both of
* those are currently not null.
*/
private switchOverReplacementBalancer;
private handleResolutionFailure;
exitIdle(): void;
updateAddressList(addressList: string[], lbConfig: LoadBalancingConfig | null): void;
resetBackoff(): void;
destroy(): void;
getTypeName(): string;
replaceChannelControlHelper(channelControlHelper: ChannelControlHelper): void;
}

View File

@ -0,0 +1,359 @@
"use strict";
/*
* Copyright 2019 gRPC authors.
*
* 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.
*
*/
Object.defineProperty(exports, "__esModule", { value: true });
const load_balancer_1 = require("./load-balancer");
const channel_1 = require("./channel");
const resolver_1 = require("./resolver");
const picker_1 = require("./picker");
const backoff_timeout_1 = require("./backoff-timeout");
const constants_1 = require("./constants");
const metadata_1 = require("./metadata");
const logging = require("./logging");
const constants_2 = require("./constants");
const TRACER_NAME = 'resolving_load_balancer';
function trace(text) {
logging.trace(constants_2.LogVerbosity.DEBUG, TRACER_NAME, text);
}
const DEFAULT_LOAD_BALANCER_NAME = 'pick_first';
class ResolvingLoadBalancer {
/**
* Wrapper class that behaves like a `LoadBalancer` and also handles name
* resolution internally.
* @param target The address of the backend to connect to.
* @param channelControlHelper `ChannelControlHelper` instance provided by
* this load balancer's owner.
* @param defaultServiceConfig The default service configuration to be used
* if none is provided by the name resolver. A `null` value indicates
* that the default behavior should be the default unconfigured behavior.
* In practice, that means using the "pick first" load balancer
* implmentation
*/
constructor(target, channelControlHelper, defaultServiceConfig) {
this.target = target;
this.channelControlHelper = channelControlHelper;
this.defaultServiceConfig = defaultServiceConfig;
/**
* Current internal load balancer used for handling calls.
* Invariant: innerLoadBalancer === null => pendingReplacementLoadBalancer === null.
*/
this.innerLoadBalancer = null;
/**
* The load balancer instance that will be used in place of the current
* `innerLoadBalancer` once either that load balancer loses its connection
* or this one establishes a connection. For use when a new name resolution
* result comes in with a different load balancing configuration, and the
* current `innerLoadBalancer` is still connected.
*/
this.pendingReplacementLoadBalancer = null;
/**
* This resolving load balancer's current connectivity state.
*/
this.currentState = channel_1.ConnectivityState.IDLE;
/**
* The service config object from the last successful resolution, if
* available. A value of undefined indicates that there has not yet
* been a successful resolution. A value of null indicates that the last
* successful resolution explicitly provided a null service config.
*/
this.previousServiceConfig = undefined;
/**
* The most recently reported connectivity state of the `innerLoadBalancer`.
*/
this.innerBalancerState = channel_1.ConnectivityState.IDLE;
this.innerBalancerPicker = new picker_1.UnavailablePicker();
/**
* The most recent reported state of the pendingReplacementLoadBalancer.
* Starts at IDLE for type simplicity. This should get updated as soon as the
* pendingReplacementLoadBalancer gets constructed.
*/
this.replacementBalancerState = channel_1.ConnectivityState.IDLE;
/**
* The picker associated with the replacementBalancerState. Starts as an
* UnavailablePicker for type simplicity. This should get updated as soon as
* the pendingReplacementLoadBalancer gets constructed.
*/
this.replacementBalancerPicker = new picker_1.UnavailablePicker();
/**
* Indicates whether we should attempt to resolve again after the backoff
* timer runs out.
*/
this.continueResolving = false;
this.updateState(channel_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this));
this.innerResolver = resolver_1.createResolver(target, {
onSuccessfulResolution: (addressList, serviceConfig, serviceConfigError) => {
let workingServiceConfig = null;
/* This first group of conditionals implements the algorithm described
* in https://github.com/grpc/proposal/blob/master/A21-service-config-error-handling.md
* in the section called "Behavior on receiving a new gRPC Config".
*/
if (serviceConfig === null) {
// Step 4 and 5
if (serviceConfigError === null) {
// Step 5
this.previousServiceConfig = serviceConfig;
workingServiceConfig = this.defaultServiceConfig;
}
else {
// Step 4
if (this.previousServiceConfig === undefined) {
// Step 4.ii
if (this.defaultServiceConfig === null) {
// Step 4.ii.b
this.handleResolutionFailure(serviceConfigError);
}
else {
// Step 4.ii.a
workingServiceConfig = this.defaultServiceConfig;
}
}
else {
// Step 4.i
workingServiceConfig = this.previousServiceConfig;
}
}
}
else {
// Step 3
workingServiceConfig = serviceConfig;
this.previousServiceConfig = serviceConfig;
}
let loadBalancerName = null;
let loadBalancingConfig = null;
if (workingServiceConfig === null ||
workingServiceConfig.loadBalancingConfig.length === 0) {
loadBalancerName = DEFAULT_LOAD_BALANCER_NAME;
}
else {
for (const lbConfig of workingServiceConfig.loadBalancingConfig) {
// Iterating through a oneof looking for whichever one is populated
for (const key in lbConfig) {
if (Object.prototype.hasOwnProperty.call(lbConfig, key)) {
if (load_balancer_1.isLoadBalancerNameRegistered(key)) {
loadBalancerName = key;
loadBalancingConfig = lbConfig;
break;
}
}
}
if (loadBalancerName !== null) {
break;
}
}
if (loadBalancerName === null) {
// There were load balancing configs but none are supported. This counts as a resolution failure
this.handleResolutionFailure({
code: constants_1.Status.UNAVAILABLE,
details: 'All load balancer options in service config are not compatible',
metadata: new metadata_1.Metadata(),
});
return;
}
}
if (this.innerLoadBalancer === null) {
this.innerLoadBalancer = load_balancer_1.createLoadBalancer(loadBalancerName, this.innerChannelControlHelper);
this.innerLoadBalancer.updateAddressList(addressList, loadBalancingConfig);
}
else if (this.innerLoadBalancer.getTypeName() === loadBalancerName) {
this.innerLoadBalancer.updateAddressList(addressList, loadBalancingConfig);
}
else {
if (this.pendingReplacementLoadBalancer === null ||
this.pendingReplacementLoadBalancer.getTypeName() !==
loadBalancerName) {
if (this.pendingReplacementLoadBalancer !== null) {
this.pendingReplacementLoadBalancer.destroy();
}
this.pendingReplacementLoadBalancer = load_balancer_1.createLoadBalancer(loadBalancerName, this.replacementChannelControlHelper);
}
this.pendingReplacementLoadBalancer.updateAddressList(addressList, loadBalancingConfig);
}
},
onError: (error) => {
this.handleResolutionFailure(error);
},
});
this.innerChannelControlHelper = {
createSubchannel: (subchannelAddress, subchannelArgs) => {
return this.channelControlHelper.createSubchannel(subchannelAddress, subchannelArgs);
},
updateState: (connectivityState, picker) => {
this.innerBalancerState = connectivityState;
if (connectivityState === channel_1.ConnectivityState.IDLE) {
picker = new picker_1.QueuePicker(this);
}
this.innerBalancerPicker = picker;
if (connectivityState !== channel_1.ConnectivityState.READY &&
this.pendingReplacementLoadBalancer !== null) {
this.switchOverReplacementBalancer();
}
else {
if (connectivityState === channel_1.ConnectivityState.IDLE) {
if (this.innerLoadBalancer) {
this.innerLoadBalancer.destroy();
this.innerLoadBalancer = null;
}
}
this.updateState(connectivityState, picker);
}
},
requestReresolution: () => {
if (this.pendingReplacementLoadBalancer === null) {
/* If the backoffTimeout is running, we're still backing off from
* making resolve requests, so we shouldn't make another one here.
* In that case, the backoff timer callback will call
* updateResolution */
if (this.backoffTimeout.isRunning()) {
this.continueResolving = true;
}
else {
this.updateResolution();
}
}
},
};
this.replacementChannelControlHelper = {
createSubchannel: (subchannelAddress, subchannelArgs) => {
return this.channelControlHelper.createSubchannel(subchannelAddress, subchannelArgs);
},
updateState: (connectivityState, picker) => {
if (connectivityState === channel_1.ConnectivityState.IDLE) {
picker = new picker_1.QueuePicker(this);
}
this.replacementBalancerState = connectivityState;
this.replacementBalancerPicker = picker;
if (connectivityState === channel_1.ConnectivityState.READY) {
this.switchOverReplacementBalancer();
}
else if (connectivityState === channel_1.ConnectivityState.IDLE) {
if (this.pendingReplacementLoadBalancer) {
this.pendingReplacementLoadBalancer.destroy();
this.pendingReplacementLoadBalancer = null;
}
}
},
requestReresolution: () => {
/* If the backoffTimeout is running, we're still backing off from
* making resolve requests, so we shouldn't make another one here.
* In that case, the backoff timer callback will call
* updateResolution */
if (this.backoffTimeout.isRunning()) {
this.continueResolving = true;
}
else {
this.updateResolution();
}
},
};
this.backoffTimeout = new backoff_timeout_1.BackoffTimeout(() => {
if (this.continueResolving) {
this.updateResolution();
this.continueResolving = false;
}
else {
if (this.innerLoadBalancer === null) {
this.updateState(channel_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this));
}
else {
this.updateState(this.innerBalancerState, this.innerBalancerPicker);
}
}
});
}
updateResolution() {
this.innerResolver.updateResolution();
if (this.innerLoadBalancer === null ||
this.innerBalancerState === channel_1.ConnectivityState.IDLE) {
this.updateState(channel_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this));
}
}
updateState(connectivitystate, picker) {
trace(this.target +
' ' +
channel_1.ConnectivityState[this.currentState] +
' -> ' +
channel_1.ConnectivityState[connectivitystate]);
this.currentState = connectivitystate;
this.channelControlHelper.updateState(connectivitystate, picker);
}
/**
* Stop using the current innerLoadBalancer and replace it with the
* pendingReplacementLoadBalancer. Must only be called if both of
* those are currently not null.
*/
switchOverReplacementBalancer() {
this.innerLoadBalancer.destroy();
this.innerLoadBalancer = this.pendingReplacementLoadBalancer;
this.innerLoadBalancer.replaceChannelControlHelper(this.innerChannelControlHelper);
this.pendingReplacementLoadBalancer = null;
this.innerBalancerState = this.replacementBalancerState;
this.innerBalancerPicker = this.replacementBalancerPicker;
this.updateState(this.replacementBalancerState, this.replacementBalancerPicker);
}
handleResolutionFailure(error) {
if (this.innerLoadBalancer === null ||
this.innerBalancerState === channel_1.ConnectivityState.IDLE) {
this.updateState(channel_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker(error));
}
this.backoffTimeout.runOnce();
}
exitIdle() {
if (this.innerLoadBalancer !== null) {
this.innerLoadBalancer.exitIdle();
}
if (this.currentState === channel_1.ConnectivityState.IDLE) {
if (this.backoffTimeout.isRunning()) {
this.continueResolving = true;
}
else {
this.updateResolution();
}
this.updateState(channel_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this));
}
}
updateAddressList(addressList, lbConfig) {
throw new Error('updateAddressList not supported on ResolvingLoadBalancer');
}
resetBackoff() {
this.backoffTimeout.reset();
if (this.innerLoadBalancer !== null) {
this.innerLoadBalancer.resetBackoff();
}
if (this.pendingReplacementLoadBalancer !== null) {
this.pendingReplacementLoadBalancer.resetBackoff();
}
}
destroy() {
if (this.innerLoadBalancer !== null) {
this.innerLoadBalancer.destroy();
this.innerLoadBalancer = null;
}
if (this.pendingReplacementLoadBalancer !== null) {
this.pendingReplacementLoadBalancer.destroy();
this.pendingReplacementLoadBalancer = null;
}
this.updateState(channel_1.ConnectivityState.SHUTDOWN, new picker_1.UnavailablePicker());
}
getTypeName() {
return 'resolving_load_balancer';
}
replaceChannelControlHelper(channelControlHelper) {
this.channelControlHelper = channelControlHelper;
}
}
exports.ResolvingLoadBalancer = ResolvingLoadBalancer;
//# sourceMappingURL=resolving-load-balancer.js.map

File diff suppressed because one or more lines are too long

127
node_modules/@grpc/grpc-js/build/src/server-call.d.ts generated vendored Normal file
View File

@ -0,0 +1,127 @@
/// <reference types="node" />
import { EventEmitter } from 'events';
import * as http2 from 'http2';
import { Duplex, Readable, Writable } from 'stream';
import { StatusObject } from './call-stream';
import { Deserialize, Serialize } from './make-client';
import { Metadata } from './metadata';
import { ObjectReadable, ObjectWritable } from './object-stream';
export declare type ServerStatusResponse = Partial<StatusObject>;
export declare type ServerErrorResponse = ServerStatusResponse & Error;
export declare type ServerSurfaceCall = {
cancelled: boolean;
getPeer(): string;
sendMetadata(responseMetadata: Metadata): void;
} & EventEmitter;
export declare type ServerUnaryCall<RequestType, ResponseType> = ServerSurfaceCall & {
request: RequestType | null;
};
export declare type ServerReadableStream<RequestType, ResponseType> = ServerSurfaceCall & ObjectReadable<RequestType>;
export declare type ServerWritableStream<RequestType, ResponseType> = ServerSurfaceCall & ObjectWritable<ResponseType> & {
request: RequestType | null;
};
export declare type ServerDuplexStream<RequestType, ResponseType> = ServerSurfaceCall & ObjectReadable<RequestType> & ObjectWritable<ResponseType>;
export declare class ServerUnaryCallImpl<RequestType, ResponseType> extends EventEmitter implements ServerUnaryCall<RequestType, ResponseType> {
private call;
metadata: Metadata;
cancelled: boolean;
request: RequestType | null;
constructor(call: Http2ServerCallStream<RequestType, ResponseType>, metadata: Metadata);
getPeer(): string;
sendMetadata(responseMetadata: Metadata): void;
}
export declare class ServerReadableStreamImpl<RequestType, ResponseType> extends Readable implements ServerReadableStream<RequestType, ResponseType> {
private call;
metadata: Metadata;
deserialize: Deserialize<RequestType>;
cancelled: boolean;
constructor(call: Http2ServerCallStream<RequestType, ResponseType>, metadata: Metadata, deserialize: Deserialize<RequestType>);
_read(size: number): void;
getPeer(): string;
sendMetadata(responseMetadata: Metadata): void;
}
export declare class ServerWritableStreamImpl<RequestType, ResponseType> extends Writable implements ServerWritableStream<RequestType, ResponseType> {
private call;
metadata: Metadata;
serialize: Serialize<ResponseType>;
cancelled: boolean;
request: RequestType | null;
private trailingMetadata;
constructor(call: Http2ServerCallStream<RequestType, ResponseType>, metadata: Metadata, serialize: Serialize<ResponseType>);
getPeer(): string;
sendMetadata(responseMetadata: Metadata): void;
_write(chunk: ResponseType, encoding: string, callback: (...args: any[]) => void): Promise<void>;
_final(callback: Function): void;
end(metadata?: any): void;
}
export declare class ServerDuplexStreamImpl<RequestType, ResponseType> extends Duplex implements ServerDuplexStream<RequestType, ResponseType> {
private call;
metadata: Metadata;
serialize: Serialize<ResponseType>;
deserialize: Deserialize<RequestType>;
cancelled: boolean;
private trailingMetadata;
constructor(call: Http2ServerCallStream<RequestType, ResponseType>, metadata: Metadata, serialize: Serialize<ResponseType>, deserialize: Deserialize<RequestType>);
getPeer(): string;
sendMetadata(responseMetadata: Metadata): void;
}
export declare type sendUnaryData<ResponseType> = (error: ServerErrorResponse | ServerStatusResponse | null, value: ResponseType | null, trailer?: Metadata, flags?: number) => void;
export declare type handleUnaryCall<RequestType, ResponseType> = (call: ServerUnaryCall<RequestType, ResponseType>, callback: sendUnaryData<ResponseType>) => void;
export declare type handleClientStreamingCall<RequestType, ResponseType> = (call: ServerReadableStream<RequestType, ResponseType>, callback: sendUnaryData<ResponseType>) => void;
export declare type handleServerStreamingCall<RequestType, ResponseType> = (call: ServerWritableStream<RequestType, ResponseType>) => void;
export declare type handleBidiStreamingCall<RequestType, ResponseType> = (call: ServerDuplexStream<RequestType, ResponseType>) => void;
export declare type HandleCall<RequestType, ResponseType> = handleUnaryCall<RequestType, ResponseType> | handleClientStreamingCall<RequestType, ResponseType> | handleServerStreamingCall<RequestType, ResponseType> | handleBidiStreamingCall<RequestType, ResponseType>;
export interface UnaryHandler<RequestType, ResponseType> {
func: handleUnaryCall<RequestType, ResponseType>;
serialize: Serialize<ResponseType>;
deserialize: Deserialize<RequestType>;
type: HandlerType;
}
export interface ClientStreamingHandler<RequestType, ResponseType> {
func: handleClientStreamingCall<RequestType, ResponseType>;
serialize: Serialize<ResponseType>;
deserialize: Deserialize<RequestType>;
type: HandlerType;
}
export interface ServerStreamingHandler<RequestType, ResponseType> {
func: handleServerStreamingCall<RequestType, ResponseType>;
serialize: Serialize<ResponseType>;
deserialize: Deserialize<RequestType>;
type: HandlerType;
}
export interface BidiStreamingHandler<RequestType, ResponseType> {
func: handleBidiStreamingCall<RequestType, ResponseType>;
serialize: Serialize<ResponseType>;
deserialize: Deserialize<RequestType>;
type: HandlerType;
}
export declare type Handler<RequestType, ResponseType> = UnaryHandler<RequestType, ResponseType> | ClientStreamingHandler<RequestType, ResponseType> | ServerStreamingHandler<RequestType, ResponseType> | BidiStreamingHandler<RequestType, ResponseType>;
export declare type HandlerType = 'bidi' | 'clientStream' | 'serverStream' | 'unary';
export declare class Http2ServerCallStream<RequestType, ResponseType> extends EventEmitter {
private stream;
private handler;
cancelled: boolean;
deadline: NodeJS.Timer;
private wantTrailers;
private metadataSent;
private canPush;
private isPushPending;
private bufferedMessages;
private messagesToPush;
constructor(stream: http2.ServerHttp2Stream, handler: Handler<RequestType, ResponseType>);
sendMetadata(customMetadata?: Metadata): void;
receiveMetadata(headers: http2.IncomingHttpHeaders): Metadata | undefined;
receiveUnaryMessage(): Promise<RequestType>;
serializeMessage(value: ResponseType): Buffer;
deserializeMessage(bytes: Buffer): Promise<RequestType>;
sendUnaryMessage(err: ServerErrorResponse | ServerStatusResponse | null, value: ResponseType | null, metadata?: Metadata, flags?: number): Promise<void>;
sendStatus(statusObj: StatusObject): void;
sendError(error: ServerErrorResponse | ServerStatusResponse): void;
write(chunk: Buffer): boolean | undefined;
resume(): void;
setupSurfaceCall(call: ServerSurfaceCall): void;
setupReadable(readable: ServerReadableStream<RequestType, ResponseType> | ServerDuplexStream<RequestType, ResponseType>): void;
consumeUnpushedMessages(readable: ServerReadableStream<RequestType, ResponseType> | ServerDuplexStream<RequestType, ResponseType>): boolean;
private pushOrBufferMessage;
private pushMessage;
}

416
node_modules/@grpc/grpc-js/build/src/server-call.js generated vendored Normal file
View File

@ -0,0 +1,416 @@
"use strict";
/*
* Copyright 2019 gRPC authors.
*
* 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.
*
*/
Object.defineProperty(exports, "__esModule", { value: true });
const events_1 = require("events");
const http2 = require("http2");
const stream_1 = require("stream");
const constants_1 = require("./constants");
const metadata_1 = require("./metadata");
const stream_decoder_1 = require("./stream-decoder");
const GRPC_ACCEPT_ENCODING_HEADER = 'grpc-accept-encoding';
const GRPC_ENCODING_HEADER = 'grpc-encoding';
const GRPC_MESSAGE_HEADER = 'grpc-message';
const GRPC_STATUS_HEADER = 'grpc-status';
const GRPC_TIMEOUT_HEADER = 'grpc-timeout';
const DEADLINE_REGEX = /(\d{1,8})\s*([HMSmun])/;
const deadlineUnitsToMs = {
H: 3600000,
M: 60000,
S: 1000,
m: 1,
u: 0.001,
n: 0.000001,
};
const defaultResponseHeaders = {
// TODO(cjihrig): Remove these encoding headers from the default response
// once compression is integrated.
[GRPC_ACCEPT_ENCODING_HEADER]: 'identity',
[GRPC_ENCODING_HEADER]: 'identity',
[http2.constants.HTTP2_HEADER_STATUS]: http2.constants.HTTP_STATUS_OK,
[http2.constants.HTTP2_HEADER_CONTENT_TYPE]: 'application/grpc+proto',
};
const defaultResponseOptions = {
waitForTrailers: true,
};
class ServerUnaryCallImpl extends events_1.EventEmitter {
constructor(call, metadata) {
super();
this.call = call;
this.metadata = metadata;
this.cancelled = false;
this.request = null;
this.call.setupSurfaceCall(this);
}
getPeer() {
throw new Error('not implemented yet');
}
sendMetadata(responseMetadata) {
this.call.sendMetadata(responseMetadata);
}
}
exports.ServerUnaryCallImpl = ServerUnaryCallImpl;
class ServerReadableStreamImpl extends stream_1.Readable {
constructor(call, metadata, deserialize) {
super({ objectMode: true });
this.call = call;
this.metadata = metadata;
this.deserialize = deserialize;
this.cancelled = false;
this.call.setupSurfaceCall(this);
this.call.setupReadable(this);
}
_read(size) {
if (!this.call.consumeUnpushedMessages(this)) {
return;
}
this.call.resume();
}
getPeer() {
throw new Error('not implemented yet');
}
sendMetadata(responseMetadata) {
this.call.sendMetadata(responseMetadata);
}
}
exports.ServerReadableStreamImpl = ServerReadableStreamImpl;
class ServerWritableStreamImpl extends stream_1.Writable {
constructor(call, metadata, serialize) {
super({ objectMode: true });
this.call = call;
this.metadata = metadata;
this.serialize = serialize;
this.cancelled = false;
this.request = null;
this.trailingMetadata = new metadata_1.Metadata();
this.call.setupSurfaceCall(this);
this.on('error', err => {
this.call.sendError(err);
this.end();
});
}
getPeer() {
throw new Error('not implemented yet');
}
sendMetadata(responseMetadata) {
this.call.sendMetadata(responseMetadata);
}
async _write(chunk, encoding,
// tslint:disable-next-line:no-any
callback) {
try {
const response = await this.call.serializeMessage(chunk);
if (!this.call.write(response)) {
this.call.once('drain', callback);
return;
}
}
catch (err) {
err.code = constants_1.Status.INTERNAL;
this.emit('error', err);
}
callback();
}
_final(callback) {
this.call.sendStatus({
code: constants_1.Status.OK,
details: 'OK',
metadata: this.trailingMetadata,
});
callback(null);
}
// tslint:disable-next-line:no-any
end(metadata) {
if (metadata) {
this.trailingMetadata = metadata;
}
super.end();
}
}
exports.ServerWritableStreamImpl = ServerWritableStreamImpl;
class ServerDuplexStreamImpl extends stream_1.Duplex {
constructor(call, metadata, serialize, deserialize) {
super({ objectMode: true });
this.call = call;
this.metadata = metadata;
this.serialize = serialize;
this.deserialize = deserialize;
this.cancelled = false;
this.trailingMetadata = new metadata_1.Metadata();
this.call.setupSurfaceCall(this);
this.call.setupReadable(this);
this.on('error', err => {
this.call.sendError(err);
this.end();
});
}
getPeer() {
throw new Error('not implemented yet');
}
sendMetadata(responseMetadata) {
this.call.sendMetadata(responseMetadata);
}
}
exports.ServerDuplexStreamImpl = ServerDuplexStreamImpl;
ServerDuplexStreamImpl.prototype._read =
ServerReadableStreamImpl.prototype._read;
ServerDuplexStreamImpl.prototype._write =
ServerWritableStreamImpl.prototype._write;
ServerDuplexStreamImpl.prototype._final =
ServerWritableStreamImpl.prototype._final;
ServerDuplexStreamImpl.prototype.end = ServerWritableStreamImpl.prototype.end;
const noopTimer = setTimeout(() => { }, 0);
// Internal class that wraps the HTTP2 request.
class Http2ServerCallStream extends events_1.EventEmitter {
constructor(stream, handler) {
super();
this.stream = stream;
this.handler = handler;
this.cancelled = false;
this.deadline = noopTimer;
this.wantTrailers = false;
this.metadataSent = false;
this.canPush = false;
this.isPushPending = false;
this.bufferedMessages = [];
this.messagesToPush = [];
this.stream.once('error', (err) => {
err.code = constants_1.Status.INTERNAL;
this.sendError(err);
});
this.stream.once('close', () => {
if (this.stream.rstCode === http2.constants.NGHTTP2_CANCEL) {
this.cancelled = true;
this.emit('cancelled', 'cancelled');
}
});
this.stream.on('drain', () => {
this.emit('drain');
});
}
sendMetadata(customMetadata) {
if (this.metadataSent) {
return;
}
this.metadataSent = true;
const custom = customMetadata ? customMetadata.toHttp2Headers() : null;
// TODO(cjihrig): Include compression headers.
const headers = Object.assign(defaultResponseHeaders, custom);
this.stream.respond(headers, defaultResponseOptions);
}
receiveMetadata(headers) {
const metadata = metadata_1.Metadata.fromHttp2Headers(headers);
// TODO(cjihrig): Receive compression metadata.
const timeoutHeader = metadata.get(GRPC_TIMEOUT_HEADER);
if (timeoutHeader.length > 0) {
const match = timeoutHeader[0].toString().match(DEADLINE_REGEX);
if (match === null) {
const err = new Error('Invalid deadline');
err.code = constants_1.Status.OUT_OF_RANGE;
this.sendError(err);
return;
}
const timeout = (+match[1] * deadlineUnitsToMs[match[2]]) | 0;
this.deadline = setTimeout(handleExpiredDeadline, timeout, this);
metadata.remove(GRPC_TIMEOUT_HEADER);
}
return metadata;
}
receiveUnaryMessage() {
return new Promise((resolve, reject) => {
const stream = this.stream;
const chunks = [];
let totalLength = 0;
stream.on('data', (data) => {
chunks.push(data);
totalLength += data.byteLength;
});
stream.once('end', async () => {
try {
const requestBytes = Buffer.concat(chunks, totalLength);
resolve(await this.deserializeMessage(requestBytes));
}
catch (err) {
err.code = constants_1.Status.INTERNAL;
this.sendError(err);
resolve();
}
});
});
}
serializeMessage(value) {
const messageBuffer = this.handler.serialize(value);
// TODO(cjihrig): Call compression aware serializeMessage().
const byteLength = messageBuffer.byteLength;
const output = Buffer.allocUnsafe(byteLength + 5);
output.writeUInt8(0, 0);
output.writeUInt32BE(byteLength, 1);
messageBuffer.copy(output, 5);
return output;
}
async deserializeMessage(bytes) {
// TODO(cjihrig): Call compression aware deserializeMessage().
const receivedMessage = bytes.slice(5);
return this.handler.deserialize(receivedMessage);
}
async sendUnaryMessage(err, value, metadata, flags) {
if (!metadata) {
metadata = new metadata_1.Metadata();
}
if (err) {
err.metadata = metadata;
this.sendError(err);
return;
}
try {
const response = await this.serializeMessage(value);
this.write(response);
this.sendStatus({ code: constants_1.Status.OK, details: 'OK', metadata });
}
catch (err) {
err.code = constants_1.Status.INTERNAL;
this.sendError(err);
}
}
sendStatus(statusObj) {
if (this.cancelled) {
return;
}
clearTimeout(this.deadline);
if (!this.wantTrailers) {
this.wantTrailers = true;
this.stream.once('wantTrailers', () => {
const trailersToSend = Object.assign({
[GRPC_STATUS_HEADER]: statusObj.code,
[GRPC_MESSAGE_HEADER]: encodeURI(statusObj.details),
}, statusObj.metadata.toHttp2Headers());
this.stream.sendTrailers(trailersToSend);
});
this.sendMetadata();
this.stream.end();
}
}
sendError(error) {
const status = {
code: constants_1.Status.UNKNOWN,
details: 'message' in error ? error.message : 'Unknown Error',
metadata: 'metadata' in error && error.metadata !== undefined
? error.metadata
: new metadata_1.Metadata(),
};
if ('code' in error &&
typeof error.code === 'number' &&
Number.isInteger(error.code)) {
status.code = error.code;
if ('details' in error && typeof error.details === 'string') {
status.details = error.details;
}
}
this.sendStatus(status);
}
write(chunk) {
if (this.cancelled) {
return;
}
this.sendMetadata();
return this.stream.write(chunk);
}
resume() {
this.stream.resume();
}
setupSurfaceCall(call) {
this.once('cancelled', reason => {
call.cancelled = true;
call.emit('cancelled', reason);
});
}
setupReadable(readable) {
const decoder = new stream_decoder_1.StreamDecoder();
this.stream.on('data', async (data) => {
const messages = decoder.write(data);
for (const message of messages) {
this.pushOrBufferMessage(readable, message);
}
});
this.stream.once('end', () => {
this.pushOrBufferMessage(readable, null);
});
}
consumeUnpushedMessages(readable) {
this.canPush = true;
while (this.messagesToPush.length > 0) {
const nextMessage = this.messagesToPush.shift();
const canPush = readable.push(nextMessage);
if (nextMessage === null || canPush === false) {
this.canPush = false;
break;
}
}
return this.canPush;
}
pushOrBufferMessage(readable, messageBytes) {
if (this.isPushPending) {
this.bufferedMessages.push(messageBytes);
}
else {
this.pushMessage(readable, messageBytes);
}
}
async pushMessage(readable, messageBytes) {
if (messageBytes === null) {
if (this.canPush) {
readable.push(null);
}
else {
this.messagesToPush.push(null);
}
return;
}
this.isPushPending = true;
try {
const deserialized = await this.deserializeMessage(messageBytes);
if (this.canPush) {
if (!readable.push(deserialized)) {
this.canPush = false;
this.stream.pause();
}
}
else {
this.messagesToPush.push(deserialized);
}
}
catch (err) {
// Ignore any remaining messages when errors occur.
this.bufferedMessages.length = 0;
err.code = constants_1.Status.INTERNAL;
readable.emit('error', err);
}
this.isPushPending = false;
if (this.bufferedMessages.length > 0) {
this.pushMessage(readable, this.bufferedMessages.shift());
}
}
}
exports.Http2ServerCallStream = Http2ServerCallStream;
function handleExpiredDeadline(call) {
const err = new Error('Deadline exceeded');
err.code = constants_1.Status.DEADLINE_EXCEEDED;
call.sendError(err);
call.cancelled = true;
call.emit('cancelled', 'deadline');
}
//# sourceMappingURL=server-call.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,12 @@
/// <reference types="node" />
import { SecureServerOptions } from 'http2';
export interface KeyCertPair {
private_key: Buffer;
cert_chain: Buffer;
}
export declare abstract class ServerCredentials {
abstract _isSecure(): boolean;
abstract _getSettings(): SecureServerOptions | null;
static createInsecure(): ServerCredentials;
static createSsl(rootCerts: Buffer | null, keyCertPairs: KeyCertPair[], checkClientCertificate?: boolean): ServerCredentials;
}

View File

@ -0,0 +1,80 @@
"use strict";
/*
* Copyright 2019 gRPC authors.
*
* 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.
*
*/
Object.defineProperty(exports, "__esModule", { value: true });
const tls_helpers_1 = require("./tls-helpers");
class ServerCredentials {
static createInsecure() {
return new InsecureServerCredentials();
}
static createSsl(rootCerts, keyCertPairs, checkClientCertificate = false) {
if (rootCerts !== null && !Buffer.isBuffer(rootCerts)) {
throw new TypeError('rootCerts must be null or a Buffer');
}
if (!Array.isArray(keyCertPairs)) {
throw new TypeError('keyCertPairs must be an array');
}
if (typeof checkClientCertificate !== 'boolean') {
throw new TypeError('checkClientCertificate must be a boolean');
}
const cert = [];
const key = [];
for (let i = 0; i < keyCertPairs.length; i++) {
const pair = keyCertPairs[i];
if (pair === null || typeof pair !== 'object') {
throw new TypeError(`keyCertPair[${i}] must be an object`);
}
if (!Buffer.isBuffer(pair.private_key)) {
throw new TypeError(`keyCertPair[${i}].private_key must be a Buffer`);
}
if (!Buffer.isBuffer(pair.cert_chain)) {
throw new TypeError(`keyCertPair[${i}].cert_chain must be a Buffer`);
}
cert.push(pair.cert_chain);
key.push(pair.private_key);
}
return new SecureServerCredentials({
ca: rootCerts || tls_helpers_1.getDefaultRootsData() || undefined,
cert,
key,
requestCert: checkClientCertificate,
ciphers: tls_helpers_1.CIPHER_SUITES
});
}
}
exports.ServerCredentials = ServerCredentials;
class InsecureServerCredentials extends ServerCredentials {
_isSecure() {
return false;
}
_getSettings() {
return null;
}
}
class SecureServerCredentials extends ServerCredentials {
constructor(options) {
super();
this.options = options;
}
_isSecure() {
return true;
}
_getSettings() {
return this.options;
}
}
//# sourceMappingURL=server-credentials.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"server-credentials.js","sourceRoot":"","sources":["../../src/server-credentials.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;AAGH,+CAAiE;AAOjE,MAAsB,iBAAiB;IAIrC,MAAM,CAAC,cAAc;QACnB,OAAO,IAAI,yBAAyB,EAAE,CAAC;IACzC,CAAC;IAED,MAAM,CAAC,SAAS,CACd,SAAwB,EACxB,YAA2B,EAC3B,sBAAsB,GAAG,KAAK;QAE9B,IAAI,SAAS,KAAK,IAAI,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE;YACrD,MAAM,IAAI,SAAS,CAAC,oCAAoC,CAAC,CAAC;SAC3D;QAED,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,YAAY,CAAC,EAAE;YAChC,MAAM,IAAI,SAAS,CAAC,+BAA+B,CAAC,CAAC;SACtD;QAED,IAAI,OAAO,sBAAsB,KAAK,SAAS,EAAE;YAC/C,MAAM,IAAI,SAAS,CAAC,0CAA0C,CAAC,CAAC;SACjE;QA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C;IACzB,CAAC;IAED,SAAS;QACP,OAAO,IAAI,CAAC;IACd,CAAC;IAED,YAAY;QACV,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;CACF"}

26
node_modules/@grpc/grpc-js/build/src/server.d.ts generated vendored Normal file
View File

@ -0,0 +1,26 @@
import { Deserialize, Serialize, ServiceDefinition } from './make-client';
import { HandleCall } from './server-call';
import { ServerCredentials } from './server-credentials';
import { ChannelOptions } from './channel-options';
export declare type UntypedHandleCall = HandleCall<any, any>;
export interface UntypedServiceImplementation {
[name: string]: UntypedHandleCall;
}
export declare class Server {
private http2Server;
private handlers;
private sessions;
private started;
private options;
constructor(options?: ChannelOptions);
addProtoService(): void;
addService(service: ServiceDefinition, implementation: UntypedServiceImplementation): void;
bind(port: string, creds: ServerCredentials): void;
bindAsync(port: string, creds: ServerCredentials, callback: (error: Error | null, port: number) => void): void;
forceShutdown(): void;
register<RequestType, ResponseType>(name: string, handler: HandleCall<RequestType, ResponseType>, serialize: Serialize<ResponseType>, deserialize: Deserialize<RequestType>, type: string): boolean;
start(): void;
tryShutdown(callback: (error?: Error) => void): void;
addHttp2Port(): void;
private _setupHandlers;
}

Some files were not shown because too many files have changed in this diff Show More