Firebase Update

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

31
express-server/node_modules/@grpc/grpc-js/README.md generated vendored Normal file
View File

@ -0,0 +1,31 @@
# Pure JavaScript gRPC Client
**Note: This is an beta-level release. Some APIs may not yet be present and there may be bugs. Please report any that you encounter**
## Installation
Node 10 is recommended. The exact set of compatible Node versions can be found in the `engines` field of the `package.json` file.
```sh
npm install @grpc/grpc-js
```
## Features
- Unary and streaming calls
- Cancellation
- Deadlines
- TLS channel credentials
- Call credentials (for auth)
- Simple reconnection
- Channel API
This library does not directly handle `.proto` files. To use `.proto` files with this library we recommend using the `@grpc/proto-loader` package.
## Some Notes on API Guarantees
The public API of this library follows semantic versioning, with some caveats:
- Some methods are prefixed with an underscore. These methods are internal and should not be considered part of the public API.
- The class `Call` is only exposed due to limitations of TypeScript. It should not be considered part of the public API.
- In general, any API that is exposed by this library but is not exposed by the `grpc` library is likely an error and should not be considered part of the public API.

View File

@ -0,0 +1,16 @@
import { Call } from './call-stream';
import { Http2Channel } 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: Http2Channel, stream: Call);
sendMetadata(metadata: Promise<Metadata>): Promise<Metadata>;
}
export declare class CallCredentialsFilterFactory implements FilterFactory<CallCredentialsFilter> {
private readonly channel;
constructor(channel: Http2Channel);
createFilter(callStream: Call): CallCredentialsFilter;
}

View File

