OLD | NEW |
(Empty) | |
| 1 /* |
| 2 * |
| 3 * Copyright 2015-2016, Google Inc. |
| 4 * All rights reserved. |
| 5 * |
| 6 * Redistribution and use in source and binary forms, with or without |
| 7 * modification, are permitted provided that the following conditions are |
| 8 * met: |
| 9 * |
| 10 * * Redistributions of source code must retain the above copyright |
| 11 * notice, this list of conditions and the following disclaimer. |
| 12 * * Redistributions in binary form must reproduce the above |
| 13 * copyright notice, this list of conditions and the following disclaimer |
| 14 * in the documentation and/or other materials provided with the |
| 15 * distribution. |
| 16 * * Neither the name of Google Inc. nor the names of its |
| 17 * contributors may be used to endorse or promote products derived from |
| 18 * this software without specific prior written permission. |
| 19 * |
| 20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
| 21 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
| 22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
| 23 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
| 24 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
| 25 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
| 26 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
| 27 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
| 28 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
| 29 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
| 30 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 31 * |
| 32 */ |
| 33 |
| 34 #include <algorithm> |
| 35 #include <cassert> |
| 36 #include <cctype> |
| 37 #include <cstring> |
| 38 #include <map> |
| 39 #include <memory> |
| 40 #include <ostream> |
| 41 #include <sstream> |
| 42 #include <tuple> |
| 43 #include <vector> |
| 44 |
| 45 #include "src/compiler/config.h" |
| 46 #include "src/compiler/generator_helpers.h" |
| 47 #include "src/compiler/python_generator.h" |
| 48 |
| 49 using grpc_generator::StringReplace; |
| 50 using grpc_generator::StripProto; |
| 51 using grpc::protobuf::Descriptor; |
| 52 using grpc::protobuf::FileDescriptor; |
| 53 using grpc::protobuf::MethodDescriptor; |
| 54 using grpc::protobuf::ServiceDescriptor; |
| 55 using grpc::protobuf::compiler::GeneratorContext; |
| 56 using grpc::protobuf::io::CodedOutputStream; |
| 57 using grpc::protobuf::io::Printer; |
| 58 using grpc::protobuf::io::StringOutputStream; |
| 59 using grpc::protobuf::io::ZeroCopyOutputStream; |
| 60 using std::initializer_list; |
| 61 using std::make_pair; |
| 62 using std::map; |
| 63 using std::pair; |
| 64 using std::replace; |
| 65 using std::vector; |
| 66 |
| 67 namespace grpc_python_generator { |
| 68 |
| 69 PythonGrpcGenerator::PythonGrpcGenerator(const GeneratorConfiguration& config) |
| 70 : config_(config) {} |
| 71 |
| 72 PythonGrpcGenerator::~PythonGrpcGenerator() {} |
| 73 |
| 74 bool PythonGrpcGenerator::Generate( |
| 75 const FileDescriptor* file, const grpc::string& parameter, |
| 76 GeneratorContext* context, grpc::string* error) const { |
| 77 // Get output file name. |
| 78 grpc::string file_name; |
| 79 static const int proto_suffix_length = strlen(".proto"); |
| 80 if (file->name().size() > static_cast<size_t>(proto_suffix_length) && |
| 81 file->name().find_last_of(".proto") == file->name().size() - 1) { |
| 82 file_name = file->name().substr( |
| 83 0, file->name().size() - proto_suffix_length) + "_pb2.py"; |
| 84 } else { |
| 85 *error = "Invalid proto file name. Proto file must end with .proto"; |
| 86 return false; |
| 87 } |
| 88 |
| 89 std::unique_ptr<ZeroCopyOutputStream> output( |
| 90 context->OpenForInsert(file_name, "module_scope")); |
| 91 CodedOutputStream coded_out(output.get()); |
| 92 bool success = false; |
| 93 grpc::string code = ""; |
| 94 tie(success, code) = grpc_python_generator::GetServices(file, config_); |
| 95 if (success) { |
| 96 coded_out.WriteRaw(code.data(), code.size()); |
| 97 return true; |
| 98 } else { |
| 99 return false; |
| 100 } |
| 101 } |
| 102 |
| 103 namespace { |
| 104 ////////////////////////////////// |
| 105 // BEGIN FORMATTING BOILERPLATE // |
| 106 ////////////////////////////////// |
| 107 |
| 108 // Converts an initializer list of the form { key0, value0, key1, value1, ... } |
| 109 // into a map of key* to value*. Is merely a readability helper for later code. |
| 110 map<grpc::string, grpc::string> ListToDict( |
| 111 const initializer_list<grpc::string>& values) { |
| 112 assert(values.size() % 2 == 0); |
| 113 map<grpc::string, grpc::string> value_map; |
| 114 auto value_iter = values.begin(); |
| 115 for (unsigned i = 0; i < values.size()/2; ++i) { |
| 116 grpc::string key = *value_iter; |
| 117 ++value_iter; |
| 118 grpc::string value = *value_iter; |
| 119 value_map[key] = value; |
| 120 ++value_iter; |
| 121 } |
| 122 return value_map; |
| 123 } |
| 124 |
| 125 // Provides RAII indentation handling. Use as: |
| 126 // { |
| 127 // IndentScope raii_my_indent_var_name_here(my_py_printer); |
| 128 // // constructor indented my_py_printer |
| 129 // ... |
| 130 // // destructor called at end of scope, un-indenting my_py_printer |
| 131 // } |
| 132 class IndentScope { |
| 133 public: |
| 134 explicit IndentScope(Printer* printer) : printer_(printer) { |
| 135 printer_->Indent(); |
| 136 } |
| 137 |
| 138 ~IndentScope() { |
| 139 printer_->Outdent(); |
| 140 } |
| 141 |
| 142 private: |
| 143 Printer* printer_; |
| 144 }; |
| 145 |
| 146 //////////////////////////////// |
| 147 // END FORMATTING BOILERPLATE // |
| 148 //////////////////////////////// |
| 149 |
| 150 // TODO(protobuf team): Export `ModuleName` from protobuf's |
| 151 // `src/google/protobuf/compiler/python/python_generator.cc` file. |
| 152 grpc::string ModuleName(const grpc::string& filename) { |
| 153 grpc::string basename = StripProto(filename); |
| 154 basename = StringReplace(basename, "-", "_"); |
| 155 basename = StringReplace(basename, "/", "."); |
| 156 return basename + "_pb2"; |
| 157 } |
| 158 |
| 159 bool GetModuleAndMessagePath(const Descriptor* type, |
| 160 pair<grpc::string, grpc::string>* out) { |
| 161 const Descriptor* path_elem_type = type; |
| 162 vector<const Descriptor*> message_path; |
| 163 do { |
| 164 message_path.push_back(path_elem_type); |
| 165 path_elem_type = path_elem_type->containing_type(); |
| 166 } while (path_elem_type); // implicit nullptr comparison; don't be explicit |
| 167 grpc::string file_name = type->file()->name(); |
| 168 static const int proto_suffix_length = strlen(".proto"); |
| 169 if (!(file_name.size() > static_cast<size_t>(proto_suffix_length) && |
| 170 file_name.find_last_of(".proto") == file_name.size() - 1)) { |
| 171 return false; |
| 172 } |
| 173 grpc::string module = ModuleName(file_name); |
| 174 grpc::string message_type; |
| 175 for (auto path_iter = message_path.rbegin(); |
| 176 path_iter != message_path.rend(); ++path_iter) { |
| 177 message_type += (*path_iter)->name() + "."; |
| 178 } |
| 179 // no pop_back prior to C++11 |
| 180 message_type.resize(message_type.size() - 1); |
| 181 *out = make_pair(module, message_type); |
| 182 return true; |
| 183 } |
| 184 |
| 185 bool PrintBetaServicer(const ServiceDescriptor* service, |
| 186 Printer* out) { |
| 187 grpc::string doc = "<fill me in later!>"; |
| 188 map<grpc::string, grpc::string> dict = ListToDict({ |
| 189 "Service", service->name(), |
| 190 "Documentation", doc, |
| 191 }); |
| 192 out->Print("\n"); |
| 193 out->Print(dict, "class Beta$Service$Servicer(object):\n"); |
| 194 { |
| 195 IndentScope raii_class_indent(out); |
| 196 out->Print(dict, "\"\"\"$Documentation$\"\"\"\n"); |
| 197 out->Print("__metaclass__ = abc.ABCMeta\n"); |
| 198 for (int i = 0; i < service->method_count(); ++i) { |
| 199 auto meth = service->method(i); |
| 200 grpc::string arg_name = meth->client_streaming() ? |
| 201 "request_iterator" : "request"; |
| 202 out->Print("@abc.abstractmethod\n"); |
| 203 out->Print("def $Method$(self, $ArgName$, context):\n", |
| 204 "Method", meth->name(), "ArgName", arg_name); |
| 205 { |
| 206 IndentScope raii_method_indent(out); |
| 207 out->Print("raise NotImplementedError()\n"); |
| 208 } |
| 209 } |
| 210 } |
| 211 return true; |
| 212 } |
| 213 |
| 214 bool PrintBetaStub(const ServiceDescriptor* service, |
| 215 Printer* out) { |
| 216 grpc::string doc = "The interface to which stubs will conform."; |
| 217 map<grpc::string, grpc::string> dict = ListToDict({ |
| 218 "Service", service->name(), |
| 219 "Documentation", doc, |
| 220 }); |
| 221 out->Print("\n"); |
| 222 out->Print(dict, "class Beta$Service$Stub(object):\n"); |
| 223 { |
| 224 IndentScope raii_class_indent(out); |
| 225 out->Print(dict, "\"\"\"$Documentation$\"\"\"\n"); |
| 226 out->Print("__metaclass__ = abc.ABCMeta\n"); |
| 227 for (int i = 0; i < service->method_count(); ++i) { |
| 228 const MethodDescriptor* meth = service->method(i); |
| 229 grpc::string arg_name = meth->client_streaming() ? |
| 230 "request_iterator" : "request"; |
| 231 auto methdict = ListToDict({"Method", meth->name(), "ArgName", arg_name}); |
| 232 out->Print("@abc.abstractmethod\n"); |
| 233 out->Print(methdict, "def $Method$(self, $ArgName$, timeout):\n"); |
| 234 { |
| 235 IndentScope raii_method_indent(out); |
| 236 out->Print("raise NotImplementedError()\n"); |
| 237 } |
| 238 if (!meth->server_streaming()) { |
| 239 out->Print(methdict, "$Method$.future = None\n"); |
| 240 } |
| 241 } |
| 242 } |
| 243 return true; |
| 244 } |
| 245 |
| 246 bool PrintBetaServerFactory(const grpc::string& package_qualified_service_name, |
| 247 const ServiceDescriptor* service, Printer* out) { |
| 248 out->Print("\n"); |
| 249 out->Print("def beta_create_$Service$_server(servicer, pool=None, " |
| 250 "pool_size=None, default_timeout=None, maximum_timeout=None):\n", |
| 251 "Service", service->name()); |
| 252 { |
| 253 IndentScope raii_create_server_indent(out); |
| 254 map<grpc::string, grpc::string> method_implementation_constructors; |
| 255 map<grpc::string, pair<grpc::string, grpc::string>> |
| 256 input_message_modules_and_classes; |
| 257 map<grpc::string, pair<grpc::string, grpc::string>> |
| 258 output_message_modules_and_classes; |
| 259 for (int i = 0; i < service->method_count(); ++i) { |
| 260 const MethodDescriptor* method = service->method(i); |
| 261 const grpc::string method_implementation_constructor = |
| 262 grpc::string(method->client_streaming() ? "stream_" : "unary_") + |
| 263 grpc::string(method->server_streaming() ? "stream_" : "unary_") + |
| 264 "inline"; |
| 265 pair<grpc::string, grpc::string> input_message_module_and_class; |
| 266 if (!GetModuleAndMessagePath(method->input_type(), |
| 267 &input_message_module_and_class)) { |
| 268 return false; |
| 269 } |
| 270 pair<grpc::string, grpc::string> output_message_module_and_class; |
| 271 if (!GetModuleAndMessagePath(method->output_type(), |
| 272 &output_message_module_and_class)) { |
| 273 return false; |
| 274 } |
| 275 // Import the modules that define the messages used in RPCs. |
| 276 out->Print("import $Module$\n", "Module", |
| 277 input_message_module_and_class.first); |
| 278 out->Print("import $Module$\n", "Module", |
| 279 output_message_module_and_class.first); |
| 280 method_implementation_constructors.insert( |
| 281 make_pair(method->name(), method_implementation_constructor)); |
| 282 input_message_modules_and_classes.insert( |
| 283 make_pair(method->name(), input_message_module_and_class)); |
| 284 output_message_modules_and_classes.insert( |
| 285 make_pair(method->name(), output_message_module_and_class)); |
| 286 } |
| 287 out->Print("request_deserializers = {\n"); |
| 288 for (auto name_and_input_module_class_pair = |
| 289 input_message_modules_and_classes.begin(); |
| 290 name_and_input_module_class_pair != |
| 291 input_message_modules_and_classes.end(); |
| 292 name_and_input_module_class_pair++) { |
| 293 IndentScope raii_indent(out); |
| 294 out->Print("(\'$PackageQualifiedServiceName$\', \'$MethodName$\'): " |
| 295 "$InputTypeModule$.$InputTypeClass$.FromString,\n", |
| 296 "PackageQualifiedServiceName", package_qualified_service_name, |
| 297 "MethodName", name_and_input_module_class_pair->first, |
| 298 "InputTypeModule", |
| 299 name_and_input_module_class_pair->second.first, |
| 300 "InputTypeClass", |
| 301 name_and_input_module_class_pair->second.second); |
| 302 } |
| 303 out->Print("}\n"); |
| 304 out->Print("response_serializers = {\n"); |
| 305 for (auto name_and_output_module_class_pair = |
| 306 output_message_modules_and_classes.begin(); |
| 307 name_and_output_module_class_pair != |
| 308 output_message_modules_and_classes.end(); |
| 309 name_and_output_module_class_pair++) { |
| 310 IndentScope raii_indent(out); |
| 311 out->Print("(\'$PackageQualifiedServiceName$\', \'$MethodName$\'): " |
| 312 "$OutputTypeModule$.$OutputTypeClass$.SerializeToString,\n", |
| 313 "PackageQualifiedServiceName", package_qualified_service_name, |
| 314 "MethodName", name_and_output_module_class_pair->first, |
| 315 "OutputTypeModule", |
| 316 name_and_output_module_class_pair->second.first, |
| 317 "OutputTypeClass", |
| 318 name_and_output_module_class_pair->second.second); |
| 319 } |
| 320 out->Print("}\n"); |
| 321 out->Print("method_implementations = {\n"); |
| 322 for (auto name_and_implementation_constructor = |
| 323 method_implementation_constructors.begin(); |
| 324 name_and_implementation_constructor != |
| 325 method_implementation_constructors.end(); |
| 326 name_and_implementation_constructor++) { |
| 327 IndentScope raii_descriptions_indent(out); |
| 328 const grpc::string method_name = |
| 329 name_and_implementation_constructor->first; |
| 330 out->Print("(\'$PackageQualifiedServiceName$\', \'$Method$\'): " |
| 331 "face_utilities.$Constructor$(servicer.$Method$),\n", |
| 332 "PackageQualifiedServiceName", package_qualified_service_name, |
| 333 "Method", name_and_implementation_constructor->first, |
| 334 "Constructor", name_and_implementation_constructor->second); |
| 335 } |
| 336 out->Print("}\n"); |
| 337 out->Print("server_options = beta_implementations.server_options(" |
| 338 "request_deserializers=request_deserializers, " |
| 339 "response_serializers=response_serializers, " |
| 340 "thread_pool=pool, thread_pool_size=pool_size, " |
| 341 "default_timeout=default_timeout, " |
| 342 "maximum_timeout=maximum_timeout)\n"); |
| 343 out->Print("return beta_implementations.server(method_implementations, " |
| 344 "options=server_options)\n"); |
| 345 } |
| 346 return true; |
| 347 } |
| 348 |
| 349 bool PrintBetaStubFactory(const grpc::string& package_qualified_service_name, |
| 350 const ServiceDescriptor* service, Printer* out) { |
| 351 map<grpc::string, grpc::string> dict = ListToDict({ |
| 352 "Service", service->name(), |
| 353 }); |
| 354 out->Print("\n"); |
| 355 out->Print(dict, "def beta_create_$Service$_stub(channel, host=None," |
| 356 " metadata_transformer=None, pool=None, pool_size=None):\n"); |
| 357 { |
| 358 IndentScope raii_create_server_indent(out); |
| 359 map<grpc::string, grpc::string> method_cardinalities; |
| 360 map<grpc::string, pair<grpc::string, grpc::string>> |
| 361 input_message_modules_and_classes; |
| 362 map<grpc::string, pair<grpc::string, grpc::string>> |
| 363 output_message_modules_and_classes; |
| 364 for (int i = 0; i < service->method_count(); ++i) { |
| 365 const MethodDescriptor* method = service->method(i); |
| 366 const grpc::string method_cardinality = |
| 367 grpc::string(method->client_streaming() ? "STREAM" : "UNARY") + |
| 368 "_" + |
| 369 grpc::string(method->server_streaming() ? "STREAM" : "UNARY"); |
| 370 pair<grpc::string, grpc::string> input_message_module_and_class; |
| 371 if (!GetModuleAndMessagePath(method->input_type(), |
| 372 &input_message_module_and_class)) { |
| 373 return false; |
| 374 } |
| 375 pair<grpc::string, grpc::string> output_message_module_and_class; |
| 376 if (!GetModuleAndMessagePath(method->output_type(), |
| 377 &output_message_module_and_class)) { |
| 378 return false; |
| 379 } |
| 380 // Import the modules that define the messages used in RPCs. |
| 381 out->Print("import $Module$\n", "Module", |
| 382 input_message_module_and_class.first); |
| 383 out->Print("import $Module$\n", "Module", |
| 384 output_message_module_and_class.first); |
| 385 method_cardinalities.insert( |
| 386 make_pair(method->name(), method_cardinality)); |
| 387 input_message_modules_and_classes.insert( |
| 388 make_pair(method->name(), input_message_module_and_class)); |
| 389 output_message_modules_and_classes.insert( |
| 390 make_pair(method->name(), output_message_module_and_class)); |
| 391 } |
| 392 out->Print("request_serializers = {\n"); |
| 393 for (auto name_and_input_module_class_pair = |
| 394 input_message_modules_and_classes.begin(); |
| 395 name_and_input_module_class_pair != |
| 396 input_message_modules_and_classes.end(); |
| 397 name_and_input_module_class_pair++) { |
| 398 IndentScope raii_indent(out); |
| 399 out->Print("(\'$PackageQualifiedServiceName$\', \'$MethodName$\'): " |
| 400 "$InputTypeModule$.$InputTypeClass$.SerializeToString,\n", |
| 401 "PackageQualifiedServiceName", package_qualified_service_name, |
| 402 "MethodName", name_and_input_module_class_pair->first, |
| 403 "InputTypeModule", |
| 404 name_and_input_module_class_pair->second.first, |
| 405 "InputTypeClass", |
| 406 name_and_input_module_class_pair->second.second); |
| 407 } |
| 408 out->Print("}\n"); |
| 409 out->Print("response_deserializers = {\n"); |
| 410 for (auto name_and_output_module_class_pair = |
| 411 output_message_modules_and_classes.begin(); |
| 412 name_and_output_module_class_pair != |
| 413 output_message_modules_and_classes.end(); |
| 414 name_and_output_module_class_pair++) { |
| 415 IndentScope raii_indent(out); |
| 416 out->Print("(\'$PackageQualifiedServiceName$\', \'$MethodName$\'): " |
| 417 "$OutputTypeModule$.$OutputTypeClass$.FromString,\n", |
| 418 "PackageQualifiedServiceName", package_qualified_service_name, |
| 419 "MethodName", name_and_output_module_class_pair->first, |
| 420 "OutputTypeModule", |
| 421 name_and_output_module_class_pair->second.first, |
| 422 "OutputTypeClass", |
| 423 name_and_output_module_class_pair->second.second); |
| 424 } |
| 425 out->Print("}\n"); |
| 426 out->Print("cardinalities = {\n"); |
| 427 for (auto name_and_cardinality = method_cardinalities.begin(); |
| 428 name_and_cardinality != method_cardinalities.end(); |
| 429 name_and_cardinality++) { |
| 430 IndentScope raii_descriptions_indent(out); |
| 431 out->Print("\'$Method$\': cardinality.Cardinality.$Cardinality$,\n", |
| 432 "Method", name_and_cardinality->first, |
| 433 "Cardinality", name_and_cardinality->second); |
| 434 } |
| 435 out->Print("}\n"); |
| 436 out->Print("stub_options = beta_implementations.stub_options(" |
| 437 "host=host, metadata_transformer=metadata_transformer, " |
| 438 "request_serializers=request_serializers, " |
| 439 "response_deserializers=response_deserializers, " |
| 440 "thread_pool=pool, thread_pool_size=pool_size)\n"); |
| 441 out->Print( |
| 442 "return beta_implementations.dynamic_stub(channel, \'$PackageQualifiedSe
rviceName$\', " |
| 443 "cardinalities, options=stub_options)\n", |
| 444 "PackageQualifiedServiceName", package_qualified_service_name); |
| 445 } |
| 446 return true; |
| 447 } |
| 448 |
| 449 bool PrintPreamble(const FileDescriptor* file, |
| 450 const GeneratorConfiguration& config, Printer* out) { |
| 451 out->Print("import abc\n"); |
| 452 out->Print("from $Package$ import implementations as beta_implementations\n", |
| 453 "Package", config.beta_package_root); |
| 454 out->Print("from grpc.framework.common import cardinality\n"); |
| 455 out->Print("from grpc.framework.interfaces.face import utilities as face_utili
ties\n"); |
| 456 return true; |
| 457 } |
| 458 |
| 459 } // namespace |
| 460 |
| 461 pair<bool, grpc::string> GetServices(const FileDescriptor* file, |
| 462 const GeneratorConfiguration& config) { |
| 463 grpc::string output; |
| 464 { |
| 465 // Scope the output stream so it closes and finalizes output to the string. |
| 466 StringOutputStream output_stream(&output); |
| 467 Printer out(&output_stream, '$'); |
| 468 if (!PrintPreamble(file, config, &out)) { |
| 469 return make_pair(false, ""); |
| 470 } |
| 471 auto package = file->package(); |
| 472 if (!package.empty()) { |
| 473 package = package.append("."); |
| 474 } |
| 475 for (int i = 0; i < file->service_count(); ++i) { |
| 476 auto service = file->service(i); |
| 477 auto package_qualified_service_name = package + service->name(); |
| 478 if (!(PrintBetaServicer(service, &out) && |
| 479 PrintBetaStub(service, &out) && |
| 480 PrintBetaServerFactory(package_qualified_service_name, service, &out
) && |
| 481 PrintBetaStubFactory(package_qualified_service_name, service, &out))
) { |
| 482 return make_pair(false, ""); |
| 483 } |
| 484 } |
| 485 } |
| 486 return make_pair(true, std::move(output)); |
| 487 } |
| 488 |
| 489 } // namespace grpc_python_generator |
OLD | NEW |