Skip to content

Commit

Permalink
Merge pull request #285 from murgatroid99/ts_style_cleanup
Browse files Browse the repository at this point in the history
Fix lint errors and formatting
  • Loading branch information
murgatroid99 authored Apr 18, 2018
2 parents 5c9a792 + 881b82d commit f1acaf2
Show file tree
Hide file tree
Showing 19 changed files with 604 additions and 555 deletions.
17 changes: 8 additions & 9 deletions packages/grpc-js-core/src/call-credentials-filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,10 @@ export class CallCredentialsFilter extends BaseFilter implements Filter {
private serviceUrl: string;
constructor(
private readonly credentials: CallCredentials,
private readonly host: string,
private readonly path: string) {
private readonly host: string, private readonly path: string) {
super();
let splitPath: string[] = path.split('/');
let serviceName: string = '';
const splitPath: string[] = path.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 */
Expand All @@ -27,8 +26,9 @@ export class CallCredentialsFilter extends BaseFilter implements Filter {
}

async sendMetadata(metadata: Promise<Metadata>): Promise<Metadata> {
let credsMetadata = this.credentials.generateMetadata({ service_url: this.serviceUrl });
let resultMetadata = await metadata;
const credsMetadata =
this.credentials.generateMetadata({service_url: this.serviceUrl});
const resultMetadata = await metadata;
resultMetadata.merge(await credsMetadata);
return resultMetadata;
}
Expand All @@ -43,8 +43,7 @@ export class CallCredentialsFilterFactory implements

createFilter(callStream: CallStream): CallCredentialsFilter {
return new CallCredentialsFilter(
this.credentials.compose(callStream.getCredentials()),
callStream.getHost(),
callStream.getMethod());
this.credentials.compose(callStream.getCredentials()),
callStream.getHost(), callStream.getMethod());
}
}
68 changes: 36 additions & 32 deletions packages/grpc-js-core/src/call-credentials.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,39 +2,59 @@ import {map, reduce} from 'lodash';

import {Metadata} from './metadata';

export type CallMetadataOptions = { service_url: string; };
export type CallMetadataOptions = {
service_url: string;
};