@ -0,0 +1,53 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const 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}`;
}
sendMetadata(metadata) {
return __awaiter(this, void 0, void 0, function* () {
const channelCredentials = this.channel.credentials._getCallCredentials();
const streamCredentials = this.stream.getCredentials();
const credentials = channelCredentials.compose(streamCredentials);
const credsMetadata = credentials.generateMetadata({ service_url: this.serviceUrl });
const resultMetadata = yield metadata;
resultMetadata.merge(yield credsMetadata);
return resultMetadata;
});
}
}
exports.CallCredentialsFilter = CallCredentialsFilter;
class CallCredentialsFilterFactory {
constructor(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,32 @@
import { Metadata } from './metadata';
export declare type 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;
/**
* 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,81 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const lodash_1 = require("lodash");
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;
}
generateMetadata(options) {
return __awaiter(this, void 0, void 0, function* () {
const base = new metadata_1.Metadata();
const generated = yield Promise.all(lodash_1.map(this.creds, (cred) => cred.generateMetadata(options)));
for (const gen of generated) {
base.merge(gen);
}
return base;
});
}
compose(other) {
return new ComposedCallCredentials(this.creds.concat([other]));
}
}
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]);
}
}
class EmptyCallCredentials extends CallCredentials {
generateMetadata(options) {
return Promise.resolve(new metadata_1.Metadata());
}
compose(other) {
return other;
}
}
//# sourceMappingURL=call-credentials.js.map

View File

@ -0,0 +1,100 @@
/// <reference types="node" />
import * as http2 from 'http2';
import { Duplex } from 'stream';
import { CallCredentials } from './call-credentials';
import { Http2Channel } from './channel';
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';
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;
credentials: CallCredentials;
filterStack: Filter;
private http2Stream;
private pendingRead;
private pendingWrite;
private pendingWriteCallback;
private pendingFinalCallback;
private readState;
private readCompressFlag;
private readPartialSize;
private readSizeRemaining;
private readMessageSize;
private readPartialMessage;
private readMessageRemaining;
private isReadFilterPending;
private canPush;
private unpushedReadMessages;
private unfilteredReadMessages;
private mappedStatusCode;
private handlingHeaders;
private handlingTrailers;
private finalStatus;
constructor(methodName: string, channel: Http2Channel, options: CallStreamOptions, filterStackFactory: FilterStackFactory);
/**
* 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(status);
private handleFilterError(error);
private handleFilteredRead(message);
private filterReceivedMessage(framedMessage);
private tryPush(messageBytes);
private handleTrailers(headers);
attachHttp2Stream(stream: http2.ClientHttp2Stream): 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;
}

View File

@ -0,0 +1,402 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const http2 = require("http2");
const stream_1 = require("stream");
const call_credentials_1 = require("./call-credentials");
const constants_1 = require("./constants");
const metadata_1 = require("./metadata");
const { HTTP2_HEADER_STATUS, HTTP2_HEADER_CONTENT_TYPE, NGHTTP2_CANCEL } = http2.constants;
var ReadState;
(function (ReadState) {
ReadState[ReadState["NO_DATA"] = 0] = "NO_DATA";
ReadState[ReadState["READING_SIZE"] = 1] = "READING_SIZE";
ReadState[ReadState["READING_MESSAGE"] = 2] = "READING_MESSAGE";
})(ReadState || (ReadState = {}));
class Http2CallStream extends stream_1.Duplex {
constructor(methodName, channel, options, filterStackFactory) {
super({ objectMode: true });
this.methodName = methodName;
this.channel = channel;
this.options = options;
this.credentials = call_credentials_1.CallCredentials.createEmpty();
this.http2Stream = null;
this.pendingRead = false;
this.pendingWrite = null;
this.pendingWriteCallback = null;
this.pendingFinalCallback = null;
this.readState = ReadState.NO_DATA;
this.readCompressFlag = Buffer.alloc(1);
this.readPartialSize = Buffer.alloc(4);
this.readSizeRemaining = 4;
this.readMessageSize = 0;
this.readPartialMessage = [];
this.readMessageRemaining = 0;
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.filterStack = filterStackFactory.createFilter(this);
}
/**
* 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.finalStatus = status;
this.emit('status', status);
}
}
handleFilterError(error) {
this.cancelWithStatus(constants_1.Status.INTERNAL, error.message);
}
handleFilteredRead(message) {
this.isReadFilterPending = false;
if (this.canPush) {
if (!this.push(message)) {
this.canPush = false;
this.http2Stream.pause();
}
}
else {
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 (framedMessage === null) {
if (this.canPush) {
this.push(null);
}
else {
this.unpushedReadMessages.push(null);
}
return;
}
this.isReadFilterPending = true;
this.filterStack.receiveMessage(Promise.resolve(framedMessage))
.then(this.handleFilteredRead.bind(this), this.handleFilterError.bind(this));
}
tryPush(messageBytes) {
if (this.isReadFilterPending) {
this.unfilteredReadMessages.push(messageBytes);
}
else {
this.filterReceivedMessage(messageBytes);
}
}
handleTrailers(headers) {
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 = (() => __awaiter(this, void 0, void 0, function* () {
let finalStatus;
try {
// Attempt to assign final status.
finalStatus =
yield this.filterStack.receiveTrailers(Promise.resolve(status));
}
catch (error) {
yield 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.
yield this.handlingHeaders;
// This is a no-op if the call was already ended when handling headers.
this.endCall(finalStatus);
}))();
}
attachHttp2Stream(stream) {
if (this.finalStatus !== null) {
stream.close(NGHTTP2_CANCEL);
}
else {
this.http2Stream = stream;
stream.on('response', (headers, flags) => {
switch (headers[HTTP2_HEADER_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) => {
let readHead = 0;
let toRead;
while (readHead < data.length) {
switch (this.readState) {
case ReadState.NO_DATA:
this.readCompressFlag = data.slice(readHead, readHead + 1);
readHead += 1;
this.readState = ReadState.READING_SIZE;
this.readPartialSize.fill(0);
this.readSizeRemaining = 4;
this.readMessageSize = 0;
this.readMessageRemaining = 0;
this.readPartialMessage = [];
break;
case ReadState.READING_SIZE:
toRead = Math.min(data.length - readHead, this.readSizeRemaining);
data.copy(this.readPartialSize, 4 - this.readSizeRemaining, readHead, readHead + toRead);
this.readSizeRemaining -= toRead;
readHead += toRead;
// readSizeRemaining >=0 here
if (this.readSizeRemaining === 0) {
this.readMessageSize = this.readPartialSize.readUInt32BE(0);
this.readMessageRemaining = this.readMessageSize;
if (this.readMessageRemaining > 0) {
this.readState = ReadState.READING_MESSAGE;
}
else {
this.tryPush(Buffer.concat([this.readCompressFlag, this.readPartialSize]));
this.readState = ReadState.NO_DATA;
}
}
break;
case ReadState.READING_MESSAGE:
toRead =
Math.min(data.length - readHead, this.readMessageRemaining);
this.readPartialMessage.push(data.slice(readHead, readHead + toRead));
this.readMessageRemaining -= toRead;
readHead += toRead;
// readMessageRemaining >=0 here
if (this.readMessageRemaining === 0) {
// At this point, we have read a full message
const framedMessageBuffers = [
this.readCompressFlag, this.readPartialSize
].concat(this.readPartialMessage);
const framedMessage = Buffer.concat(framedMessageBuffers, this.readMessageSize + 5);
this.tryPush(framedMessage);
this.readState = ReadState.NO_DATA;
}
break;
default:
throw new Error('This should never happen');
}
}
});
stream.on('end', () => {
this.tryPush(null);
});
stream.on('close', (errorCode) => __awaiter(this, void 0, void 0, function* () {
let code;
let details = '';
switch (errorCode) {
case http2.constants.NGHTTP2_REFUSED_STREAM:
code = constants_1.Status.UNAVAILABLE;
break;
case http2.constants.NGHTTP2_CANCEL:
code = constants_1.Status.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.
yield 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) => {
this.endCall({
code: constants_1.Status.INTERNAL,
details: 'Internal HTTP2 error',
metadata: new metadata_1.Metadata()
});
});
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) {
stream.end(this.pendingFinalCallback);
}
}
}
sendMetadata(metadata) {
this.channel._startHttp2Stream(this.options.host, this.methodName, 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();
(() => __awaiter(this, void 0, void 0, function* () {
// If trailers are currently being processed, the call should be ended
// by handleTrailers instead.
yield 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 = credentials;
}
getStatus() {
return this.finalStatus;
}
getPeer() {
throw new Error('Not yet implemented');
}
getMethod() {
return this.methodName;
}
getHost() {
return this.options.host;
}
_read(size) {
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.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) {
if (this.http2Stream === null) {
this.pendingFinalCallback = cb;
}
else {
this.http2Stream.end(cb);
}
}
}
exports.Http2CallStream = Http2CallStream;
//# sourceMappingURL=call-stream.js.map

View File

@ -0,0 +1,72 @@
/// <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>;
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;
}

View File

@ -0,0 +1,154 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const events_1 = require("events");
const stream_1 = require("stream");
const constants_1 = require("./constants");
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) {
const error = Object.assign(new Error(status.details), status);
stream.emit('error', error);
}
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

View File

@ -0,0 +1,73 @@
/// <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;
/**
* 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,96 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tls_1 = require("tls");
const call_credentials_1 = require("./call-credentials");
// 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.`);
}
}
/**
* 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');
}
const secureContext = tls_1.createSecureContext({
ca: rootCerts || undefined,
key: privateKey || undefined,
cert: certChain || undefined
});
const connectionOptions = { secureContext };
if (verifyOptions && verifyOptions.checkServerIdentity) {
connectionOptions.checkServerIdentity =
(host, cert) => {
return verifyOptions.checkServerIdentity(host, { raw: cert.raw });
};
}
return new SecureChannelCredentialsImpl(connectionOptions);
}
/**
* 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;
}
}
class SecureChannelCredentialsImpl extends ChannelCredentials {
constructor(connectionOptions, callCredentials) {
super(callCredentials);
this.connectionOptions = connectionOptions;
}
compose(callCredentials) {
const combinedCallCredentials = this.callCredentials.compose(callCredentials);
return new SecureChannelCredentialsImpl(this.connectionOptions, combinedCallCredentials);
}
_getConnectionOptions() {
return this.connectionOptions;
}
_isSecure() {
return true;
}
}
//# sourceMappingURL=channel-credentials.js.map

View File

@ -0,0 +1,24 @@
/**
* 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;
[key: string]: string | number;
}
/**
* 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;
};

View File

@ -0,0 +1,15 @@
"use strict";
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
};
//# sourceMappingURL=channel-options.js.map

View File

@ -0,0 +1,92 @@
/// <reference types="node" />
import { EventEmitter } from 'events';
import { Call, Deadline, 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 Http2Channel extends EventEmitter implements Channel {
readonly credentials: ChannelCredentials;
private readonly options;
private readonly userAgent;
private readonly target;
private readonly defaultAuthority;
private connectivityState;
private connecting;
private subChannel;
private filterStackFactory;
private subChannelConnectCallback;
private subChannelCloseCallback;
private backoffTimerId;
private currentBackoff;
private currentBackoffDeadline;
private handleStateChange(oldState, newState);
private transitionToState(oldStates, newState);
private startConnecting();
constructor(address: string, credentials: ChannelCredentials, options: Partial<ChannelOptions>);
_startHttp2Stream(authority: string, methodName: string, stream: Http2CallStream, metadata: Metadata): void;
createCall(method: string, deadline: Deadline | null | undefined, host: string | null | undefined, parentCall: Call | null | undefined, propagateFlags: number | null | undefined): Call;
/**
* Attempts to connect, returning a Promise that resolves when the connection
* is successful, or rejects if the channel is shut down.
*/
private connect();
getConnectivityState(tryToConnect: boolean): ConnectivityState;
watchConnectivityState(currentState: ConnectivityState, deadline: Date | number, callback: (error?: Error) => void): void;
getTarget(): string;
close(): void;
}

