Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/refactor grpcweb service codegen #51

Merged
merged 4 commits into from
Apr 2, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ ts_library(
name = "src",
srcs = glob([
"*.ts",
"service/*.ts",
"ts/*.ts",
]),
deps = [],
Expand Down
18 changes: 3 additions & 15 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {ExportMap} from "./ExportMap";
import {filePathFromProtoWithoutExtension, withAllStdIn} from "./util";
import {CodeGeneratorRequest, CodeGeneratorResponse} from "google-protobuf/google/protobuf/compiler/plugin_pb";
import {FileDescriptorProto} from "google-protobuf/google/protobuf/descriptor_pb";
import {printFileDescriptorJSServices, printFileDescriptorTSServices} from "./ts/fileDescriptorTSServices";
import {generateGrpcWebService} from "./service/grpcweb";

withAllStdIn((inputBuff: Buffer) => {
try {
Expand Down Expand Up @@ -37,20 +37,8 @@ withAllStdIn((inputBuff: Buffer) => {
codeGenResponse.addFile(thisFile);

if (generateServices) {
const fileDescriptorTsOutput = printFileDescriptorTSServices(fileNameToDescriptor[fileName], exportMap);
if (fileDescriptorTsOutput !== "") {
const thisServiceFile = new CodeGeneratorResponse.File();
thisServiceFile.setName(outputFileName + "_service.d.ts");
thisServiceFile.setContent(fileDescriptorTsOutput);
codeGenResponse.addFile(thisServiceFile);
}
const fileDescriptorJsOutput = printFileDescriptorJSServices(fileNameToDescriptor[fileName], exportMap);
if (fileDescriptorJsOutput !== "") {
const thisServiceFile = new CodeGeneratorResponse.File();
thisServiceFile.setName(outputFileName + "_service.js");
thisServiceFile.setContent(fileDescriptorJsOutput);
codeGenResponse.addFile(thisServiceFile);
}
generateGrpcWebService(outputFileName, fileNameToDescriptor[fileName], exportMap)
.forEach(file => codeGenResponse.addFile(file));
}
});

Expand Down
242 changes: 242 additions & 0 deletions src/service/grpcweb.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,242 @@
import {filePathToPseudoNamespace, filePathFromProtoWithoutExtension, getPathToRoot} from "../util";
import {ExportMap} from "../ExportMap";
import {Printer} from "../Printer";
import {
FileDescriptorProto, MethodDescriptorProto,
ServiceDescriptorProto
} from "google-protobuf/google/protobuf/descriptor_pb";
import {WellKnownTypesMap} from "../WellKnown";
import {getFieldType, MESSAGE_TYPE} from "../ts/FieldTypes";
import {CodeGeneratorResponse} from "google-protobuf/google/protobuf/compiler/plugin_pb";

export function generateGrpcWebService(filename: string, descriptor: FileDescriptorProto, exportMap: ExportMap): CodeGeneratorResponse.File[] {
if (descriptor.getServiceList().length === 0) {
return [];
}
return [
createFile(generateTypescriptDefinition(descriptor, exportMap), `${filename}_service.d.ts`),
createFile(generateJavaScript(descriptor, exportMap), `${filename}_service.js`),
];
}

function createFile(output: string, filename: string): CodeGeneratorResponse.File {
const file = new CodeGeneratorResponse.File();
file.setName(filename);
file.setContent(output);
return file;
}

type CallingTypes = {
requestType: string
responseType: string
}

function getCallingTypes(method: MethodDescriptorProto, exportMap: ExportMap): CallingTypes {
return {
requestType: getFieldType(MESSAGE_TYPE, method.getInputType().slice(1), "", exportMap),
responseType: getFieldType(MESSAGE_TYPE, method.getOutputType().slice(1), "", exportMap),
};
}

function isUsed(fileDescriptor: FileDescriptorProto, pseudoNamespace: string, exportMap: ExportMap) {
return fileDescriptor.getServiceList().some(service => {
return service.getMethodList().some(method => {
const callingTypes = getCallingTypes(method, exportMap);
const namespacePackage = pseudoNamespace + ".";
return (
callingTypes.requestType.indexOf(namespacePackage) === 0 ||
callingTypes.responseType.indexOf(namespacePackage) === 0
);
});
});
}

type ImportDescriptor = {
readonly namespace: string
readonly path: string
};

type RPCMethodDescriptor = {
readonly name: string,
readonly serviceName: string,
readonly requestStream: boolean
readonly responseStream: boolean
readonly requestType: string
readonly responseType: string
};

class RPCDescriptor {
private readonly grpcService: GrpcWebServiceDescriptor;
private readonly protoService: ServiceDescriptorProto;
private readonly exportMap: ExportMap;

constructor(grpcService: GrpcWebServiceDescriptor, protoService: ServiceDescriptorProto, exportMap: ExportMap) {
this.grpcService = grpcService;
this.protoService = protoService;
this.exportMap = exportMap;
}
get name(): string {
return this.protoService.getName();
}

get qualifiedName(): string {
return (this.grpcService.packageName ? `${this.grpcService.packageName}.` : "") + this.name;
}

get methods(): RPCMethodDescriptor[] {
return this.protoService.getMethodList()
.map(method => {
const callingTypes = getCallingTypes(method, this.exportMap);
return {
name: method.getName(),
serviceName: this.name,
requestStream: method.getClientStreaming(),
responseStream: method.getServerStreaming(),
requestType: callingTypes.requestType,
responseType: callingTypes.responseType,
}
});
}
}

class GrpcWebServiceDescriptor {
private readonly fileDescriptor: FileDescriptorProto;
private readonly exportMap: ExportMap;
private readonly pathToRoot: string;

constructor(fileDescriptor: FileDescriptorProto, exportMap: ExportMap) {
this.fileDescriptor = fileDescriptor;
this.exportMap = exportMap;
this.pathToRoot = getPathToRoot(fileDescriptor.getName())
}

get filename(): string {
return this.fileDescriptor.getName();
}

get packageName(): string {
return this.fileDescriptor.getPackage();
}

get imports(): ImportDescriptor[] {
const dependencies = this.fileDescriptor.getDependencyList()
.filter(dependency => isUsed(this.fileDescriptor, filePathToPseudoNamespace(dependency), this.exportMap))
.map(dependency => {
const namespace = filePathToPseudoNamespace(dependency);
if (dependency in WellKnownTypesMap) {
return {
namespace,
path: WellKnownTypesMap[dependency],
}
} else {
return {
namespace,
path: `${this.pathToRoot}${filePathFromProtoWithoutExtension(filePathFromProtoWithoutExtension(dependency))}`
}
}
});
const hostProto = {
namespace: filePathToPseudoNamespace(this.filename),
path: `${this.pathToRoot}${filePathFromProtoWithoutExtension(this.filename)}`,
};
return [ hostProto ].concat(dependencies);
}

get services(): RPCDescriptor[] {
return this.fileDescriptor.getServiceList()
.map(service => {
return new RPCDescriptor(this, service, this.exportMap);
})
}
}

function generateTypescriptDefinition(fileDescriptor: FileDescriptorProto, exportMap: ExportMap) {
const serviceDescriptor = new GrpcWebServiceDescriptor(fileDescriptor, exportMap);
const printer = new Printer(0);

// Header.
printer.printLn(`// package: ${serviceDescriptor.packageName}`);
printer.printLn(`// file: ${serviceDescriptor.filename}`);
printer.printEmptyLn();

// Import statements.
serviceDescriptor.imports
.forEach(importDescriptor => {
printer.printLn(`import * as ${importDescriptor.namespace} from "${importDescriptor.path}";`);
});
printer.printEmptyLn();

// Services.
serviceDescriptor.services
.forEach(service => {

// Method Type Definitions
service.methods.forEach(method => {
printer.printLn(`type ${method.serviceName}${method.name} = {`);
printer.printIndentedLn(`readonly methodName: string;`);
printer.printIndentedLn(`readonly service: typeof ${method.serviceName};`);
printer.printIndentedLn(`readonly requestStream: ${method.requestStream};`);
printer.printIndentedLn(`readonly responseStream: ${method.responseStream};`);
printer.printIndentedLn(`readonly requestType: typeof ${method.requestType};`);
printer.printIndentedLn(`readonly responseType: typeof ${method.responseType};`);
printer.printLn(`};`);
printer.printEmptyLn();
});

printer.printLn(`export class ${service.name} {`);
printer.printIndentedLn(`static readonly serviceName: string;`);
service.methods.forEach(method => {
printer.printIndentedLn(`static readonly ${method.name}: ${method.serviceName}${method.name};`);
});
printer.printLn(`}`);
printer.printEmptyLn();
});

return printer.getOutput();
}

function generateJavaScript(fileDescriptor: FileDescriptorProto, exportMap: ExportMap) {
const serviceDescriptor = new GrpcWebServiceDescriptor(fileDescriptor, exportMap);
const printer = new Printer(0);

// Header.
printer.printLn(`// package: ${serviceDescriptor.packageName}`);
printer.printLn(`// file: ${serviceDescriptor.filename}`);
printer.printEmptyLn();

// Import Statements
serviceDescriptor.imports
.forEach(importDescriptor => {
printer.printLn(`var ${importDescriptor.namespace} = require("${importDescriptor.path}");`);
});
printer.printEmptyLn();

// Services.
serviceDescriptor.services
.forEach(service => {
printer.printLn(`var ${service.name} = (function () {`);
printer.printIndentedLn(`function ${service.name}() {}`);
printer.printIndentedLn(`${service.name}.serviceName = "${service.qualifiedName}";`);
printer.printIndentedLn(`return ${service.name};`);
printer.printLn(`}());`);
printer.printEmptyLn();

service.methods
.forEach(method => {
printer.print(`${method.serviceName}.${method.name} = {`);
printer.printIndentedLn(`methodName: "${method.name}",`);
printer.printIndentedLn(`service: ${method.serviceName},`);
printer.printIndentedLn(`requestStream: ${method.requestStream},`);
printer.printIndentedLn(`responseStream: ${method.responseStream},`);
printer.printIndentedLn(`requestType: ${method.requestType},`);
printer.printIndentedLn(`responseType: ${method.responseType}`);
printer.printLn(`};`);
printer.printEmptyLn();
});

printer.printLn(`exports.${service.name} = ${service.name};`);
printer.printEmptyLn();
});

return printer.getOutput();
}
Loading