blob: 15cda474ccd37a423268dc3e381d99b74548e851 [file] [log] [blame]
Masood Malekghassemif8e297a2015-02-19 15:39:32 -08001/*
2 *
Craig Tiller6169d5f2016-03-31 07:46:18 -07003 * Copyright 2015, Google Inc.
Masood Malekghassemif8e297a2015-02-19 15:39:32 -08004 * 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
Masood Malekghassemi40e8cbd2015-02-26 08:39:50 -080034#include <algorithm>
Masood Malekghassemif8e297a2015-02-19 15:39:32 -080035#include <cassert>
36#include <cctype>
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -080037#include <cstring>
Masood Malekghassemif8e297a2015-02-19 15:39:32 -080038#include <map>
Masood Malekghassemi3bb52152015-03-17 21:52:52 -070039#include <memory>
Masood Malekghassemif8e297a2015-02-19 15:39:32 -080040#include <ostream>
41#include <sstream>
Masood Malekghassemi3bb52152015-03-17 21:52:52 -070042#include <tuple>
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -080043#include <vector>
Masood Malekghassemif8e297a2015-02-19 15:39:32 -080044
Masood Malekghassemi65c803b2015-03-20 06:48:47 -070045#include "src/compiler/config.h"
Nicolas "Pixel" Noble93fa0982015-02-27 21:50:58 +010046#include "src/compiler/generator_helpers.h"
Masood Malekghassemif8e297a2015-02-19 15:39:32 -080047#include "src/compiler/python_generator.h"
Masood Malekghassemif8e297a2015-02-19 15:39:32 -080048
Nicolas "Pixel" Noble93fa0982015-02-27 21:50:58 +010049using grpc_generator::StringReplace;
50using grpc_generator::StripProto;
Masood Malekghassemi65c803b2015-03-20 06:48:47 -070051using grpc::protobuf::Descriptor;
52using grpc::protobuf::FileDescriptor;
53using grpc::protobuf::MethodDescriptor;
54using grpc::protobuf::ServiceDescriptor;
55using grpc::protobuf::compiler::GeneratorContext;
56using grpc::protobuf::io::CodedOutputStream;
57using grpc::protobuf::io::Printer;
58using grpc::protobuf::io::StringOutputStream;
59using grpc::protobuf::io::ZeroCopyOutputStream;
Masood Malekghassemif8e297a2015-02-19 15:39:32 -080060using std::initializer_list;
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -080061using std::make_pair;
Masood Malekghassemif8e297a2015-02-19 15:39:32 -080062using std::map;
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -080063using std::pair;
Masood Malekghassemi40e8cbd2015-02-26 08:39:50 -080064using std::replace;
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -080065using std::vector;
Masood Malekghassemif8e297a2015-02-19 15:39:32 -080066
67namespace grpc_python_generator {
Masood Malekghassemi3bb52152015-03-17 21:52:52 -070068
69PythonGrpcGenerator::PythonGrpcGenerator(const GeneratorConfiguration& config)
70 : config_(config) {}
71
72PythonGrpcGenerator::~PythonGrpcGenerator() {}
73
74bool PythonGrpcGenerator::Generate(
Masood Malekghassemi65c803b2015-03-20 06:48:47 -070075 const FileDescriptor* file, const grpc::string& parameter,
76 GeneratorContext* context, grpc::string* error) const {
Masood Malekghassemi3bb52152015-03-17 21:52:52 -070077 // Get output file name.
Masood Malekghassemi65c803b2015-03-20 06:48:47 -070078 grpc::string file_name;
Masood Malekghassemi3bb52152015-03-17 21:52:52 -070079 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;
Masood Malekghassemi65c803b2015-03-20 06:48:47 -070093 grpc::string code = "";
Masood Malekghassemi3bb52152015-03-17 21:52:52 -070094 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
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800103namespace {
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.
Masood Malekghassemi65c803b2015-03-20 06:48:47 -0700110map<grpc::string, grpc::string> ListToDict(
111 const initializer_list<grpc::string>& values) {
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800112 assert(values.size() % 2 == 0);
Masood Malekghassemi65c803b2015-03-20 06:48:47 -0700113 map<grpc::string, grpc::string> value_map;
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800114 auto value_iter = values.begin();
115 for (unsigned i = 0; i < values.size()/2; ++i) {
Masood Malekghassemi65c803b2015-03-20 06:48:47 -0700116 grpc::string key = *value_iter;
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800117 ++value_iter;
Masood Malekghassemi65c803b2015-03-20 06:48:47 -0700118 grpc::string value = *value_iter;
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800119 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// }
132class 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
Ken Paysonbe187b02016-05-06 15:32:58 -0700150// TODO(https://github.com/google/protobuf/issues/888):
151// Export `ModuleName` from protobuf's
Masood Malekghassemi40e8cbd2015-02-26 08:39:50 -0800152// `src/google/protobuf/compiler/python/python_generator.cc` file.
Masood Malekghassemi65c803b2015-03-20 06:48:47 -0700153grpc::string ModuleName(const grpc::string& filename) {
154 grpc::string basename = StripProto(filename);
Nicolas "Pixel" Noble93fa0982015-02-27 21:50:58 +0100155 basename = StringReplace(basename, "-", "_");
156 basename = StringReplace(basename, "/", ".");
Masood Malekghassemi40e8cbd2015-02-26 08:39:50 -0800157 return basename + "_pb2";
158}
159
Ken Paysonbe187b02016-05-06 15:32:58 -0700160// TODO(https://github.com/google/protobuf/issues/888):
161// Export `ModuleAlias` from protobuf's
162// `src/google/protobuf/compiler/python/python_generator.cc` file.
163grpc::string ModuleAlias(const grpc::string& filename) {
164 grpc::string module_name = ModuleName(filename);
165 // We can't have dots in the module name, so we replace each with _dot_.
166 // But that could lead to a collision between a.b and a_dot_b, so we also
167 // duplicate each underscore.
168 module_name = StringReplace(module_name, "_", "__");
169 module_name = StringReplace(module_name, ".", "_dot_");
170 return module_name;
171}
172
173
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800174bool GetModuleAndMessagePath(const Descriptor* type,
Ken Paysonbe187b02016-05-06 15:32:58 -0700175 const ServiceDescriptor* service,
176 grpc::string* out) {
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800177 const Descriptor* path_elem_type = type;
178 vector<const Descriptor*> message_path;
179 do {
180 message_path.push_back(path_elem_type);
181 path_elem_type = path_elem_type->containing_type();
Vijay Paic0897432015-07-27 22:18:13 +0000182 } while (path_elem_type); // implicit nullptr comparison; don't be explicit
Masood Malekghassemi65c803b2015-03-20 06:48:47 -0700183 grpc::string file_name = type->file()->name();
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800184 static const int proto_suffix_length = strlen(".proto");
185 if (!(file_name.size() > static_cast<size_t>(proto_suffix_length) &&
186 file_name.find_last_of(".proto") == file_name.size() - 1)) {
187 return false;
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800188 }
Ken Paysonbe187b02016-05-06 15:32:58 -0700189 grpc::string service_file_name = service->file()->name();
190 grpc::string module = service_file_name == file_name ?
191 "" : ModuleAlias(file_name) + ".";
Masood Malekghassemi65c803b2015-03-20 06:48:47 -0700192 grpc::string message_type;
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800193 for (auto path_iter = message_path.rbegin();
194 path_iter != message_path.rend(); ++path_iter) {
195 message_type += (*path_iter)->name() + ".";
196 }
Craig Tillercf133f42015-02-26 14:05:56 -0800197 // no pop_back prior to C++11
198 message_type.resize(message_type.size() - 1);
Ken Paysonbe187b02016-05-06 15:32:58 -0700199 *out = module + message_type;
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800200 return true;
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800201}
202
yang-gb0de7162016-05-03 15:48:19 -0700203// Get all comments (leading, leading_detached, trailing) and print them as a
204// docstring. Any leading space of a line will be removed, but the line wrapping
205// will not be changed.
206template <typename DescriptorType>
207static void PrintAllComments(const DescriptorType* desc, Printer* printer) {
208 std::vector<grpc::string> comments;
209 grpc_generator::GetComment(desc, grpc_generator::COMMENTTYPE_LEADING_DETACHED,
210 &comments);
211 grpc_generator::GetComment(desc, grpc_generator::COMMENTTYPE_LEADING,
212 &comments);
213 grpc_generator::GetComment(desc, grpc_generator::COMMENTTYPE_TRAILING,
214 &comments);
215 if (comments.empty()) {
216 return;
217 }
218 printer->Print("\"\"\"");
219 for (auto it = comments.begin(); it != comments.end(); ++it) {
220 size_t start_pos = it->find_first_not_of(' ');
221 if (start_pos != grpc::string::npos) {
222 printer->Print(it->c_str() + start_pos);
223 }
224 printer->Print("\n");
225 }
226 printer->Print("\"\"\"\n");
227}
228
Nathaniel Manistacd9ec0e2015-08-31 07:49:45 +0000229bool PrintBetaServicer(const ServiceDescriptor* service,
230 Printer* out) {
Ken Paysonbe187b02016-05-06 15:32:58 -0700231 out->Print("\n\n");
yang-gb0de7162016-05-03 15:48:19 -0700232 out->Print("class Beta$Service$Servicer(object):\n", "Service",
233 service->name());
Nathaniel Manistacd9ec0e2015-08-31 07:49:45 +0000234 {
235 IndentScope raii_class_indent(out);
yang-gb0de7162016-05-03 15:48:19 -0700236 PrintAllComments(service, out);
Nathaniel Manistacd9ec0e2015-08-31 07:49:45 +0000237 for (int i = 0; i < service->method_count(); ++i) {
238 auto meth = service->method(i);
239 grpc::string arg_name = meth->client_streaming() ?
240 "request_iterator" : "request";
Nathaniel Manistacd9ec0e2015-08-31 07:49:45 +0000241 out->Print("def $Method$(self, $ArgName$, context):\n",
242 "Method", meth->name(), "ArgName", arg_name);
243 {
244 IndentScope raii_method_indent(out);
yang-gb0de7162016-05-03 15:48:19 -0700245 PrintAllComments(meth, out);
Masood Malekghassemi832ae812016-04-27 18:38:54 -0700246 out->Print("context.code(beta_interfaces.StatusCode.UNIMPLEMENTED)\n");
Nathaniel Manistacd9ec0e2015-08-31 07:49:45 +0000247 }
248 }
249 }
250 return true;
251}
252
253bool PrintBetaStub(const ServiceDescriptor* service,
254 Printer* out) {
Ken Paysonbe187b02016-05-06 15:32:58 -0700255 out->Print("\n\n");
yang-gb0de7162016-05-03 15:48:19 -0700256 out->Print("class Beta$Service$Stub(object):\n", "Service", service->name());
Nathaniel Manistacd9ec0e2015-08-31 07:49:45 +0000257 {
258 IndentScope raii_class_indent(out);
yang-gb0de7162016-05-03 15:48:19 -0700259 PrintAllComments(service, out);
Nathaniel Manistacd9ec0e2015-08-31 07:49:45 +0000260 for (int i = 0; i < service->method_count(); ++i) {
261 const MethodDescriptor* meth = service->method(i);
262 grpc::string arg_name = meth->client_streaming() ?
263 "request_iterator" : "request";
264 auto methdict = ListToDict({"Method", meth->name(), "ArgName", arg_name});
Ken Paysonbe187b02016-05-06 15:32:58 -0700265 out->Print(methdict, "def $Method$(self, $ArgName$, timeout, metadata=None, with_call=False, protocol_options=None):\n");
Nathaniel Manistacd9ec0e2015-08-31 07:49:45 +0000266 {
267 IndentScope raii_method_indent(out);
yang-gb0de7162016-05-03 15:48:19 -0700268 PrintAllComments(meth, out);
Nathaniel Manistacd9ec0e2015-08-31 07:49:45 +0000269 out->Print("raise NotImplementedError()\n");
270 }
271 if (!meth->server_streaming()) {
272 out->Print(methdict, "$Method$.future = None\n");
273 }
274 }
275 }
276 return true;
277}
278
279bool PrintBetaServerFactory(const grpc::string& package_qualified_service_name,
280 const ServiceDescriptor* service, Printer* out) {
Ken Paysonbe187b02016-05-06 15:32:58 -0700281 out->Print("\n\n");
Nathaniel Manistacd9ec0e2015-08-31 07:49:45 +0000282 out->Print("def beta_create_$Service$_server(servicer, pool=None, "
283 "pool_size=None, default_timeout=None, maximum_timeout=None):\n",
284 "Service", service->name());
285 {
286 IndentScope raii_create_server_indent(out);
287 map<grpc::string, grpc::string> method_implementation_constructors;
Ken Paysonbe187b02016-05-06 15:32:58 -0700288 map<grpc::string, grpc::string> input_message_modules_and_classes;
289 map<grpc::string, grpc::string> output_message_modules_and_classes;
Nathaniel Manistacd9ec0e2015-08-31 07:49:45 +0000290 for (int i = 0; i < service->method_count(); ++i) {
291 const MethodDescriptor* method = service->method(i);
292 const grpc::string method_implementation_constructor =
293 grpc::string(method->client_streaming() ? "stream_" : "unary_") +
294 grpc::string(method->server_streaming() ? "stream_" : "unary_") +
295 "inline";
Ken Paysonbe187b02016-05-06 15:32:58 -0700296 grpc::string input_message_module_and_class;
297 if (!GetModuleAndMessagePath(method->input_type(), service,
Nathaniel Manistacd9ec0e2015-08-31 07:49:45 +0000298 &input_message_module_and_class)) {
299 return false;
300 }
Ken Paysonbe187b02016-05-06 15:32:58 -0700301 grpc::string output_message_module_and_class;
302 if (!GetModuleAndMessagePath(method->output_type(), service,
Nathaniel Manistacd9ec0e2015-08-31 07:49:45 +0000303 &output_message_module_and_class)) {
304 return false;
305 }
Nathaniel Manistacd9ec0e2015-08-31 07:49:45 +0000306 method_implementation_constructors.insert(
307 make_pair(method->name(), method_implementation_constructor));
308 input_message_modules_and_classes.insert(
309 make_pair(method->name(), input_message_module_and_class));
310 output_message_modules_and_classes.insert(
311 make_pair(method->name(), output_message_module_and_class));
312 }
313 out->Print("request_deserializers = {\n");
314 for (auto name_and_input_module_class_pair =
315 input_message_modules_and_classes.begin();
316 name_and_input_module_class_pair !=
317 input_message_modules_and_classes.end();
318 name_and_input_module_class_pair++) {
319 IndentScope raii_indent(out);
320 out->Print("(\'$PackageQualifiedServiceName$\', \'$MethodName$\'): "
Ken Paysonbe187b02016-05-06 15:32:58 -0700321 "$InputTypeModuleAndClass$.FromString,\n",
Nathaniel Manistacd9ec0e2015-08-31 07:49:45 +0000322 "PackageQualifiedServiceName", package_qualified_service_name,
323 "MethodName", name_and_input_module_class_pair->first,
Ken Paysonbe187b02016-05-06 15:32:58 -0700324 "InputTypeModuleAndClass",
325 name_and_input_module_class_pair->second);
Nathaniel Manistacd9ec0e2015-08-31 07:49:45 +0000326 }
327 out->Print("}\n");
328 out->Print("response_serializers = {\n");
329 for (auto name_and_output_module_class_pair =
330 output_message_modules_and_classes.begin();
331 name_and_output_module_class_pair !=
332 output_message_modules_and_classes.end();
333 name_and_output_module_class_pair++) {
334 IndentScope raii_indent(out);
335 out->Print("(\'$PackageQualifiedServiceName$\', \'$MethodName$\'): "
Ken Paysonbe187b02016-05-06 15:32:58 -0700336 "$OutputTypeModuleAndClass$.SerializeToString,\n",
Nathaniel Manistacd9ec0e2015-08-31 07:49:45 +0000337 "PackageQualifiedServiceName", package_qualified_service_name,
338 "MethodName", name_and_output_module_class_pair->first,
Ken Paysonbe187b02016-05-06 15:32:58 -0700339 "OutputTypeModuleAndClass",
340 name_and_output_module_class_pair->second);
Nathaniel Manistacd9ec0e2015-08-31 07:49:45 +0000341 }
342 out->Print("}\n");
343 out->Print("method_implementations = {\n");
344 for (auto name_and_implementation_constructor =
Nathaniel Manista45479402016-06-13 20:14:18 +0000345 method_implementation_constructors.begin();
Nathaniel Manistacd9ec0e2015-08-31 07:49:45 +0000346 name_and_implementation_constructor !=
347 method_implementation_constructors.end();
348 name_and_implementation_constructor++) {
349 IndentScope raii_descriptions_indent(out);
350 const grpc::string method_name =
351 name_and_implementation_constructor->first;
352 out->Print("(\'$PackageQualifiedServiceName$\', \'$Method$\'): "
353 "face_utilities.$Constructor$(servicer.$Method$),\n",
354 "PackageQualifiedServiceName", package_qualified_service_name,
355 "Method", name_and_implementation_constructor->first,
356 "Constructor", name_and_implementation_constructor->second);
357 }
358 out->Print("}\n");
Nathaniel Manistaf65d3c12015-09-05 03:55:19 +0000359 out->Print("server_options = beta_implementations.server_options("
Nathaniel Manistacd9ec0e2015-08-31 07:49:45 +0000360 "request_deserializers=request_deserializers, "
361 "response_serializers=response_serializers, "
362 "thread_pool=pool, thread_pool_size=pool_size, "
363 "default_timeout=default_timeout, "
364 "maximum_timeout=maximum_timeout)\n");
Nathaniel Manistaf65d3c12015-09-05 03:55:19 +0000365 out->Print("return beta_implementations.server(method_implementations, "
Nathaniel Manistacd9ec0e2015-08-31 07:49:45 +0000366 "options=server_options)\n");
367 }
368 return true;
369}
370
371bool PrintBetaStubFactory(const grpc::string& package_qualified_service_name,
372 const ServiceDescriptor* service, Printer* out) {
373 map<grpc::string, grpc::string> dict = ListToDict({
374 "Service", service->name(),
375 });
Ken Paysonbe187b02016-05-06 15:32:58 -0700376 out->Print("\n\n");
Nathaniel Manistacd9ec0e2015-08-31 07:49:45 +0000377 out->Print(dict, "def beta_create_$Service$_stub(channel, host=None,"
378 " metadata_transformer=None, pool=None, pool_size=None):\n");
379 {
380 IndentScope raii_create_server_indent(out);
381 map<grpc::string, grpc::string> method_cardinalities;
Ken Paysonbe187b02016-05-06 15:32:58 -0700382 map<grpc::string, grpc::string> input_message_modules_and_classes;
383 map<grpc::string, grpc::string> output_message_modules_and_classes;
Nathaniel Manistacd9ec0e2015-08-31 07:49:45 +0000384 for (int i = 0; i < service->method_count(); ++i) {
385 const MethodDescriptor* method = service->method(i);
386 const grpc::string method_cardinality =
387 grpc::string(method->client_streaming() ? "STREAM" : "UNARY") +
388 "_" +
Ken Paysonbe187b02016-05-06 15:32:58 -0700389 grpc::string(method->server_streaming() ? "STREAM" : "UNARY");
390 grpc::string input_message_module_and_class;
391 if (!GetModuleAndMessagePath(method->input_type(), service,
Nathaniel Manistacd9ec0e2015-08-31 07:49:45 +0000392 &input_message_module_and_class)) {
393 return false;
394 }
Ken Paysonbe187b02016-05-06 15:32:58 -0700395 grpc::string output_message_module_and_class;
396 if (!GetModuleAndMessagePath(method->output_type(), service,
Nathaniel Manistacd9ec0e2015-08-31 07:49:45 +0000397 &output_message_module_and_class)) {
398 return false;
399 }
Nathaniel Manistacd9ec0e2015-08-31 07:49:45 +0000400 method_cardinalities.insert(
401 make_pair(method->name(), method_cardinality));
402 input_message_modules_and_classes.insert(
403 make_pair(method->name(), input_message_module_and_class));
404 output_message_modules_and_classes.insert(
405 make_pair(method->name(), output_message_module_and_class));
406 }
407 out->Print("request_serializers = {\n");
408 for (auto name_and_input_module_class_pair =
409 input_message_modules_and_classes.begin();
410 name_and_input_module_class_pair !=
411 input_message_modules_and_classes.end();
412 name_and_input_module_class_pair++) {
413 IndentScope raii_indent(out);
414 out->Print("(\'$PackageQualifiedServiceName$\', \'$MethodName$\'): "
Ken Paysonbe187b02016-05-06 15:32:58 -0700415 "$InputTypeModuleAndClass$.SerializeToString,\n",
Nathaniel Manistacd9ec0e2015-08-31 07:49:45 +0000416 "PackageQualifiedServiceName", package_qualified_service_name,
417 "MethodName", name_and_input_module_class_pair->first,
Ken Paysonbe187b02016-05-06 15:32:58 -0700418 "InputTypeModuleAndClass",
419 name_and_input_module_class_pair->second);
Nathaniel Manistacd9ec0e2015-08-31 07:49:45 +0000420 }
421 out->Print("}\n");
422 out->Print("response_deserializers = {\n");
423 for (auto name_and_output_module_class_pair =
424 output_message_modules_and_classes.begin();
425 name_and_output_module_class_pair !=
426 output_message_modules_and_classes.end();
427 name_and_output_module_class_pair++) {
428 IndentScope raii_indent(out);
429 out->Print("(\'$PackageQualifiedServiceName$\', \'$MethodName$\'): "
Ken Paysonbe187b02016-05-06 15:32:58 -0700430 "$OutputTypeModuleAndClass$.FromString,\n",
Nathaniel Manistacd9ec0e2015-08-31 07:49:45 +0000431 "PackageQualifiedServiceName", package_qualified_service_name,
432 "MethodName", name_and_output_module_class_pair->first,
Ken Paysonbe187b02016-05-06 15:32:58 -0700433 "OutputTypeModuleAndClass",
434 name_and_output_module_class_pair->second);
Nathaniel Manistacd9ec0e2015-08-31 07:49:45 +0000435 }
436 out->Print("}\n");
437 out->Print("cardinalities = {\n");
438 for (auto name_and_cardinality = method_cardinalities.begin();
439 name_and_cardinality != method_cardinalities.end();
440 name_and_cardinality++) {
441 IndentScope raii_descriptions_indent(out);
442 out->Print("\'$Method$\': cardinality.Cardinality.$Cardinality$,\n",
443 "Method", name_and_cardinality->first,
444 "Cardinality", name_and_cardinality->second);
445 }
446 out->Print("}\n");
Nathaniel Manistaf65d3c12015-09-05 03:55:19 +0000447 out->Print("stub_options = beta_implementations.stub_options("
Nathaniel Manistacd9ec0e2015-08-31 07:49:45 +0000448 "host=host, metadata_transformer=metadata_transformer, "
449 "request_serializers=request_serializers, "
450 "response_deserializers=response_deserializers, "
451 "thread_pool=pool, thread_pool_size=pool_size)\n");
452 out->Print(
Nathaniel Manistaf65d3c12015-09-05 03:55:19 +0000453 "return beta_implementations.dynamic_stub(channel, \'$PackageQualifiedServiceName$\', "
Nathaniel Manistacd9ec0e2015-08-31 07:49:45 +0000454 "cardinalities, options=stub_options)\n",
455 "PackageQualifiedServiceName", package_qualified_service_name);
456 }
457 return true;
458}
459
Nathaniel Manista45479402016-06-13 20:14:18 +0000460bool PrintStub(const grpc::string& package_qualified_service_name,
461 const ServiceDescriptor* service, Printer* out) {
462 out->Print("\n\n");
463 out->Print("class $Service$Stub(object):\n", "Service", service->name());
464 {
465 IndentScope raii_class_indent(out);
466 PrintAllComments(service, out);
467 out->Print("\n");
468 out->Print("def __init__(self, channel):\n");
469 {
470 IndentScope raii_init_indent(out);
471 out->Print("\"\"\"Constructor.\n");
472 out->Print("\n");
473 out->Print("Args:\n");
474 {
475 IndentScope raii_args_indent(out);
476 out->Print("channel: A grpc.Channel.\n");
477 }
478 out->Print("\"\"\"\n");
479 for (int i = 0; i < service->method_count(); ++i) {
480 auto method = service->method(i);
481 auto multi_callable_constructor =
482 grpc::string(method->client_streaming() ? "stream" : "unary") +
483 "_" +
484 grpc::string(method->server_streaming() ? "stream" : "unary");
485 grpc::string request_module_and_class;
486 if (!GetModuleAndMessagePath(method->input_type(), service,
487 &request_module_and_class)) {
488 return false;
489 }
490 grpc::string response_module_and_class;
491 if (!GetModuleAndMessagePath(method->output_type(), service,
492 &response_module_and_class)) {
493 return false;
494 }
495 out->Print("self.$Method$ = channel.$MultiCallableConstructor$(\n",
496 "Method", method->name(),
497 "MultiCallableConstructor", multi_callable_constructor);
498 {
499 IndentScope raii_first_attribute_indent(out);
500 IndentScope raii_second_attribute_indent(out);
501 out->Print(
502 "'/$PackageQualifiedService$/$Method$',\n",
503 "PackageQualifiedService", package_qualified_service_name,
504 "Method", method->name());
505 out->Print(
506 "request_serializer=$RequestModuleAndClass$.SerializeToString,\n",
507 "RequestModuleAndClass", request_module_and_class);
508 out->Print(
509 "response_deserializer=$ResponseModuleAndClass$.FromString,\n",
510 "ResponseModuleAndClass", response_module_and_class);
511 out->Print(")\n");
512 }
513 }
514 }
515 }
516 return true;
517}
518
519bool PrintServicer(const ServiceDescriptor* service, Printer* out) {
520 out->Print("\n\n");
521 out->Print("class $Service$Servicer(object):\n", "Service", service->name());
522 {
523 IndentScope raii_class_indent(out);
524 PrintAllComments(service, out);
525 for (int i = 0; i < service->method_count(); ++i) {
526 auto method = service->method(i);
527 grpc::string arg_name = method->client_streaming() ?
528 "request_iterator" : "request";
529 out->Print("\n");
530 out->Print("def $Method$(self, $ArgName$, context):\n",
531 "Method", method->name(), "ArgName", arg_name);
532 {
533 IndentScope raii_method_indent(out);
534 PrintAllComments(method, out);
535 out->Print("context.set_code(grpc.StatusCode.UNIMPLEMENTED)\n");
536 out->Print("context.set_details('Method not implemented!')\n");
537 out->Print("raise NotImplementedError('Method not implemented!')\n");
538 }
539 }
540 }
541 return true;
542}
543
544bool PrintAddServicerToServer(const grpc::string& package_qualified_service_name,
545 const ServiceDescriptor* service, Printer* out) {
546 out->Print("\n\n");
547 out->Print("def add_$Service$Servicer_to_server(servicer, server):\n",
548 "Service", service->name());
549 {
550 IndentScope raii_class_indent(out);
551 out->Print("rpc_method_handlers = {\n");
552 {
553 IndentScope raii_dict_first_indent(out);
554 IndentScope raii_dict_second_indent(out);
555 for (int i = 0; i < service->method_count(); ++i) {
556 auto method = service->method(i);
557 auto method_handler_constructor =
558 grpc::string(method->client_streaming() ? "stream" : "unary") +
559 "_" +
560 grpc::string(method->server_streaming() ? "stream" : "unary") +
561 "_rpc_method_handler";
562 grpc::string request_module_and_class;
563 if (!GetModuleAndMessagePath(method->input_type(), service,
564 &request_module_and_class)) {
565 return false;
566 }
567 grpc::string response_module_and_class;
568 if (!GetModuleAndMessagePath(method->output_type(), service,
569 &response_module_and_class)) {
570 return false;
571 }
572 out->Print("'$Method$': grpc.$MethodHandlerConstructor$(\n",
573 "Method", method->name(),
574 "MethodHandlerConstructor", method_handler_constructor);
575 {
576 IndentScope raii_call_first_indent(out);
577 IndentScope raii_call_second_indent(out);
578 out->Print("servicer.$Method$,\n", "Method", method->name());
579 out->Print("request_deserializer=$RequestModuleAndClass$.FromString,\n",
580 "RequestModuleAndClass", request_module_and_class);
581 out->Print("response_serializer=$ResponseModuleAndClass$.SerializeToString,\n",
582 "ResponseModuleAndClass", response_module_and_class);
583 }
584 out->Print("),\n");
585 }
586 }
587 out->Print("}\n");
588 out->Print("generic_handler = grpc.method_handlers_generic_handler(\n");
589 {
590 IndentScope raii_call_first_indent(out);
591 IndentScope raii_call_second_indent(out);
592 out->Print("'$PackageQualifiedServiceName$', rpc_method_handlers)\n",
593 "PackageQualifiedServiceName", package_qualified_service_name);
594 }
595 out->Print("server.add_generic_rpc_handlers((generic_handler,))\n");
596 }
597 return true;
598}
599
Masood Malekghassemi3bb52152015-03-17 21:52:52 -0700600bool PrintPreamble(const FileDescriptor* file,
601 const GeneratorConfiguration& config, Printer* out) {
Nathaniel Manista45479402016-06-13 20:14:18 +0000602 out->Print("import $Package$\n", "Package", config.grpc_package_root);
Nathaniel Manistaf65d3c12015-09-05 03:55:19 +0000603 out->Print("from $Package$ import implementations as beta_implementations\n",
Nathaniel Manistacd9ec0e2015-08-31 07:49:45 +0000604 "Package", config.beta_package_root);
Masood Malekghassemi832ae812016-04-27 18:38:54 -0700605 out->Print("from $Package$ import interfaces as beta_interfaces\n",
606 "Package", config.beta_package_root);
Nathaniel Manistacd9ec0e2015-08-31 07:49:45 +0000607 out->Print("from grpc.framework.common import cardinality\n");
608 out->Print("from grpc.framework.interfaces.face import utilities as face_utilities\n");
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800609 return true;
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800610}
611
612} // namespace
613
Masood Malekghassemi65c803b2015-03-20 06:48:47 -0700614pair<bool, grpc::string> GetServices(const FileDescriptor* file,
Nathaniel Manistadc8c3232016-01-16 18:28:45 +0000615 const GeneratorConfiguration& config) {
Masood Malekghassemi65c803b2015-03-20 06:48:47 -0700616 grpc::string output;
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800617 {
618 // Scope the output stream so it closes and finalizes output to the string.
619 StringOutputStream output_stream(&output);
620 Printer out(&output_stream, '$');
Masood Malekghassemi3bb52152015-03-17 21:52:52 -0700621 if (!PrintPreamble(file, config, &out)) {
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800622 return make_pair(false, "");
623 }
Nathaniel Manistac4fada62015-03-13 22:23:59 +0000624 auto package = file->package();
625 if (!package.empty()) {
626 package = package.append(".");
627 }
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800628 for (int i = 0; i < file->service_count(); ++i) {
629 auto service = file->service(i);
Nathaniel Manistac4fada62015-03-13 22:23:59 +0000630 auto package_qualified_service_name = package + service->name();
Nathaniel Manista45479402016-06-13 20:14:18 +0000631 if (!(PrintStub(package_qualified_service_name, service, &out) &&
632 PrintServicer(service, &out) &&
633 PrintAddServicerToServer(package_qualified_service_name, service, &out) &&
634 PrintBetaServicer(service, &out) &&
Nathaniel Manistacd9ec0e2015-08-31 07:49:45 +0000635 PrintBetaStub(service, &out) &&
636 PrintBetaServerFactory(package_qualified_service_name, service, &out) &&
637 PrintBetaStubFactory(package_qualified_service_name, service, &out))) {
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800638 return make_pair(false, "");
639 }
640 }
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800641 }
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800642 return make_pair(true, std::move(output));
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800643}
644
645} // namespace grpc_python_generator