View File

@ -0,0 +1,297 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const events_1 = require("events");
const http2 = require("http2");
const tls_1 = require("tls");
const url = require("url");
const call_credentials_filter_1 = require("./call-credentials-filter");
const call_stream_1 = require("./call-stream");
const channel_options_1 = require("./channel-options");
const compression_filter_1 = require("./compression-filter");
const constants_1 = require("./constants");
const deadline_filter_1 = require("./deadline-filter");
const filter_stack_1 = require("./filter-stack");
const metadata_status_filter_1 = require("./metadata-status-filter");
const subchannel_1 = require("./subchannel");
const { version: clientVersion } = require('../../package');
const MIN_CONNECT_TIMEOUT_MS = 20000;
const INITIAL_BACKOFF_MS = 1000;
const BACKOFF_MULTIPLIER = 1.6;
const MAX_BACKOFF_MS = 120000;
const BACKOFF_JITTER = 0.2;
const { HTTP2_HEADER_AUTHORITY, HTTP2_HEADER_CONTENT_TYPE, HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, HTTP2_HEADER_TE, HTTP2_HEADER_USER_AGENT } = http2.constants;
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 = {}));
function uniformRandom(min, max) {
return Math.random() * (max - min) + min;
}
class Http2Channel extends events_1.EventEmitter {
constructor(address, credentials, options) {
super();
this.credentials = credentials;
this.options = options;
this.connectivityState = ConnectivityState.IDLE;
// Helper Promise object only used in the implementation of connect().
this.connecting = null;
/* For now, we have up to one subchannel, which will exist as long as we are
* connecting or trying to connect */
this.subChannel = null;
this.subChannelConnectCallback = () => { };
this.subChannelCloseCallback = () => { };
this.currentBackoff = INITIAL_BACKOFF_MS;
for (const option in options) {
if (options.hasOwnProperty(option)) {
if (!channel_options_1.recognizedOptions.hasOwnProperty(option)) {
console.warn(`Unrecognized channel argument '${option}' will be ignored.`);
}
}
}
if (credentials._isSecure()) {
this.target = new url.URL(`https://${address}`);
}
else {
this.target = new url.URL(`http://${address}`);
}
// 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 = this.target.host;
}
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)
]);
this.currentBackoffDeadline = new Date();
/* The only purpose of these lines is to ensure that this.backoffTimerId has
* a value of type NodeJS.Timer. */
this.backoffTimerId = setTimeout(() => { }, 0);
// Build user-agent string.
this.userAgent = [
options['grpc.primary_user_agent'], `grpc-node-js/${clientVersion}`,
options['grpc.secondary_user_agent']
].filter(e => e).join(' '); // remove falsey values first
}
handleStateChange(oldState, newState) {
const now = new Date();
switch (newState) {
case ConnectivityState.CONNECTING:
if (oldState === ConnectivityState.IDLE) {
this.currentBackoff = INITIAL_BACKOFF_MS;
this.currentBackoffDeadline =
new Date(now.getTime() + INITIAL_BACKOFF_MS);
}
else if (oldState === ConnectivityState.TRANSIENT_FAILURE) {
this.currentBackoff = Math.min(this.currentBackoff * BACKOFF_MULTIPLIER, MAX_BACKOFF_MS);
const jitterMagnitude = BACKOFF_JITTER * this.currentBackoff;
this.currentBackoffDeadline = new Date(now.getTime() + this.currentBackoff +
uniformRandom(-jitterMagnitude, jitterMagnitude));
}
this.startConnecting();
break;
case ConnectivityState.READY:
this.emit('connect');
break;
case ConnectivityState.TRANSIENT_FAILURE:
this.subChannel = null;
this.backoffTimerId = setTimeout(() => {
this.transitionToState([ConnectivityState.TRANSIENT_FAILURE], ConnectivityState.CONNECTING);
}, this.currentBackoffDeadline.getTime() - now.getTime());
break;
case ConnectivityState.IDLE:
case ConnectivityState.SHUTDOWN:
if (this.subChannel) {
this.subChannel.close();
this.subChannel.removeListener('connect', this.subChannelConnectCallback);
this.subChannel.removeListener('close', this.subChannelCloseCallback);
this.subChannel = null;
this.emit('shutdown');
clearTimeout(this.backoffTimerId);
}
break;
default:
throw new Error('This should never happen');
}
}
// Transition from any of a set of oldStates to a specific newState
transitionToState(oldStates, newState) {
if (oldStates.indexOf(this.connectivityState) > -1) {
const oldState = this.connectivityState;
this.connectivityState = newState;
this.handleStateChange(oldState, newState);
this.emit('connectivityStateChanged', newState);
}
}
startConnecting() {
const connectionOptions = this.credentials._getConnectionOptions() || {};
if (connectionOptions.secureContext !== null) {
// If provided, the value of grpc.ssl_target_name_override should be used
// to override the target hostname when checking server identity.
// This option is used for testing only.
if (this.options['grpc.ssl_target_name_override']) {
const sslTargetNameOverride = this.options['grpc.ssl_target_name_override'];
connectionOptions.checkServerIdentity =
(host, cert) => {
return tls_1.checkServerIdentity(sslTargetNameOverride, cert);
};
connectionOptions.servername = sslTargetNameOverride;
}
}
const subChannel = new subchannel_1.Http2SubChannel(this.target, connectionOptions, this.userAgent, this.options);
this.subChannel = subChannel;
const now = new Date();
const connectionTimeout = Math.max(this.currentBackoffDeadline.getTime() - now.getTime(), MIN_CONNECT_TIMEOUT_MS);
const connectionTimerId = setTimeout(() => {
// This should trigger the 'close' event, which will send us back to
// TRANSIENT_FAILURE
subChannel.close();
}, connectionTimeout);
this.subChannelConnectCallback = () => {
// Connection succeeded
clearTimeout(connectionTimerId);
this.transitionToState([ConnectivityState.CONNECTING], ConnectivityState.READY);
};
subChannel.once('connect', this.subChannelConnectCallback);
this.subChannelCloseCallback = () => {
// Connection failed
clearTimeout(connectionTimerId);
/* TODO(murgatroid99): verify that this works for
* CONNECTING->TRANSITIVE_FAILURE see nodejs/node#16645 */
this.transitionToState([ConnectivityState.CONNECTING, ConnectivityState.READY], ConnectivityState.TRANSIENT_FAILURE);
};
subChannel.once('close', this.subChannelCloseCallback);
}
_startHttp2Stream(authority, methodName, stream, metadata) {
const finalMetadata = stream.filterStack.sendMetadata(Promise.resolve(metadata.clone()));
Promise.all([finalMetadata, this.connect()])
.then(([metadataValue]) => {
const headers = metadataValue.toHttp2Headers();
headers[HTTP2_HEADER_AUTHORITY] = authority;
headers[HTTP2_HEADER_USER_AGENT] = this.userAgent;
headers[HTTP2_HEADER_CONTENT_TYPE] = 'application/grpc';
headers[HTTP2_HEADER_METHOD] = 'POST';
headers[HTTP2_HEADER_PATH] = methodName;
headers[HTTP2_HEADER_TE] = 'trailers';
if (this.connectivityState === ConnectivityState.READY) {
const subChannel = this.subChannel;
subChannel.startCallStream(metadataValue, stream);
}
else {
/* In this case, we lost the connection while finalizing
* metadata. That should be very unusual */
setImmediate(() => {
this._startHttp2Stream(authority, methodName, stream, metadata);
});
}
})
.catch((error) => {
// We assume the error code isn't 0 (Status.OK)
stream.cancelWithStatus(error.code || constants_1.Status.UNKNOWN, `Getting metadata from plugin failed with error: ${error.message}`);
});
}
createCall(method, deadline, host, parentCall, propagateFlags) {
if (this.connectivityState === ConnectivityState.SHUTDOWN) {
throw new Error('Channel has been shut down');
}
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);
return stream;
}
/**
* Attempts to connect, returning a Promise that resolves when the connection
* is successful, or rejects if the channel is shut down.
*/
connect() {
if (this.connectivityState === ConnectivityState.READY) {
return Promise.resolve();
}
else if (this.connectivityState === ConnectivityState.SHUTDOWN) {
return Promise.reject(new Error('Channel has been shut down'));
}
else {
// In effect, this.connecting is only assigned upon the first attempt to
// transition from IDLE to CONNECTING, so this condition could have also
// been (connectivityState === IDLE).
if (!this.connecting) {
this.connecting = new Promise((resolve, reject) => {
this.transitionToState([ConnectivityState.IDLE], ConnectivityState.CONNECTING);
const onConnect = () => {
this.connecting = null;
this.removeListener('shutdown', onShutdown);
resolve();
};
const onShutdown = () => {
this.connecting = null;
this.removeListener('connect', onConnect);
reject(new Error('Channel has been shut down'));
};
this.once('connect', onConnect);
this.once('shutdown', onShutdown);
});
}
return this.connecting;
}
}
getConnectivityState(tryToConnect) {
if (tryToConnect) {
this.transitionToState([ConnectivityState.IDLE], ConnectivityState.CONNECTING);
}
return this.connectivityState;
}
watchConnectivityState(currentState, deadline, callback) {
if (this.connectivityState !== currentState) {
/* If the connectivity state is different from the provided currentState,
* we assume that a state change has successfully occurred */
setImmediate(callback);
}
else {
let deadlineMs = 0;
if (deadline instanceof Date) {
deadlineMs = deadline.getTime();
}
else {
deadlineMs = deadline;
}
let timeout = deadlineMs - Date.now();
if (timeout < 0) {
timeout = 0;
}
const timeoutId = setTimeout(() => {
this.removeListener('connectivityStateChanged', eventCb);
callback(new Error('Channel state did not change before deadline'));
}, timeout);
const eventCb = () => {
clearTimeout(timeoutId);
callback();
};
this.once('connectivityStateChanged', eventCb);
}
}
getTarget() {
return this.target.toString();
}
close() {
if (this.connectivityState === ConnectivityState.SHUTDOWN) {
throw new Error('Channel has been shut down');
}
this.transitionToState([
ConnectivityState.CONNECTING, ConnectivityState.READY,
ConnectivityState.TRANSIENT_FAILURE, ConnectivityState.IDLE
], ConnectivityState.SHUTDOWN);
}
}
exports.Http2Channel = Http2Channel;
//# sourceMappingURL=channel.js.map

