blob: 490c51839949e094569d4dd56620a3614bb59b99 [file] [log] [blame]
Masood Malekghassemif8e297a2015-02-19 15:39:32 -08001/*
2 *
3 * Copyright 2015, 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 <cassert>
35#include <cctype>
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -080036#include <cstring>
Masood Malekghassemif8e297a2015-02-19 15:39:32 -080037#include <map>
38#include <ostream>
39#include <sstream>
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -080040#include <vector>
Masood Malekghassemif8e297a2015-02-19 15:39:32 -080041
42#include "src/compiler/python_generator.h"
43#include <google/protobuf/io/printer.h>
44#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
45#include <google/protobuf/descriptor.pb.h>
46#include <google/protobuf/descriptor.h>
47
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -080048using google::protobuf::Descriptor;
Masood Malekghassemif8e297a2015-02-19 15:39:32 -080049using google::protobuf::FileDescriptor;
50using google::protobuf::ServiceDescriptor;
51using google::protobuf::MethodDescriptor;
52using google::protobuf::io::Printer;
53using google::protobuf::io::StringOutputStream;
54using std::initializer_list;
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -080055using std::make_pair;
Masood Malekghassemif8e297a2015-02-19 15:39:32 -080056using std::map;
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -080057using std::pair;
Masood Malekghassemif8e297a2015-02-19 15:39:32 -080058using std::string;
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -080059using std::strlen;
60using std::vector;
Masood Malekghassemif8e297a2015-02-19 15:39:32 -080061
62namespace grpc_python_generator {
63namespace {
64//////////////////////////////////
65// BEGIN FORMATTING BOILERPLATE //
66//////////////////////////////////
67
68// Converts an initializer list of the form { key0, value0, key1, value1, ... }
69// into a map of key* to value*. Is merely a readability helper for later code.
70map<string, string> ListToDict(const initializer_list<string>& values) {
71 assert(values.size() % 2 == 0);
72 map<string, string> value_map;
73 auto value_iter = values.begin();
74 for (unsigned i = 0; i < values.size()/2; ++i) {
75 string key = *value_iter;
76 ++value_iter;
77 string value = *value_iter;
78 value_map[key] = value;
79 ++value_iter;
80 }
81 return value_map;
82}
83
84// Provides RAII indentation handling. Use as:
85// {
86// IndentScope raii_my_indent_var_name_here(my_py_printer);
87// // constructor indented my_py_printer
88// ...
89// // destructor called at end of scope, un-indenting my_py_printer
90// }
91class IndentScope {
92 public:
93 explicit IndentScope(Printer* printer) : printer_(printer) {
94 printer_->Indent();
95 }
96
97 ~IndentScope() {
98 printer_->Outdent();
99 }
100
101 private:
102 Printer* printer_;
103};
104
105////////////////////////////////
106// END FORMATTING BOILERPLATE //
107////////////////////////////////
108
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800109bool PrintServicer(const ServiceDescriptor* service,
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800110 Printer* out) {
111 string doc = "<fill me in later!>";
112 map<string, string> dict = ListToDict({
113 "Service", service->name(),
114 "Documentation", doc,
115 });
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800116 out->Print(dict, "class EarlyAdopter$Service$Servicer(object):\n");
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800117 {
118 IndentScope raii_class_indent(out);
119 out->Print(dict, "\"\"\"$Documentation$\"\"\"\n");
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800120 out->Print("__metaclass__ = abc.ABCMeta\n");
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800121 for (int i = 0; i < service->method_count(); ++i) {
122 auto meth = service->method(i);
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800123 string arg_name = meth->client_streaming() ?
124 "request_iterator" : "request";
125 out->Print("@abc.abstractmethod\n");
126 out->Print("def $Method$(self, $ArgName$):\n",
127 "Method", meth->name(), "ArgName", arg_name);
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800128 {
129 IndentScope raii_method_indent(out);
130 out->Print("raise NotImplementedError()\n");
131 }
132 }
133 }
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800134 return true;
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800135}
136
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800137bool PrintServer(const ServiceDescriptor* service, Printer* out) {
138 string doc = "<fill me in later!>";
139 map<string, string> dict = ListToDict({
140 "Service", service->name(),
141 "Documentation", doc,
142 });
143 out->Print(dict, "class EarlyAdopter$Service$Server(object):\n");
144 {
145 IndentScope raii_class_indent(out);
146 out->Print(dict, "\"\"\"$Documentation$\"\"\"\n");
147 out->Print("__metaclass__ = abc.ABCMeta\n");
148 out->Print("@abc.abstractmethod\n");
149 out->Print("def start(self):\n");
150 {
151 IndentScope raii_method_indent(out);
152 out->Print("raise NotImplementedError()\n");
153 }
154
155 out->Print("@abc.abstractmethod\n");
156 out->Print("def stop(self):\n");
157 {
158 IndentScope raii_method_indent(out);
159 out->Print("raise NotImplementedError()\n");
160 }
161 }
162 return true;
163}
164
165bool PrintStub(const ServiceDescriptor* service,
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800166 Printer* out) {
167 string doc = "<fill me in later!>";
168 map<string, string> dict = ListToDict({
169 "Service", service->name(),
170 "Documentation", doc,
171 });
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800172 out->Print(dict, "class EarlyAdopter$Service$Stub(object):\n");
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800173 {
174 IndentScope raii_class_indent(out);
175 out->Print(dict, "\"\"\"$Documentation$\"\"\"\n");
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800176 out->Print("__metaclass__ = abc.ABCMeta\n");
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800177 for (int i = 0; i < service->method_count(); ++i) {
178 const MethodDescriptor* meth = service->method(i);
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800179 string arg_name = meth->client_streaming() ?
180 "request_iterator" : "request";
181 auto methdict = ListToDict({"Method", meth->name(), "ArgName", arg_name});
182 out->Print("@abc.abstractmethod\n");
183 out->Print(methdict, "def $Method$(self, $ArgName$):\n");
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800184 {
185 IndentScope raii_method_indent(out);
186 out->Print("raise NotImplementedError()\n");
187 }
188 out->Print(methdict, "$Method$.async = None\n");
189 }
190 }
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800191 return true;
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800192}
193
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800194bool GetModuleAndMessagePath(const Descriptor* type,
195 pair<string, string>* out) {
196 const Descriptor* path_elem_type = type;
197 vector<const Descriptor*> message_path;
198 do {
199 message_path.push_back(path_elem_type);
200 path_elem_type = path_elem_type->containing_type();
201 } while (path_elem_type != nullptr);
202 string file_name = type->file()->name();
203 string module_name;
204 static const int proto_suffix_length = strlen(".proto");
205 if (!(file_name.size() > static_cast<size_t>(proto_suffix_length) &&
206 file_name.find_last_of(".proto") == file_name.size() - 1)) {
207 return false;
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800208 }
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800209 module_name = file_name.substr(
210 0, file_name.size() - proto_suffix_length) + "_pb2";
211 string package = type->file()->package();
212 string module = (package.empty() ? "" : package + ".") +
213 module_name;
214 string message_type;
215 for (auto path_iter = message_path.rbegin();
216 path_iter != message_path.rend(); ++path_iter) {
217 message_type += (*path_iter)->name() + ".";
218 }
Craig Tillercf133f42015-02-26 14:05:56 -0800219 // no pop_back prior to C++11
220 message_type.resize(message_type.size() - 1);
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800221 *out = make_pair(module, message_type);
222 return true;
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800223}
224
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800225bool PrintServerFactory(const ServiceDescriptor* service, Printer* out) {
226 out->Print("def early_adopter_create_$Service$_server(servicer, port, "
227 "root_certificates, key_chain_pairs):\n",
228 "Service", service->name());
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800229 {
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800230 IndentScope raii_create_server_indent(out);
231 map<string, pair<string, string>> method_to_module_and_message;
232 out->Print("method_implementations = {\n");
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800233 for (int i = 0; i < service->method_count(); ++i) {
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800234 IndentScope raii_implementations_indent(out);
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800235 const MethodDescriptor* meth = service->method(i);
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800236 string meth_type =
237 string(meth->client_streaming() ? "stream" : "unary") +
238 string(meth->server_streaming() ? "_stream" : "_unary") + "_inline";
239 out->Print("\"$Method$\": utilities.$Type$(servicer.$Method$),\n",
240 "Method", meth->name(),
241 "Type", meth_type);
242 // Maintain information on the input type of the service method for later
243 // use in constructing the service assembly's activated fore link.
244 const Descriptor* input_type = meth->input_type();
245 pair<string, string> module_and_message;
246 if (!GetModuleAndMessagePath(input_type, &module_and_message)) {
247 return false;
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800248 }
Nicolas "Pixel" Noblee6d72c22015-02-25 22:16:45 +0100249 method_to_module_and_message.insert(
250 make_pair(meth->name(), module_and_message));
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800251 }
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800252 out->Print("}\n");
253 // Ensure that we've imported all of the relevant messages.
254 for (auto& meth_vals : method_to_module_and_message) {
255 out->Print("import $Module$\n",
256 "Module", meth_vals.second.first);
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800257 }
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800258 out->Print("request_deserializers = {\n");
259 for (auto& meth_vals : method_to_module_and_message) {
260 IndentScope raii_serializers_indent(out);
261 string full_input_type_path = meth_vals.second.first + "." +
262 meth_vals.second.second;
263 out->Print("\"$Method$\": $Type$.FromString,\n",
264 "Method", meth_vals.first,
265 "Type", full_input_type_path);
266 }
267 out->Print("}\n");
268 out->Print("response_serializers = {\n");
269 for (auto& meth_vals : method_to_module_and_message) {
270 IndentScope raii_serializers_indent(out);
271 out->Print("\"$Method$\": lambda x: x.SerializeToString(),\n",
272 "Method", meth_vals.first);
273 }
274 out->Print("}\n");
275 out->Print("link = fore.activated_fore_link(port, request_deserializers, "
276 "response_serializers, root_certificates, key_chain_pairs)\n");
277 out->Print("return implementations.assemble_service("
278 "method_implementations, link)\n");
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800279 }
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800280 return true;
281}
282
283bool PrintStubFactory(const ServiceDescriptor* service, Printer* out) {
284 map<string, string> dict = ListToDict({
285 "Service", service->name(),
286 });
287 out->Print(dict, "def early_adopter_create_$Service$_stub(host, port):\n");
288 {
289 IndentScope raii_create_server_indent(out);
290 map<string, pair<string, string>> method_to_module_and_message;
291 out->Print("method_implementations = {\n");
292 for (int i = 0; i < service->method_count(); ++i) {
293 IndentScope raii_implementations_indent(out);
294 const MethodDescriptor* meth = service->method(i);
295 string meth_type =
296 string(meth->client_streaming() ? "stream" : "unary") +
297 string(meth->server_streaming() ? "_stream" : "_unary") + "_inline";
298 // TODO(atash): once the expected input to assemble_dynamic_inline_stub is
299 // cleaned up, change this to the expected argument's dictionary values.
300 out->Print("\"$Method$\": utilities.$Type$(None),\n",
301 "Method", meth->name(),
302 "Type", meth_type);
303 // Maintain information on the input type of the service method for later
304 // use in constructing the service assembly's activated fore link.
305 const Descriptor* output_type = meth->output_type();
306 pair<string, string> module_and_message;
307 if (!GetModuleAndMessagePath(output_type, &module_and_message)) {
308 return false;
309 }
Nicolas "Pixel" Noblee6d72c22015-02-25 22:16:45 +0100310 method_to_module_and_message.insert(
311 make_pair(meth->name(), module_and_message));
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800312 }
313 out->Print("}\n");
314 // Ensure that we've imported all of the relevant messages.
315 for (auto& meth_vals : method_to_module_and_message) {
316 out->Print("import $Module$\n",
317 "Module", meth_vals.second.first);
318 }
319 out->Print("response_deserializers = {\n");
320 for (auto& meth_vals : method_to_module_and_message) {
321 IndentScope raii_serializers_indent(out);
322 string full_output_type_path = meth_vals.second.first + "." +
323 meth_vals.second.second;
324 out->Print("\"$Method$\": $Type$.FromString,\n",
325 "Method", meth_vals.first,
326 "Type", full_output_type_path);
327 }
328 out->Print("}\n");
329 out->Print("request_serializers = {\n");
330 for (auto& meth_vals : method_to_module_and_message) {
331 IndentScope raii_serializers_indent(out);
332 out->Print("\"$Method$\": lambda x: x.SerializeToString(),\n",
333 "Method", meth_vals.first);
334 }
335 out->Print("}\n");
336 out->Print("link = rear.activated_rear_link("
337 "host, port, request_serializers, response_deserializers)\n");
338 out->Print("return implementations.assemble_dynamic_inline_stub("
339 "method_implementations, link)\n");
340 }
341 return true;
342}
343
344bool PrintPreamble(const FileDescriptor* file, Printer* out) {
345 out->Print("import abc\n");
346 out->Print("from grpc._adapter import fore\n");
347 out->Print("from grpc._adapter import rear\n");
348 out->Print("from grpc.framework.assembly import implementations\n");
349 out->Print("from grpc.framework.assembly import utilities\n");
350 return true;
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800351}
352
353} // namespace
354
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800355pair<bool, string> GetServices(const FileDescriptor* file) {
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800356 string output;
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800357 {
358 // Scope the output stream so it closes and finalizes output to the string.
359 StringOutputStream output_stream(&output);
360 Printer out(&output_stream, '$');
361 if (!PrintPreamble(file, &out)) {
362 return make_pair(false, "");
363 }
364 for (int i = 0; i < file->service_count(); ++i) {
365 auto service = file->service(i);
366 if (!(PrintServicer(service, &out) &&
367 PrintServer(service, &out) &&
368 PrintStub(service, &out) &&
369 PrintServerFactory(service, &out) &&
370 PrintStubFactory(service, &out))) {
371 return make_pair(false, "");
372 }
373 }
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800374 }
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800375 return make_pair(true, std::move(output));
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800376}
377
378} // namespace grpc_python_generator