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 std::string filename)40 std::string ModuleAlias(const std::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 std::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 std::string & filename)57 std::string GetJSMessageFilename(const std::string& filename) {
58 std::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 std::string & from_filename,const std::string & to_filename)64 std::string GetRootPath(const std::string& from_filename,
65 const std::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 std::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 std::string & from_file,const std::string & to_file)86 std::string GetRelativePath(const std::string& from_file,
87 const std::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<std::string, const Descriptor*> GetAllMessages(const FileDescriptor* file) {
94 map<std::string, const Descriptor*> message_types;
95 for (int service_num = 0; service_num < file->service_count();
96 service_num++) {
97 const ServiceDescriptor* service = file->service(service_num);
98 for (int method_num = 0; method_num < service->method_count();
99 method_num++) {
100 const MethodDescriptor* method = service->method(method_num);
101 const Descriptor* input_type = method->input_type();
102 const Descriptor* output_type = method->output_type();
103 message_types[input_type->full_name()] = input_type;
104 message_types[output_type->full_name()] = output_type;
105 }
106 }
107 return message_types;
108 }
109
MessageIdentifierName(const std::string & name)110 std::string MessageIdentifierName(const std::string& name) {
111 return grpc_generator::StringReplace(name, ".", "_");
112 }
113
NodeObjectPath(const Descriptor * descriptor)114 std::string NodeObjectPath(const Descriptor* descriptor) {
115 std::string module_alias = ModuleAlias(descriptor->file()->name());
116 std::string name = descriptor->full_name();
117 grpc_generator::StripPrefix(&name, descriptor->file()->package() + ".");
118 return module_alias + "." + name;
119 }
120
121 // Prints out the message serializer and deserializer functions
PrintMessageTransformer(const Descriptor * descriptor,Printer * out,const Parameters & params)122 void PrintMessageTransformer(const Descriptor* descriptor, Printer* out,
123 const Parameters& params) {
124 map<std::string, std::string> template_vars;
125 std::string full_name = descriptor->full_name();
126 template_vars["identifier_name"] = MessageIdentifierName(full_name);
127 template_vars["name"] = full_name;
128 template_vars["node_name"] = NodeObjectPath(descriptor);
129 // Print the serializer
130 out->Print(template_vars, "function serialize_$identifier_name$(arg) {\n");
131 out->Indent();
132 out->Print(template_vars, "if (!(arg instanceof $node_name$)) {\n");
133 out->Indent();
134 out->Print(template_vars,
135 "throw new Error('Expected argument of type $name$');\n");
136 out->Outdent();
137 out->Print("}\n");
138 if (params.minimum_node_version > 5) {
139 // Node version is > 5, we should use Buffer.from
140 out->Print("return Buffer.from(arg.serializeBinary());\n");
141 } else {
142 out->Print("return new Buffer(arg.serializeBinary());\n");
143 }
144 out->Outdent();
145 out->Print("}\n\n");
146
147 // Print the deserializer
148 out->Print(template_vars,
149 "function deserialize_$identifier_name$(buffer_arg) {\n");
150 out->Indent();
151 out->Print(
152 template_vars,
153 "return $node_name$.deserializeBinary(new Uint8Array(buffer_arg));\n");
154 out->Outdent();
155 out->Print("}\n\n");
156 }
157
PrintMethod(const MethodDescriptor * method,Printer * out)158 void PrintMethod(const MethodDescriptor* method, Printer* out) {
159 const Descriptor* input_type = method->input_type();
160 const Descriptor* output_type = method->output_type();
161 map<std::string, std::string> vars;
162 vars["service_name"] = method->service()->full_name();
163 vars["name"] = method->name();
164 vars["input_type"] = NodeObjectPath(input_type);
165 vars["input_type_id"] = MessageIdentifierName(input_type->full_name());
166 vars["output_type"] = NodeObjectPath(output_type);
167 vars["output_type_id"] = MessageIdentifierName(output_type->full_name());
168 vars["client_stream"] = method->client_streaming() ? "true" : "false";
169 vars["server_stream"] = method->server_streaming() ? "true" : "false";
170 out->Print("{\n");
171 out->Indent();
172 out->Print(vars, "path: '/$service_name$/$name$',\n");
173 out->Print(vars, "requestStream: $client_stream$,\n");
174 out->Print(vars, "responseStream: $server_stream$,\n");
175 out->Print(vars, "requestType: $input_type$,\n");
176 out->Print(vars, "responseType: $output_type$,\n");
177 out->Print(vars, "requestSerialize: serialize_$input_type_id$,\n");
178 out->Print(vars, "requestDeserialize: deserialize_$input_type_id$,\n");
179 out->Print(vars, "responseSerialize: serialize_$output_type_id$,\n");
180 out->Print(vars, "responseDeserialize: deserialize_$output_type_id$,\n");
181 out->Outdent();
182 out->Print("}");
183 }
184
185 // Prints out the service descriptor object
PrintService(const ServiceDescriptor * service,Printer * out)186 void PrintService(const ServiceDescriptor* service, Printer* out) {
187 map<std::string, std::string> template_vars;
188 out->Print(GetNodeComments(service, true).c_str());
189 template_vars["name"] = service->name();
190 out->Print(template_vars, "var $name$Service = exports.$name$Service = {\n");
191 out->Indent();
192 for (int i = 0; i < service->method_count(); i++) {
193 std::string method_name =
194 grpc_generator::LowercaseFirstLetter(service->method(i)->name());
195 out->Print(GetNodeComments(service->method(i), true).c_str());
196 out->Print("$method_name$: ", "method_name", method_name);
197 PrintMethod(service->method(i), out);
198 out->Print(",\n");
199 out->Print(GetNodeComments(service->method(i), false).c_str());
200 }
201 out->Outdent();
202 out->Print("};\n\n");
203 out->Print(template_vars,
204 "exports.$name$Client = "
205 "grpc.makeGenericClientConstructor($name$Service);\n");
206 out->Print(GetNodeComments(service, false).c_str());
207 }
208
PrintImports(const FileDescriptor * file,Printer * out)209 void PrintImports(const FileDescriptor* file, Printer* out) {
210 out->Print("var grpc = require('grpc');\n");
211 if (file->message_type_count() > 0) {
212 std::string file_path =
213 GetRelativePath(file->name(), GetJSMessageFilename(file->name()));
214 out->Print("var $module_alias$ = require('$file_path$');\n", "module_alias",
215 ModuleAlias(file->name()), "file_path", file_path);
216 }
217
218 for (int i = 0; i < file->dependency_count(); i++) {
219 std::string file_path = GetRelativePath(
220 file->name(), GetJSMessageFilename(file->dependency(i)->name()));
221 out->Print("var $module_alias$ = require('$file_path$');\n", "module_alias",
222 ModuleAlias(file->dependency(i)->name()), "file_path",
223 file_path);
224 }
225 out->Print("\n");
226 }
227
PrintTransformers(const FileDescriptor * file,Printer * out,const Parameters & params)228 void PrintTransformers(const FileDescriptor* file, Printer* out,
229 const Parameters& params) {
230 map<std::string, const Descriptor*> messages = GetAllMessages(file);
231 for (std::map<std::string, const Descriptor*>::iterator it = messages.begin();
232 it != messages.end(); it++) {
233 PrintMessageTransformer(it->second, out, params);
234 }
235 out->Print("\n");
236 }
237
PrintServices(const FileDescriptor * file,Printer * out)238 void PrintServices(const FileDescriptor* file, Printer* out) {
239 for (int i = 0; i < file->service_count(); i++) {
240 PrintService(file->service(i), out);
241 }
242 }
243 } // namespace
244
GenerateFile(const FileDescriptor * file,const Parameters & params)245 std::string GenerateFile(const FileDescriptor* file, const Parameters& params) {
246 std::string output;
247 {
248 StringOutputStream output_stream(&output);
249 Printer out(&output_stream, '$');
250
251 if (file->service_count() == 0) {
252 return output;
253 }
254 out.Print("// GENERATED CODE -- DO NOT EDIT!\n\n");
255
256 std::string leading_comments = GetNodeComments(file, true);
257 if (!leading_comments.empty()) {
258 out.Print("// Original file comments:\n");
259 out.PrintRaw(leading_comments.c_str());
260 }
261
262 out.Print("'use strict';\n");
263
264 PrintImports(file, &out);
265
266 PrintTransformers(file, &out, params);
267
268 PrintServices(file, &out);
269
270 out.Print(GetNodeComments(file, false).c_str());
271 }
272 return output;
273 }
274
275 } // namespace grpc_node_generator
276