View File

@ -0,0 +1,49 @@
/// <reference types="node" />
import { ClientDuplexStream, ClientReadableStream, ClientUnaryCall, ClientWritableStream, ServiceError } from './call';
import { CallCredentials } from './call-credentials';
import { Call, Deadline } from './call-stream';
import { Channel } from './channel';
import { ChannelCredentials } from './channel-credentials';
import { ChannelOptions } from './channel-options';
import { Metadata } from './metadata';
export declare const kChannel: unique symbol;
export interface UnaryCallback<ResponseType> {
(err: ServiceError | null, value?: ResponseType): void;
}
export interface CallOptions {
deadline?: Deadline;
host?: string;
parent?: Call;
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 [kChannel];
constructor(address: string, credentials: ChannelCredentials, options?: ClientOptions);
close(): void;
getChannel(): Channel;
waitForReady(deadline: Deadline, callback: (error?: Error) => void): void;
private handleUnaryResponse<ResponseType>(call, deserialize, callback);
private checkOptionalUnaryResponseArguments<ResponseType>(arg1, arg2?, arg3?);
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(arg1?, arg2?);
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>;
}

View File

@ -0,0 +1,186 @@
"use strict";
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");
// This symbol must be exported (for now).
// See: https://github.com/Microsoft/TypeScript/issues/20080
exports.kChannel = 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[exports.kChannel] = options.channelOverride;
}
else if (options.channelFactoryOverride) {
this[exports.kChannel] =
options.channelFactoryOverride(address, credentials, options);
}
else {
this[exports.kChannel] = new channel_1.Http2Channel(address, credentials, options);
}
}
close() {
this[exports.kChannel].close();
}
getChannel() {
return this[exports.kChannel];
}
waitForReady(deadline, callback) {
const checkState = (err) => {
if (err) {
callback(new Error('Failed to connect before the deadline'));
return;
}
let newState;
try {
newState = this[exports.kChannel].getConnectivityState(true);
}
catch (e) {
callback(new Error('The channel has been closed'));
return;
}
if (newState === channel_1.ConnectivityState.READY) {
callback();
}
else {
try {
this[exports.kChannel].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('end', () => {
if (responseMessage == null) {
call.cancelWithStatus(constants_1.Status.INTERNAL, 'Not enough responses received');
}
});
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 {
const error = Object.assign(new Error(status.details), status);
callback(error);
}
});
}
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[exports.kChannel].createCall(method, options.deadline, options.host, options.parent, 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[exports.kChannel].createCall(method, options.deadline, options.host, options.parent, 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[exports.kChannel].createCall(method, options.deadline, options.host, options.parent, 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[exports.kChannel].createCall(method, options.deadline, options.host, options.parent, 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

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,209 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const 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
*/
writeMessage(message, compress) {
return __awaiter(this, void 0, void 0, function* () {
let messageBuffer = message;
if (compress) {
messageBuffer = yield 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
*/
readMessage(data) {
return __awaiter(this, void 0, void 0, function* () {
const compressed = data.readUInt8(0) === 1;
let messageBuffer = data.slice(5);
if (compressed) {
messageBuffer = yield this.decompressMessage(messageBuffer);
}
return messageBuffer;
});
}
}
class IdentityHandler extends CompressionHandler {
compressMessage(message) {
return __awaiter(this, void 0, void 0, function* () {
return message;
});
}
writeMessage(message, compress) {
return __awaiter(this, void 0, void 0, function* () {
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 wth 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();
}
sendMetadata(metadata) {
return __awaiter(this, void 0, void 0, function* () {
const headers = yield metadata;
headers.set('grpc-encoding', 'identity');
headers.set('grpc-accept-encoding', 'identity,deflate,gzip');
return headers;
});
}
receiveMetadata(metadata) {
return __awaiter(this, void 0, void 0, function* () {
const headers = yield 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;
});
}
sendMessage(message) {
return __awaiter(this, void 0, void 0, function* () {
/* 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 = yield message;
const compress = resolvedMessage.flags === undefined ?
false :
(resolvedMessage.flags & 2 /* NoCompress */) === 0;
return {
message: yield this.sendCompression.writeMessage(resolvedMessage.message, compress),
flags: resolvedMessage.flags
};
});
}
receiveMessage(message) {
return __awaiter(this, void 0, void 0, function* () {
/* 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(yield 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,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,
}

View File

@ -0,0 +1,29 @@
"use strict";
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,17 @@
import { Call } from './call-stream';
import { Http2Channel } 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: Http2Channel, callStream: Call);
sendMetadata(metadata: Promise<Metadata>): Promise<Metadata>;
}
export declare class DeadlineFilterFactory implements FilterFactory<DeadlineFilter> {
private readonly channel;
constructor(channel: Http2Channel);
createFilter(callStream: Call): DeadlineFilter;
}

View File

@ -0,0 +1,79 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const channel_1 = require("./channel");
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));
}
}
sendMetadata(metadata) {
if (this.deadline === Infinity) {
return metadata;
}
return new Promise((resolve, reject) => {
if (this.channel.getConnectivityState(false) ===
channel_1.ConnectivityState.READY) {
resolve(metadata);
}
else {
const handleStateChange = (newState) => {
if (newState === channel_1.ConnectivityState.READY) {
resolve(metadata);
this.channel.removeListener('connectivityStateChanged', handleStateChange);
}
};
this.channel.on('connectivityStateChanged', handleStateChange);
}
})
.then((finalMetadata) => {
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,27 @@
export interface EmitterAugmentation0<Name extends string | symbol> {
addListener(event: Name, listener: () => void): this;
emit(event: Name): boolean;
on(event: Name, listener: () => void): this;
once(event: Name, listener: () => void): this;
prependListener(event: Name, listener: () => void): this;
prependOnceListener(event: Name, listener: () => void): this;
removeListener(event: Name, listener: () => void): this;
}
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;
}
export interface EmitterAugmentation2<Name extends string | symbol, Arg1, Arg2> {
addListener(event: Name, listener: (arg1: Arg1, arg2: Arg2) => void): this;
emit(event: Name, arg1: Arg1, arg2: Arg2): boolean;
on(event: Name, listener: (arg1: Arg1, arg2: Arg2) => void): this;
once(event: Name, listener: (arg1: Arg1, arg2: Arg2) => void): this;
prependListener(event: Name, listener: (arg1: Arg1, arg2: Arg2) => void): this;
prependOnceListener(event: Name, listener: (arg1: Arg1, arg2: Arg2) => void): this;
removeListener(event: Name, listener: (arg1: Arg1, arg2: Arg2) => void): this;
}

View File

@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=events.js.map

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>): any;
receiveMetadata(metadata: Promise<Metadata>): any;
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;
}

View File

@ -0,0 +1,34 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const lodash_1 = require("lodash");
class FilterStack {
constructor(filters) {
this.filters = filters;
}
sendMetadata(metadata) {
return lodash_1.flow(lodash_1.map(this.filters, (filter) => filter.sendMetadata.bind(filter)))(metadata);
}
receiveMetadata(metadata) {
return lodash_1.flowRight(lodash_1.map(this.filters, (filter) => filter.receiveMetadata.bind(filter)))(metadata);
}
sendMessage(message) {
return lodash_1.flow(lodash_1.map(this.filters, (filter) => filter.sendMessage.bind(filter)))(message);
}
receiveMessage(message) {
return lodash_1.flowRight(lodash_1.map(this.filters, (filter) => filter.receiveMessage.bind(filter)))(message);
}
receiveTrailers(status) {
return lodash_1.flowRight(lodash_1.map(this.filters, (filter) => filter.receiveTrailers.bind(filter)))(status);
}
}
exports.FilterStack = FilterStack;
class FilterStackFactory {
constructor(factories) {
this.factories = factories;
}
createFilter(callStream) {
return new FilterStack(lodash_1.map(this.factories, (factory) => factory.createFilter(callStream)));
}
}
exports.FilterStackFactory = FilterStackFactory;
//# sourceMappingURL=filter-stack.js.map

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;
}

View File

@ -0,0 +1,39 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
class BaseFilter {
sendMetadata(metadata) {
return __awaiter(this, void 0, void 0, function* () {
return metadata;
});
}
receiveMetadata(metadata) {
return __awaiter(this, void 0, void 0, function* () {
return metadata;
});
}
sendMessage(message) {
return __awaiter(this, void 0, void 0, function* () {
return message;
});
}
receiveMessage(message) {
return __awaiter(this, void 0, void 0, function* () {
return message;
});
}
receiveTrailers(status) {
return __awaiter(this, void 0, void 0, function* () {
return status;
});
}
}
exports.BaseFilter = BaseFilter;
//# sourceMappingURL=filter.js.map

View File

@ -0,0 +1,43 @@
/// <reference types="node" />
import { Channel } from './channel';
import { Client } from './client';
import { LogVerbosity, Status } from './constants';
import { loadPackageDefinition, makeClientConstructor } from './make-client';
import { Metadata } from './metadata';
import { StatusBuilder } from './status-builder';
export interface OAuth2Client {
getRequestMetadata: (url: string, callback: (err: Error | null, headers?: {
Authorization: string;
}) => void) => void;
}
/**** Client Credentials ****/
export declare const credentials: {
[key: string]: Function;
};
/**** Metadata ****/
export { Metadata };
/**** Constants ****/
export { LogVerbosity as logVerbosity, Status as status };
/**** Client ****/
export { Client, loadPackageDefinition, makeClientConstructor, makeClientConstructor as makeGenericClientConstructor, 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;
/**** 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 declare const Server: (options: any) => never;
export declare const ServerCredentials: {
createSsl: (rootCerts: any, keyCertPairs: any, checkClientCertificate: any) => never;
createInsecure: () => never;
};
export declare const getClientChannel: (client: Client) => any;
export { StatusBuilder };
export declare const ListenerBuilder: () => never;
export declare const InterceptorBuilder: () => never;
export declare const InterceptingCall: () => never;

View File

@ -0,0 +1,121 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const semver = require("semver");
const call_credentials_1 = require("./call-credentials");
const channel_credentials_1 = require("./channel-credentials");
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 status_builder_1 = require("./status-builder");
exports.StatusBuilder = status_builder_1.StatusBuilder;
const supportedNodeVersions = '^8.11.2 || >=9.4';
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) => {
googleCredentials.getRequestMetadata(options.service_url, (err, headers) => {
if (err) {
callback(err);
return;
}
const metadata = new metadata_1.Metadata();
metadata.add('authorization', headers.Authorization);
callback(null, metadata);
});
});
},
/**
* 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.Server = (options) => {
throw new Error('Not yet implemented');
};
exports.ServerCredentials = {
createSsl: (rootCerts, keyCertPairs, checkClientCertificate) => {
throw new Error('Not yet implemented');
},
createInsecure: () => {
throw new Error('Not yet implemented');
}
};
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');
};
//# sourceMappingURL=index.js.map

View File

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

View File

@ -0,0 +1,21 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const constants_1 = require("./constants");
let _logger = console;
let _logVerbosity = constants_1.LogVerbosity.DEBUG;
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);
}
};
//# sourceMappingURL=logging.js.map

View File

@ -0,0 +1,57 @@
/// <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<object, object>;
}
export interface PackageDefinition {
[index: string]: ServiceDefinition;
}
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 declare type GrpcObject = {
[index: string]: GrpcObject | ServiceClientConstructor;
};
/**
* 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;

View File

@ -0,0 +1,98 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const _ = require("lodash");
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 {
}
_.each(methods, (attrs, name) => {
let methodType;
// TODO(murgatroid99): Verify that we don't need this anymore
if (_.startsWith(name, '$')) {
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
_.assign(ServiceClientImpl.prototype[name], attrs);
if (attrs.originalName) {
ServiceClientImpl.prototype[attrs.originalName] =
ServiceClientImpl.prototype[name];
}
});
ServiceClientImpl.service = methods;
return ServiceClientImpl;
}
exports.makeClientConstructor = makeClientConstructor;
/**
* 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];
}
current[serviceName] = makeClientConstructor(service, serviceName, {});
}
}
return result;
}
exports.loadPackageDefinition = loadPackageDefinition;
//# sourceMappingURL=make-client.js.map

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,48 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const constants_1 = require("./constants");
const filter_1 = require("./filter");
class MetadataStatusFilter extends filter_1.BaseFilter {
receiveTrailers(status) {
return __awaiter(this, void 0, void 0, function* () {
// tslint:disable-next-line:prefer-const
let { code, details, metadata } = yield 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,71 @@
/// <reference types="node" />
import * as http2 from 'http2';
export declare type MetadataValue = string | Buffer;
export interface MetadataObject {
[key: string]: MetadataValue[];
}
/**
* A class for storing metadata. Keys are normalized to lowercase ASCII.
*/
export declare class Metadata {
protected internalRepr: MetadataObject;
/**
* 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;
/**
* 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;
}

View File

@ -0,0 +1,214 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const lodash_1 = require("lodash");
const LEGAL_KEY_REGEX = /^[0-9a-z_.-]+$/;
const LEGAL_NON_BINARY_VALUE_REGEX = /^[ -~]*$/;
function cloneMetadataObject(repr) {
const result = {};
lodash_1.forOwn(repr, (value, key) => {
result[key] = value.map(v => {
if (v instanceof Buffer) {
return Buffer.from(v);
}
else {
return v;
}
});
});
return result;
}
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 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() {
this.internalRepr = {};
}
/**
* 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[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);
if (!this.internalRepr[key]) {
this.internalRepr[key] = [value];
}
else {
this.internalRepr[key].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);
if (Object.prototype.hasOwnProperty.call(this.internalRepr, key)) {
delete this.internalRepr[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);
if (Object.prototype.hasOwnProperty.call(this.internalRepr, key)) {
return this.internalRepr[key];
}
else {
return [];
}
}
/**
* 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 = {};
lodash_1.forOwn(this.internalRepr, (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();
newMetadata.internalRepr = cloneMetadataObject(this.internalRepr);
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) {
lodash_1.forOwn(other.internalRepr, (values, key) => {
this.internalRepr[key] = (this.internalRepr[key] || []).concat(values);
});
}
/**
* Creates an OutgoingHttpHeaders object that can be used with the http2 API.
*/
toHttp2Headers() {
// NOTE: Node <8.9 formats http2 headers incorrectly.
const result = {};
lodash_1.forOwn(this.internalRepr, (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();
lodash_1.forOwn(headers, (values, key) => {
// Reserved headers (beginning with `:`) are not valid keys.
if (key.charAt(0) === ':') {
return;
}
if (isBinaryKey(key)) {
if (Array.isArray(values)) {
values.forEach((value) => {
result.add(key, Buffer.from(value, 'base64'));
});
}
else if (values !== undefined) {
values.split(',').forEach(v => {
result.add(key, Buffer.from(v.trim(), 'base64'));
});
}
}
else {
if (Array.isArray(values)) {
values.forEach((value) => {
result.add(key, value);
});
}
else if (values !== undefined) {
values.split(',').forEach(v => result.add(key, v.trim()));
}
}
});
return result;
}
}
exports.Metadata = Metadata;
//# sourceMappingURL=metadata.js.map

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>;

View File

@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=object-stream.js.map

View File

@ -0,0 +1,28 @@
import { StatusObject } from './call-stream';
import { Status } from './constants';
import { Metadata } from './metadata';
/**
* A builder for gRPC status objects.
*/
export declare class StatusBuilder {
private code;
private details;
private metadata;
constructor();
/**
* Adds a status code to the builder.
*/
withCode(code: Status): this;
/**
* Adds details to the builder.
*/
withDetails(details: string): this;
/**
* Adds metadata to the builder.
*/
withMetadata(metadata: Metadata): this;
/**
* Builds the status object.
*/
build(): Partial<StatusObject>;
}

View File

@ -0,0 +1,51 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* A builder for gRPC status objects.
*/
class StatusBuilder {
constructor() {
this.code = null;
this.details = null;
this.metadata = null;
}
/**
* Adds a status code to the builder.
*/
withCode(code) {
this.code = code;
return this;
}
/**
* Adds details to the builder.
*/
withDetails(details) {
this.details = details;
return this;
}
/**
* Adds metadata to the builder.
*/
withMetadata(metadata) {
this.metadata = metadata;
return this;
}
/**
* Builds the status object.
*/
build() {
const status = {};
if (this.code !== null) {
status.code = this.code;
}
if (this.details !== null) {
status.details = this.details;
}
if (this.metadata !== null) {
status.metadata = this.metadata;
}
return status;
}
}
exports.StatusBuilder = StatusBuilder;
//# sourceMappingURL=status-builder.js.map

View File

@ -0,0 +1,33 @@
/// <reference types="node" />
import { EventEmitter } from 'events';
import * as http2 from 'http2';
import * as url from 'url';
import { Call, Http2CallStream } from './call-stream';
import { ChannelOptions } from './channel-options';
import { Metadata } from './metadata';
export interface SubChannel extends EventEmitter {
/**
* Attach a call stream to this subchannel's connection to start it
* @param headers The headers to start the stream with
* @param callStream The stream to start
*/
startCallStream(metadata: Metadata, callStream: Call): void;
close(): void;
}
export declare class Http2SubChannel extends EventEmitter implements SubChannel {
private session;
private refCount;
private userAgent;
private keepaliveTimeMs;
private keepaliveTimeoutMs;
private keepaliveIntervalId;
private keepaliveTimeoutId;
constructor(target: url.URL, connectionOptions: http2.SecureClientSessionOptions, userAgent: string, channelArgs: Partial<ChannelOptions>);
private ref();
private unref();
private sendPing();
private startKeepalivePings();
private stopKeepalivePings();
startCallStream(metadata: Metadata, callStream: Http2CallStream): void;
close(): void;
}

View File

@ -0,0 +1,96 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const events_1 = require("events");
const http2 = require("http2");
const { HTTP2_HEADER_AUTHORITY, HTTP2_HEADER_CONTENT_TYPE, HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, HTTP2_HEADER_TE, HTTP2_HEADER_USER_AGENT } = http2.constants;
/* setInterval and setTimeout only accept signed 32 bit integers. JS doesn't
* have a constant for the max signed 32 bit integer, so this is a simple way
* to calculate it */
const KEEPALIVE_TIME_MS = ~(1 << 31);
const KEEPALIVE_TIMEOUT_MS = 20000;
class Http2SubChannel extends events_1.EventEmitter {
constructor(target, connectionOptions, userAgent, channelArgs) {
super();
this.refCount = 0;
this.keepaliveTimeMs = KEEPALIVE_TIME_MS;
this.keepaliveTimeoutMs = KEEPALIVE_TIMEOUT_MS;
this.session = http2.connect(target, connectionOptions);
this.session.on('connect', () => {
this.emit('connect');
});
this.session.on('close', () => {
this.stopKeepalivePings();
this.emit('close');
});
this.session.on('error', () => {
this.stopKeepalivePings();
this.emit('close');
});
this.userAgent = userAgent;
if (channelArgs['grpc.keepalive_time_ms']) {
this.keepaliveTimeMs = channelArgs['grpc.keepalive_time_ms'];
}
if (channelArgs['grpc.keepalive_timeout_ms']) {
this.keepaliveTimeoutMs = channelArgs['grpc.keepalive_timeout_ms'];
}
this.keepaliveIntervalId = setTimeout(() => { }, 0);
clearTimeout(this.keepaliveIntervalId);
this.keepaliveTimeoutId = setTimeout(() => { }, 0);
clearTimeout(this.keepaliveTimeoutId);
}
ref() {
if (this.refCount === 0) {
this.session.ref();
this.startKeepalivePings();
}
this.refCount += 1;
}
unref() {
this.refCount -= 1;
if (this.refCount === 0) {
this.session.unref();
this.stopKeepalivePings();
}
}
sendPing() {
this.keepaliveTimeoutId = setTimeout(() => {
this.emit('close');
}, this.keepaliveTimeoutMs);
this.session.ping((err, duration, payload) => {
clearTimeout(this.keepaliveTimeoutId);
});
}
/* TODO(murgatroid99): refactor subchannels so that keepalives can be handled
* per subchannel */
startKeepalivePings() {
this.keepaliveIntervalId = setInterval(() => {
this.sendPing();
}, this.keepaliveTimeMs);
this.sendPing();
}
stopKeepalivePings() {
clearInterval(this.keepaliveIntervalId);
clearTimeout(this.keepaliveTimeoutId);
}
// Prerequisite: this subchannel is connected
startCallStream(metadata, callStream) {
const headers = metadata.toHttp2Headers();
headers[HTTP2_HEADER_AUTHORITY] = callStream.getHost();
headers[HTTP2_HEADER_USER_AGENT] = this.userAgent;
headers[HTTP2_HEADER_CONTENT_TYPE] = 'application/grpc';
headers[HTTP2_HEADER_METHOD] = 'POST';
headers[HTTP2_HEADER_PATH] = callStream.getMethod();
headers[HTTP2_HEADER_TE] = 'trailers';
const http2Stream = this.session.request(headers);
this.ref();
http2Stream.on('close', () => {
this.unref();
});
callStream.attachHttp2Stream(http2Stream);
}
close() {
this.session.close();
}
}
exports.Http2SubChannel = Http2SubChannel;
//# sourceMappingURL=subchannel.js.map

79
express-server/node_modules/@grpc/grpc-js/package.json generated vendored Normal file
View File

@ -0,0 +1,79 @@
{
"_from": "@grpc/grpc-js@^0.3.0",
"_id": "@grpc/grpc-js@0.3.2",
"_inBundle": false,
"_integrity": "sha512-vvcC4EZwS2kzEuwe3zmExi20YM1tqO+L/xdpzInze0WnRfhwbssDfLtMfAyAPQaL2CD8dRZLCOVLbsSdF1KVjA==",
"_location": "/@grpc/grpc-js",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "@grpc/grpc-js@^0.3.0",
"name": "@grpc/grpc-js",
"escapedName": "@grpc%2fgrpc-js",
"scope": "@grpc",
"rawSpec": "^0.3.0",
"saveSpec": null,
"fetchSpec": "^0.3.0"
},
"_requiredBy": [
"/google-gax"
],
"_resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-0.3.2.tgz",
"_shasum": "8adcf22154bfd4a0903296d6656420c2ff86e388",
"_spec": "@grpc/grpc-js@^0.3.0",
"_where": "D:\\Desktop\\Git\\Firebase\\SmartShopperFirebase\\node_modules\\google-gax",
"author": {
"name": "Google Inc."
},
"bundleDependencies": false,
"contributors": [
{
"name": "Google Inc."
}
],
"dependencies": {
"lodash": "^4.17.4",
"semver": "^5.5.0"
},
"deprecated": false,
"description": "gRPC Library for Node - pure JS implementation",
"devDependencies": {
"@types/lodash": "^4.14.108",
"@types/mocha": "^2.2.43",
"@types/node": "^10.5.4",
"clang-format": "^1.0.55",
"gts": "^0.5.1",
"typescript": "~2.7.0"
},
"engines": {
"node": "^8.11.2 || >=9.4"
},
"files": [
"build/src/*.{js,d.ts}"
],
"homepage": "https://grpc.io/",
"keywords": [],
"license": "Apache-2.0",
"main": "build/src/index.js",
"name": "@grpc/grpc-js",
"repository": {
"type": "git",
"url": "https://github.com/grpc/grpc-node/tree/master/packages/grpc-js-core"
},
"scripts": {
"build": "npm run compile",
"check": "gts check",
"clean": "gts clean",
"compile": "tsc -p .",
"fix": "gts fix",
"format": "clang-format -i -style=\"{Language: JavaScript, BasedOnStyle: Google, ColumnLimit: 80}\" src/*.ts test/*.ts",
"lint": "tslint -c node_modules/google-ts-style/tslint.json -p . -t codeFrame --type-check",
"posttest": "npm run check",
"prepare": "npm run compile",
"pretest": "npm run compile",
"test": "gulp test"
},
"types": "build/src/index.d.ts",
"version": "0.3.2"
}