export type CallMetadataGenerator =
(options: CallMetadataOptions, cb: (err: Error|null, metadata?: Metadata) => void) =>
void;
(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 interface CallCredentials {
export abstract class CallCredentials {
/**
* Asynchronously generates a new Metadata object.
* @param options Options used in generating the Metadata object.
*/
generateMetadata(options: CallMetadataOptions): Promise<Metadata>;
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.
*/
compose(callCredentials: CallCredentials): CallCredentials;
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 {
return new SingleCallCredentials(metadataGenerator);
}

static createEmpty(): CallCredentials {
return new EmptyCallCredentials();
}
}

class ComposedCallCredentials implements CallCredentials {
constructor(private creds: CallCredentials[]) {}
class ComposedCallCredentials extends CallCredentials {
constructor(private creds: CallCredentials[]) {
super();
}

async generateMetadata(options: CallMetadataOptions): Promise<Metadata> {
let base: Metadata = new Metadata();
let generated: Metadata[] = await Promise.all(
const base: Metadata = new Metadata();
const generated: Metadata[] = await Promise.all(
map(this.creds, (cred) => cred.generateMetadata(options)));
for (let gen of generated) {
for (const gen of generated) {
base.merge(gen);
}
return base;
Expand All @@ -45,8 +65,10 @@ class ComposedCallCredentials implements CallCredentials {
}
}

class SingleCallCredentials implements CallCredentials {
constructor(private metadataGenerator: CallMetadataGenerator) {}
class SingleCallCredentials extends CallCredentials {
constructor(private metadataGenerator: CallMetadataGenerator) {
super();
}

generateMetadata(options: CallMetadataOptions): Promise<Metadata> {
return new Promise<Metadata>((resolve, reject) => {
Expand All @@ -65,7 +87,7 @@ class SingleCallCredentials implements CallCredentials {
}
}

class EmptyCallCredentials implements CallCredentials {
class EmptyCallCredentials extends CallCredentials {
generateMetadata(options: CallMetadataOptions): Promise<Metadata> {
return Promise.resolve(new Metadata());
}
Expand All @@ -74,21 +96,3 @@ class EmptyCallCredentials implements CallCredentials {
return other;
}
}

export namespace 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.
*/
export function createFromMetadataGenerator(
metadataGenerator: CallMetadataGenerator): CallCredentials {
return new SingleCallCredentials(metadataGenerator);
}

export function createEmpty(): CallCredentials {
return new EmptyCallCredentials();
}
}
63 changes: 38 additions & 25 deletions packages/grpc-js-core/src/call-stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@ import {FilterStackFactory} from './filter-stack';
import {Metadata} from './metadata';
import {ObjectDuplex} from './object-stream';

const {HTTP2_HEADER_STATUS, HTTP2_HEADER_CONTENT_TYPE, NGHTTP2_CANCEL} = http2.constants;
const {HTTP2_HEADER_STATUS, HTTP2_HEADER_CONTENT_TYPE, NGHTTP2_CANCEL} =
http2.constants;

export type Deadline = Date | number;
export type Deadline = Date|number;

export interface CallStreamOptions {
deadline: Deadline;
Expand All @@ -36,20 +37,19 @@ export interface WriteObject {
/**
* This interface represents a duplex stream associated with a single gRPC call.
*/
export type CallStream = {
cancelWithStatus(status: Status, details: string): void;
getPeer(): string;
export type CallStream = {
cancelWithStatus(status: Status, details: string): void; getPeer(): string;

getDeadline(): Deadline;
getCredentials(): CallCredentials;
/* If the return value is null, the call has not ended yet. Otherwise, it has
* ended with the specified status */
getStatus(): StatusObject|null;
getStatus(): StatusObject | null;
getMethod(): string;
getHost(): string;
} & EmitterAugmentation1<'metadata', Metadata>
& EmitterAugmentation1<'status', StatusObject>
& ObjectDuplex<WriteObject, Buffer>;
}&EmitterAugmentation1<'metadata', Metadata>&
EmitterAugmentation1<'status', StatusObject>&
ObjectDuplex<WriteObject, Buffer>;

enum ReadState {
NO_DATA,
Expand All @@ -60,7 +60,7 @@ enum ReadState {
const emptyBuffer = Buffer.alloc(0);

export class Http2CallStream extends Duplex implements CallStream {
public filterStack: Filter;
filterStack: Filter;
private statusEmitted = false;
private http2Stream: http2.ClientHttp2Stream|null = null;
private pendingRead = false;
Expand All @@ -76,7 +76,7 @@ export class Http2CallStream extends Duplex implements CallStream {
private readPartialMessage: Buffer[] = [];
private readMessageRemaining = 0;

private unpushedReadMessages: (Buffer|null)[] = [];
private unpushedReadMessages: Array<Buffer|null> = [];

// Status code mapped from :status. To be used if grpc-status is not received
private mappedStatusCode: Status = Status.UNKNOWN;
Expand Down Expand Up @@ -124,20 +124,21 @@ export class Http2CallStream extends Duplex implements CallStream {
}

private handleTrailers(headers: http2.IncomingHttpHeaders) {
let code: Status = this.mappedStatusCode;
let details = '';
const code: Status = this.mappedStatusCode;
const details = '';
let metadata: Metadata;
try {
metadata = Metadata.fromHttp2Headers(headers);
} catch (e) {
metadata = new Metadata();
}
let status: StatusObject = {code, details, metadata};
const status: StatusObject = {code, details, metadata};
this.handlingTrailers = (async () => {
let finalStatus;
try {
// Attempt to assign final status.
finalStatus = await this.filterStack.receiveTrailers(Promise.resolve(status));
finalStatus =
await this.filterStack.receiveTrailers(Promise.resolve(status));
} catch (error) {
await this.handlingHeaders;
// This is a no-op if the call was already ended when handling headers.
Expand Down Expand Up @@ -195,17 +196,26 @@ export class Http2CallStream extends Duplex implements CallStream {
try {
metadata = Metadata.fromHttp2Headers(headers);
} catch (error) {
this.endCall({code: Status.UNKNOWN, details: error.message, metadata: new Metadata()});
this.endCall({
code: Status.UNKNOWN,
details: error.message,
metadata: new Metadata()
});
return;
}
this.handlingHeaders =
this.filterStack.receiveMetadata(Promise.resolve(metadata))
.then((finalMetadata) => {
this.emit('metadata', finalMetadata);
}).catch((error) => {
this.destroyHttp2Stream();
this.endCall({code: Status.UNKNOWN, details: error.message, metadata: new Metadata()});
});
this.filterStack.receiveMetadata(Promise.resolve(metadata))
.then((finalMetadata) => {
this.emit('metadata', finalMetadata);
})
.catch((error) => {
this.destroyHttp2Stream();
this.endCall({
code: Status.UNKNOWN,
details: error.message,
metadata: new Metadata()
});
});
}
});
stream.on('trailers', this.handleTrailers.bind(this));
Expand Down Expand Up @@ -260,6 +270,9 @@ export class Http2CallStream extends Duplex implements CallStream {
canPush = this.tryPush(messageBytes, canPush);
this.readState = ReadState.NO_DATA;
}
break;
default:
throw new Error('This should never happen');
}
}
});
Expand Down Expand Up @@ -298,7 +311,7 @@ export class Http2CallStream extends Duplex implements CallStream {
// 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: code, details: details, metadata: new Metadata()});
this.endCall({code, details, metadata: new Metadata()});
});
stream.on('error', (err: Error) => {
this.endCall({
Expand Down Expand Up @@ -338,7 +351,7 @@ export class Http2CallStream extends Duplex implements CallStream {
// If trailers are currently being processed, the call should be ended
// by handleTrailers instead.
await this.handlingTrailers;
this.endCall({code: status, details: details, metadata: new Metadata()});
this.endCall({code: status, details, metadata: new Metadata()});
})();
}

Expand Down
Loading

0 comments on commit f1acaf2

Please sign in to comment.