• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *
3  * Copyright 2016 gRPC authors.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */
18 
19 #include <map>
20 
21 #include "src/compiler/config.h"
22 #include "src/compiler/generator_helpers.h"
23 #include "src/compiler/node_generator.h"
24 #include "src/compiler/node_generator_helpers.h"
25 
26 using grpc::protobuf::Descriptor;
27 using grpc::protobuf::FileDescriptor;
28 using grpc::protobuf::MethodDescriptor;
29 using grpc::protobuf::ServiceDescriptor;
30 using grpc::protobuf::io::Printer;
31 using grpc::protobuf::io::StringOutputStream;
32 using std::map;
33 
34 namespace grpc_node_generator {
35 namespace {
36 
37 // Returns the alias we assign to the module of the given .proto filename
38 // when importing. Copied entirely from
39 // github:google/protobuf/src/google/protobuf/compiler/js/js_generator.cc#L154
ModuleAlias(const grpc::string filename)40 grpc::string ModuleAlias(const grpc::string filename) {
41   // This scheme could technically cause problems if a file includes any 2 of:
42   //   foo/bar_baz.proto
43   //   foo_bar_baz.proto
44   //   foo_bar/baz.proto
45   //
46   // We'll worry about this problem if/when we actually see it.  This name isn't
47   // exposed to users so we can change it later if we need to.
48   grpc::string basename = grpc_generator::StripProto(filename);
49   basename = grpc_generator::StringReplace(basename, "-", "$");
50   basename = grpc_generator::StringReplace(basename, "/", "_");
51   basename = grpc_generator::StringReplace(basename, ".", "_");
52   return basename + "_pb";
53 }
54 
55 // Given a filename like foo/bar/baz.proto, returns the corresponding JavaScript
56 // message file foo/bar/baz.js
GetJSMessageFilename(const grpc::string & filename)57 grpc::string GetJSMessageFilename(const grpc::string& filename) {
58   grpc::string name = filename;
59   return grpc_generator::StripProto(name) + "_pb.js";
60 }
61 
62 // Given a filename like foo/bar/baz.proto, returns the root directory
63 // path ../../
GetRootPath(const grpc::string & from_filename,const grpc::string & to_filename)64 grpc::string GetRootPath(const grpc::string& from_filename,
65                          const grpc::string& to_filename) {
66   if (to_filename.find("google/protobuf") == 0) {
67     // Well-known types (.proto files in the google/protobuf directory) are
68     // assumed to come from the 'google-protobuf' npm package.  We may want to
69     // generalize this exception later by letting others put generated code in
70     // their own npm packages.
71     return "google-protobuf/";
72   }
73   size_t slashes = std::count(from_filename.begin(), from_filename.end(), '/');
74   if (slashes == 0) {
75     return "./";
76   }
77   grpc::string result = "";
78   for (size_t i = 0; i < slashes; i++) {
79     result += "../";
80   }
81   return result;
82 }
83 
84 // Return the relative path to load to_file from the directory containing
85 // from_file, assuming that both paths are relative to the same directory
GetRelativePath(const grpc::string & from_file,const grpc::string & to_file)86 grpc::string GetRelativePath(const grpc::string& from_file,
87                              const grpc::string& to_file) {
88   return GetRootPath(from_file, to_file) + to_file;
89 }
90 
91 /* Finds all message types used in all services in the file, and returns them
92  * as a map of fully qualified message type name to message descriptor */
GetAllMessages(const FileDescriptor * file)93 map<grpc::string, const Descriptor*> GetAllMessages(
94     const FileDescriptor* file) {
95   map<grpc::string, const Descriptor*> message_types;
96   for (int service_num = 0; service_num < file->service_count();
97        service_num++) {
98     const ServiceDescriptor* service = file->service(service_num);
99     for (int method_num = 0; method_num < service->method_count();
100          method_num++) {
101       const MethodDescriptor* method = service->method(method_num);
102       const Descriptor* input_type = method->input_type();
103       const Descriptor* output_type = method->output_type();
104       message_types[input_type->full_name()] = input_type;
105       message_types[output_type->full_name()] = output_type;
106     }
107   }
108   return message_types;
109 }
110 
MessageIdentifierName(const grpc::string & name)111 grpc::string MessageIdentifierName(const grpc::string& name) {
112   return grpc_generator::StringReplace(name, ".", "_");
113 }
114 
NodeObjectPath(const Descriptor * descriptor)115 grpc::string NodeObjectPath(const Descriptor* descriptor) {
116   grpc::string module_alias = ModuleAlias(descriptor->file()->name());
117   grpc::string name = descriptor->full_name();
118   grpc_generator::StripPrefix(&name, descriptor->file()->package() + ".");
119   return module_alias + "." + name;
120 }
121 
122 // Prints out the message serializer and deserializer functions
PrintMessageTransformer(const Descriptor * descriptor,Printer * out,const Parameters & params)123 void PrintMessageTransformer(const Descriptor* descriptor, Printer* out,
124                              const Parameters& params) {
125   map<grpc::string, grpc::string> template_vars;
126   grpc::string full_name = descriptor->full_name();
127   template_vars["identifier_name"] = MessageIdentifierName(full_name);
128   template_vars["name"] = full_name;
129   template_vars["node_name"] = NodeObjectPath(descriptor);
130   // Print the serializer
131   out->Print(template_vars, "function serialize_$identifier_name$(arg) {\n");
132   out->Indent();
133   out->Print(template_vars, "if (!(arg instanceof $node_name$)) {\n");
134   out->Indent();
135   out->Print(template_vars,
136              "throw new Error('Expected argument of type $name$');\n");
137   out->Outdent();
138   out->Print("}\n");
139   if (params.minimum_node_version > 5) {
140     // Node version is > 5, we should use Buffer.from
141     out->Print("return Buffer.from(arg.serializeBinary());\n");
142   } else {
143     out->Print("return new Buffer(arg.serializeBinary());\n");
144   }
145   out->Outdent();
146   out->Print("}\n\n");
147 
148   // Print the deserializer
149   out->Print(template_vars,
150              "function deserialize_$identifier_name$(buffer_arg) {\n");
151   out->Indent();
152   out->Print(
153       template_vars,
154       "return $node_name$.deserializeBinary(new Uint8Array(buffer_arg));\n");
155   out->Outdent();
156   out->Print("}\n\n");
157 }
158 
PrintMethod(const MethodDescriptor * method,Printer * out)159 void PrintMethod(const MethodDescriptor* method, Printer* out) {
160   const Descriptor* input_type = method->input_type();
161   const Descriptor* output_type = method->output_type();
162   map<grpc::string, grpc::string> vars;
163   vars["service_name"] = method->service()->full_name();
164   vars["name"] = method->name();
165   vars["input_type"] = NodeObjectPath(input_type);
166   vars["input_type_id"] = MessageIdentifierName(input_type->full_name());
167   vars["output_type"] = NodeObjectPath(output_type);
168   vars["output_type_id"] = MessageIdentifierName(output_type->full_name());
169   vars["client_stream"] = method->client_streaming() ? "true" : "false";
170   vars["server_stream"] = method->server_streaming() ? "true" : "false";
171   out->Print("{\n");
172   out->Indent();
173   out->Print(vars, "path: '/$service_name$/$name$',\n");
174   out->Print(vars, "requestStream: $client_stream$,\n");
175   out->Print(vars, "responseStream: $server_stream$,\n");
176   out->Print(vars, "requestType: $input_type$,\n");
177   out->Print(vars, "responseType: $output_type$,\n");
178   out->Print(vars, "requestSerialize: serialize_$input_type_id$,\n");
179   out->Print(vars, "requestDeserialize: deserialize_$input_type_id$,\n");
180   out->Print(vars, "responseSerialize: serialize_$output_type_id$,\n");
181   out->Print(vars, "responseDeserialize: deserialize_$output_type_id$,\n");
182   out->Outdent();
183   out->Print("}");
184 }
185 
186 // Prints out the service descriptor object
PrintService(const ServiceDescriptor * service,Printer * out)187 void PrintService(const ServiceDescriptor* service, Printer* out) {
188   map<grpc::string, grpc::string> template_vars;
189   out->Print(GetNodeComments(service, true).c_str());
190   template_vars["name"] = service->name();
191   out->Print(template_vars, "var $name$Service = exports.$name$Service = {\n");
192   out->Indent();
193   for (int i = 0; i < service->method_count(); i++) {
194     grpc::string method_name =
195         grpc_generator::LowercaseFirstLetter(service->method(i)->name());
196     out->Print(GetNodeComments(service->method(i), true).c_str());
197     out->Print("$method_name$: ", "method_name", method_name);
198     PrintMethod(service->method(i), out);
199     out->Print(",\n");
200     out->Print(GetNodeComments(service->method(i), false).c_str());
201   }
202   out->Outdent();
203   out->Print("};\n\n");
204   out->Print(template_vars,
205              "exports.$name$Client = "
206              "grpc.makeGenericClientConstructor($name$Service);\n");
207   out->Print(GetNodeComments(service, false).c_str());
208 }
209 
PrintImports(const FileDescriptor * file,Printer * out)210 void PrintImports(const FileDescriptor* file, Printer* out) {
211   out->Print("var grpc = require('grpc');\n");
212   if (file->message_type_count() > 0) {
213     grpc::string file_path =
214         GetRelativePath(file->name(), GetJSMessageFilename(file->name()));
215     out->Print("var $module_alias$ = require('$file_path$');\n", "module_alias",
216                ModuleAlias(file->name()), "file_path", file_path);
217   }
218 
219   for (int i = 0; i < file->dependency_count(); i++) {
220     grpc::string file_path = GetRelativePath(
221         file->name(), GetJSMessageFilename(file->dependency(i)->name()));
222     out->Print("var $module_alias$ = require('$file_path$');\n", "module_alias",
223                ModuleAlias(file->dependency(i)->name()), "file_path",
224                file_path);
225   }
226   out->Print("\n");
227 }
228 
PrintTransformers(const FileDescriptor * file,Printer * out,const Parameters & params)229 void PrintTransformers(const FileDescriptor* file, Printer* out,
230                        const Parameters& params) {
231   map<grpc::string, const Descriptor*> messages = GetAllMessages(file);
232   for (std::map<grpc::string, const Descriptor*>::iterator it =
233            messages.begin();
234        it != messages.end(); it++) {
235     PrintMessageTransformer(it->second, out, params);
236   }
237   out->Print("\n");
238 }
239 
PrintServices(const FileDescriptor * file,Printer * out)240 void PrintServices(const FileDescriptor* file, Printer* out) {
241   for (int i = 0; i < file->service_count(); i++) {
242     PrintService(file->service(i), out);
243   }
244 }
245 }  // namespace
246 
GenerateFile(const FileDescriptor * file,const Parameters & params)247 grpc::string GenerateFile(const FileDescriptor* file,
248                           const Parameters& params) {
249   grpc::string output;
250   {
251     StringOutputStream output_stream(&output);
252     Printer out(&output_stream, '$');
253 
254     if (file->service_count() == 0) {
255       return output;
256     }
257     out.Print("// GENERATED CODE -- DO NOT EDIT!\n\n");
258 
259     grpc::string leading_comments = GetNodeComments(file, true);
260     if (!leading_comments.empty()) {
261       out.Print("// Original file comments:\n");
262       out.PrintRaw(leading_comments.c_str());
263     }
264 
265     out.Print("'use strict';\n");
266 
267     PrintImports(file, &out);
268 
269     PrintTransformers(file, &out, params);
270 
271     PrintServices(file, &out);
272 
273     out.Print(GetNodeComments(file, false).c_str());
274   }
275   return output;
276 }
277 
278 }  // namespace grpc_node_generator
279