blob: 34d5332d03fdf485687ee4265a30c177af436402 [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 }
219 message_type.pop_back();
220 *out = make_pair(module, message_type);
221 return true;
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800222}
223
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800224bool PrintServerFactory(const ServiceDescriptor* service, Printer* out) {
225 out->Print("def early_adopter_create_$Service$_server(servicer, port, "
226 "root_certificates, key_chain_pairs):\n",
227 "Service", service->name());
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800228 {
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800229 IndentScope raii_create_server_indent(out);
230 map<string, pair<string, string>> method_to_module_and_message;
231 out->Print("method_implementations = {\n");
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800232 for (int i = 0; i < service->method_count(); ++i) {
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800233 IndentScope raii_implementations_indent(out);
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800234 const MethodDescriptor* meth = service->method(i);
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800235 string meth_type =
236 string(meth->client_streaming() ? "stream" : "unary") +
237 string(meth->server_streaming() ? "_stream" : "_unary") + "_inline";
238 out->Print("\"$Method$\": utilities.$Type$(servicer.$Method$),\n",
239 "Method", meth->name(),
240 "Type", meth_type);
241 // Maintain information on the input type of the service method for later
242 // use in constructing the service assembly's activated fore link.
243 const Descriptor* input_type = meth->input_type();
244 pair<string, string> module_and_message;
245 if (!GetModuleAndMessagePath(input_type, &module_and_message)) {
246 return false;
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800247 }
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800248 method_to_module_and_message.emplace(
249 meth->name(), module_and_message);
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800250 }
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800251 out->Print("}\n");
252 // Ensure that we've imported all of the relevant messages.
253 for (auto& meth_vals : method_to_module_and_message) {
254 out->Print("import $Module$\n",
255 "Module", meth_vals.second.first);
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800256 }
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800257 out->Print("request_deserializers = {\n");
258 for (auto& meth_vals : method_to_module_and_message) {
259 IndentScope raii_serializers_indent(out);
260 string full_input_type_path = meth_vals.second.first + "." +
261 meth_vals.second.second;
262 out->Print("\"$Method$\": $Type$.FromString,\n",
263 "Method", meth_vals.first,
264 "Type", full_input_type_path);
265 }
266 out->Print("}\n");
267 out->Print("response_serializers = {\n");
268 for (auto& meth_vals : method_to_module_and_message) {
269 IndentScope raii_serializers_indent(out);
270 out->Print("\"$Method$\": lambda x: x.SerializeToString(),\n",
271 "Method", meth_vals.first);
272 }
273 out->Print("}\n");
274 out->Print("link = fore.activated_fore_link(port, request_deserializers, "
275 "response_serializers, root_certificates, key_chain_pairs)\n");
276 out->Print("return implementations.assemble_service("
277 "method_implementations, link)\n");
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800278 }
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800279 return true;
280}
281
282bool PrintStubFactory(const ServiceDescriptor* service, Printer* out) {
283 map<string, string> dict = ListToDict({
284 "Service", service->name(),
285 });
286 out->Print(dict, "def early_adopter_create_$Service$_stub(host, port):\n");
287 {
288 IndentScope raii_create_server_indent(out);
289 map<string, pair<string, string>> method_to_module_and_message;
290 out->Print("method_implementations = {\n");
291 for (int i = 0; i < service->method_count(); ++i) {
292 IndentScope raii_implementations_indent(out);
293 const MethodDescriptor* meth = service->method(i);
294 string meth_type =
295 string(meth->client_streaming() ? "stream" : "unary") +
296 string(meth->server_streaming() ? "_stream" : "_unary") + "_inline";
297 // TODO(atash): once the expected input to assemble_dynamic_inline_stub is
298 // cleaned up, change this to the expected argument's dictionary values.
299 out->Print("\"$Method$\": utilities.$Type$(None),\n",
300 "Method", meth->name(),
301 "Type", meth_type);
302 // Maintain information on the input type of the service method for later
303 // use in constructing the service assembly's activated fore link.
304 const Descriptor* output_type = meth->output_type();
305 pair<string, string> module_and_message;
306 if (!GetModuleAndMessagePath(output_type, &module_and_message)) {
307 return false;
308 }
309 method_to_module_and_message.emplace(
310 meth->name(), module_and_message);
311 }
312 out->Print("}\n");
313 // Ensure that we've imported all of the relevant messages.
314 for (auto& meth_vals : method_to_module_and_message) {
315 out->Print("import $Module$\n",
316 "Module", meth_vals.second.first);
317 }
318 out->Print("response_deserializers = {\n");
319 for (auto& meth_vals : method_to_module_and_message) {
320 IndentScope raii_serializers_indent(out);
321 string full_output_type_path = meth_vals.second.first + "." +
322 meth_vals.second.second;
323 out->Print("\"$Method$\": $Type$.FromString,\n",
324 "Method", meth_vals.first,
325 "Type", full_output_type_path);
326 }
327 out->Print("}\n");
328 out->Print("request_serializers = {\n");
329 for (auto& meth_vals : method_to_module_and_message) {
330 IndentScope raii_serializers_indent(out);
331 out->Print("\"$Method$\": lambda x: x.SerializeToString(),\n",
332 "Method", meth_vals.first);
333 }
334 out->Print("}\n");
335 out->Print("link = rear.activated_rear_link("
336 "host, port, request_serializers, response_deserializers)\n");
337 out->Print("return implementations.assemble_dynamic_inline_stub("
338 "method_implementations, link)\n");
339 }
340 return true;
341}
342
343bool PrintPreamble(const FileDescriptor* file, Printer* out) {
344 out->Print("import abc\n");
345 out->Print("from grpc._adapter import fore\n");
346 out->Print("from grpc._adapter import rear\n");
347 out->Print("from grpc.framework.assembly import implementations\n");
348 out->Print("from grpc.framework.assembly import utilities\n");
349 return true;
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800350}
351
352} // namespace
353
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800354pair<bool, string> GetServices(const FileDescriptor* file) {
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800355 string output;
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800356 {
357 // Scope the output stream so it closes and finalizes output to the string.
358 StringOutputStream output_stream(&output);
359 Printer out(&output_stream, '$');
360 if (!PrintPreamble(file, &out)) {
361 return make_pair(false, "");
362 }
363 for (int i = 0; i < file->service_count(); ++i) {
364 auto service = file->service(i);
365 if (!(PrintServicer(service, &out) &&
366 PrintServer(service, &out) &&
367 PrintStub(service, &out) &&
368 PrintServerFactory(service, &out) &&
369 PrintStubFactory(service, &out))) {
370 return make_pair(false, "");
371 }
372 }
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800373 }
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800374 return make_pair(true, std::move(output));
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800375}
376
377} // namespace grpc_python_generator