blob: 6aafc86be55b15b3aa3373ec63286b36a6f31d7e [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
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>
39#include <ostream>
40#include <sstream>
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -080041#include <vector>
Masood Malekghassemif8e297a2015-02-19 15:39:32 -080042
43#include "src/compiler/python_generator.h"
44#include <google/protobuf/io/printer.h>
45#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
46#include <google/protobuf/descriptor.pb.h>
47#include <google/protobuf/descriptor.h>
Masood Malekghassemi40e8cbd2015-02-26 08:39:50 -080048#include <google/protobuf/stubs/strutil.h>
Masood Malekghassemif8e297a2015-02-19 15:39:32 -080049
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -080050using google::protobuf::Descriptor;
Masood Malekghassemif8e297a2015-02-19 15:39:32 -080051using google::protobuf::FileDescriptor;
Masood Malekghassemi40e8cbd2015-02-26 08:39:50 -080052using google::protobuf::HasSuffixString;
Masood Malekghassemif8e297a2015-02-19 15:39:32 -080053using google::protobuf::MethodDescriptor;
Masood Malekghassemi40e8cbd2015-02-26 08:39:50 -080054using google::protobuf::ServiceDescriptor;
55using google::protobuf::StripString;
56using google::protobuf::StripSuffixString;
Masood Malekghassemif8e297a2015-02-19 15:39:32 -080057using google::protobuf::io::Printer;
58using google::protobuf::io::StringOutputStream;
59using std::initializer_list;
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -080060using std::make_pair;
Masood Malekghassemif8e297a2015-02-19 15:39:32 -080061using std::map;
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -080062using std::pair;
Masood Malekghassemi40e8cbd2015-02-26 08:39:50 -080063using std::replace;
Masood Malekghassemif8e297a2015-02-19 15:39:32 -080064using std::string;
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -080065using std::strlen;
66using std::vector;
Masood Malekghassemif8e297a2015-02-19 15:39:32 -080067
68namespace grpc_python_generator {
69namespace {
70//////////////////////////////////
71// BEGIN FORMATTING BOILERPLATE //
72//////////////////////////////////
73
74// Converts an initializer list of the form { key0, value0, key1, value1, ... }
75// into a map of key* to value*. Is merely a readability helper for later code.
76map<string, string> ListToDict(const initializer_list<string>& values) {
77 assert(values.size() % 2 == 0);
78 map<string, string> value_map;
79 auto value_iter = values.begin();
80 for (unsigned i = 0; i < values.size()/2; ++i) {
81 string key = *value_iter;
82 ++value_iter;
83 string value = *value_iter;
84 value_map[key] = value;
85 ++value_iter;
86 }
87 return value_map;
88}
89
90// Provides RAII indentation handling. Use as:
91// {
92// IndentScope raii_my_indent_var_name_here(my_py_printer);
93// // constructor indented my_py_printer
94// ...
95// // destructor called at end of scope, un-indenting my_py_printer
96// }
97class IndentScope {
98 public:
99 explicit IndentScope(Printer* printer) : printer_(printer) {
100 printer_->Indent();
101 }
102
103 ~IndentScope() {
104 printer_->Outdent();
105 }
106
107 private:
108 Printer* printer_;
109};
110
111////////////////////////////////
112// END FORMATTING BOILERPLATE //
113////////////////////////////////
114
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800115bool PrintServicer(const ServiceDescriptor* service,
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800116 Printer* out) {
117 string doc = "<fill me in later!>";
118 map<string, string> dict = ListToDict({
119 "Service", service->name(),
120 "Documentation", doc,
121 });
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800122 out->Print(dict, "class EarlyAdopter$Service$Servicer(object):\n");
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800123 {
124 IndentScope raii_class_indent(out);
125 out->Print(dict, "\"\"\"$Documentation$\"\"\"\n");
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800126 out->Print("__metaclass__ = abc.ABCMeta\n");
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800127 for (int i = 0; i < service->method_count(); ++i) {
128 auto meth = service->method(i);
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800129 string arg_name = meth->client_streaming() ?
130 "request_iterator" : "request";
131 out->Print("@abc.abstractmethod\n");
Masood Malekghassemi40e8cbd2015-02-26 08:39:50 -0800132 out->Print("def $Method$(self, $ArgName$, context):\n",
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800133 "Method", meth->name(), "ArgName", arg_name);
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800134 {
135 IndentScope raii_method_indent(out);
136 out->Print("raise NotImplementedError()\n");
137 }
138 }
139 }
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800140 return true;
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800141}
142
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800143bool PrintServer(const ServiceDescriptor* service, Printer* out) {
144 string doc = "<fill me in later!>";
145 map<string, string> dict = ListToDict({
146 "Service", service->name(),
147 "Documentation", doc,
148 });
149 out->Print(dict, "class EarlyAdopter$Service$Server(object):\n");
150 {
151 IndentScope raii_class_indent(out);
152 out->Print(dict, "\"\"\"$Documentation$\"\"\"\n");
153 out->Print("__metaclass__ = abc.ABCMeta\n");
154 out->Print("@abc.abstractmethod\n");
155 out->Print("def start(self):\n");
156 {
157 IndentScope raii_method_indent(out);
158 out->Print("raise NotImplementedError()\n");
159 }
160
161 out->Print("@abc.abstractmethod\n");
162 out->Print("def stop(self):\n");
163 {
164 IndentScope raii_method_indent(out);
165 out->Print("raise NotImplementedError()\n");
166 }
167 }
168 return true;
169}
170
171bool PrintStub(const ServiceDescriptor* service,
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800172 Printer* out) {
173 string doc = "<fill me in later!>";
174 map<string, string> dict = ListToDict({
175 "Service", service->name(),
176 "Documentation", doc,
177 });
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800178 out->Print(dict, "class EarlyAdopter$Service$Stub(object):\n");
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800179 {
180 IndentScope raii_class_indent(out);
181 out->Print(dict, "\"\"\"$Documentation$\"\"\"\n");
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800182 out->Print("__metaclass__ = abc.ABCMeta\n");
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800183 for (int i = 0; i < service->method_count(); ++i) {
184 const MethodDescriptor* meth = service->method(i);
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800185 string arg_name = meth->client_streaming() ?
186 "request_iterator" : "request";
187 auto methdict = ListToDict({"Method", meth->name(), "ArgName", arg_name});
188 out->Print("@abc.abstractmethod\n");
189 out->Print(methdict, "def $Method$(self, $ArgName$):\n");
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800190 {
191 IndentScope raii_method_indent(out);
192 out->Print("raise NotImplementedError()\n");
193 }
194 out->Print(methdict, "$Method$.async = None\n");
195 }
196 }
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800197 return true;
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800198}
199
Masood Malekghassemi40e8cbd2015-02-26 08:39:50 -0800200// TODO(protobuf team): See TODO for `ModuleName`.
201string StripProto(const string& filename) {
202 const char* suffix = HasSuffixString(filename, ".protodevel")
203 ? ".protodevel" : ".proto";
204 return StripSuffixString(filename, suffix);
205}
206// TODO(protobuf team): Export `ModuleName` from protobuf's
207// `src/google/protobuf/compiler/python/python_generator.cc` file.
208string ModuleName(const string& filename) {
209 string basename = StripProto(filename);
210 StripString(&basename, "-", '_');
211 StripString(&basename, "/", '.');
212 return basename + "_pb2";
213}
214
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800215bool GetModuleAndMessagePath(const Descriptor* type,
216 pair<string, string>* out) {
217 const Descriptor* path_elem_type = type;
218 vector<const Descriptor*> message_path;
219 do {
220 message_path.push_back(path_elem_type);
221 path_elem_type = path_elem_type->containing_type();
222 } while (path_elem_type != nullptr);
223 string file_name = type->file()->name();
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800224 static const int proto_suffix_length = strlen(".proto");
225 if (!(file_name.size() > static_cast<size_t>(proto_suffix_length) &&
226 file_name.find_last_of(".proto") == file_name.size() - 1)) {
227 return false;
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800228 }
Masood Malekghassemi40e8cbd2015-02-26 08:39:50 -0800229 string module = ModuleName(file_name);
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800230 string message_type;
231 for (auto path_iter = message_path.rbegin();
232 path_iter != message_path.rend(); ++path_iter) {
233 message_type += (*path_iter)->name() + ".";
234 }
235 message_type.pop_back();
236 *out = make_pair(module, message_type);
237 return true;
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800238}
239
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800240bool PrintServerFactory(const ServiceDescriptor* service, Printer* out) {
241 out->Print("def early_adopter_create_$Service$_server(servicer, port, "
242 "root_certificates, key_chain_pairs):\n",
243 "Service", service->name());
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800244 {
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800245 IndentScope raii_create_server_indent(out);
246 map<string, pair<string, string>> method_to_module_and_message;
247 out->Print("method_implementations = {\n");
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800248 for (int i = 0; i < service->method_count(); ++i) {
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800249 IndentScope raii_implementations_indent(out);
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800250 const MethodDescriptor* meth = service->method(i);
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800251 string meth_type =
252 string(meth->client_streaming() ? "stream" : "unary") +
253 string(meth->server_streaming() ? "_stream" : "_unary") + "_inline";
254 out->Print("\"$Method$\": utilities.$Type$(servicer.$Method$),\n",
255 "Method", meth->name(),
256 "Type", meth_type);
257 // Maintain information on the input type of the service method for later
258 // use in constructing the service assembly's activated fore link.
259 const Descriptor* input_type = meth->input_type();
260 pair<string, string> module_and_message;
261 if (!GetModuleAndMessagePath(input_type, &module_and_message)) {
262 return false;
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800263 }
Nicolas "Pixel" Noblee6d72c22015-02-25 22:16:45 +0100264 method_to_module_and_message.insert(
265 make_pair(meth->name(), module_and_message));
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800266 }
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800267 out->Print("}\n");
268 // Ensure that we've imported all of the relevant messages.
269 for (auto& meth_vals : method_to_module_and_message) {
270 out->Print("import $Module$\n",
271 "Module", meth_vals.second.first);
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800272 }
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800273 out->Print("request_deserializers = {\n");
274 for (auto& meth_vals : method_to_module_and_message) {
275 IndentScope raii_serializers_indent(out);
276 string full_input_type_path = meth_vals.second.first + "." +
277 meth_vals.second.second;
278 out->Print("\"$Method$\": $Type$.FromString,\n",
279 "Method", meth_vals.first,
280 "Type", full_input_type_path);
281 }
282 out->Print("}\n");
283 out->Print("response_serializers = {\n");
284 for (auto& meth_vals : method_to_module_and_message) {
285 IndentScope raii_serializers_indent(out);
286 out->Print("\"$Method$\": lambda x: x.SerializeToString(),\n",
287 "Method", meth_vals.first);
288 }
289 out->Print("}\n");
290 out->Print("link = fore.activated_fore_link(port, request_deserializers, "
291 "response_serializers, root_certificates, key_chain_pairs)\n");
292 out->Print("return implementations.assemble_service("
293 "method_implementations, link)\n");
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800294 }
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800295 return true;
296}
297
298bool PrintStubFactory(const ServiceDescriptor* service, Printer* out) {
299 map<string, string> dict = ListToDict({
300 "Service", service->name(),
301 });
302 out->Print(dict, "def early_adopter_create_$Service$_stub(host, port):\n");
303 {
304 IndentScope raii_create_server_indent(out);
305 map<string, pair<string, string>> method_to_module_and_message;
306 out->Print("method_implementations = {\n");
307 for (int i = 0; i < service->method_count(); ++i) {
308 IndentScope raii_implementations_indent(out);
309 const MethodDescriptor* meth = service->method(i);
310 string meth_type =
311 string(meth->client_streaming() ? "stream" : "unary") +
312 string(meth->server_streaming() ? "_stream" : "_unary") + "_inline";
313 // TODO(atash): once the expected input to assemble_dynamic_inline_stub is
314 // cleaned up, change this to the expected argument's dictionary values.
315 out->Print("\"$Method$\": utilities.$Type$(None),\n",
316 "Method", meth->name(),
317 "Type", meth_type);
318 // Maintain information on the input type of the service method for later
319 // use in constructing the service assembly's activated fore link.
320 const Descriptor* output_type = meth->output_type();
321 pair<string, string> module_and_message;
322 if (!GetModuleAndMessagePath(output_type, &module_and_message)) {
323 return false;
324 }
Nicolas "Pixel" Noblee6d72c22015-02-25 22:16:45 +0100325 method_to_module_and_message.insert(
326 make_pair(meth->name(), module_and_message));
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800327 }
328 out->Print("}\n");
329 // Ensure that we've imported all of the relevant messages.
330 for (auto& meth_vals : method_to_module_and_message) {
331 out->Print("import $Module$\n",
332 "Module", meth_vals.second.first);
333 }
334 out->Print("response_deserializers = {\n");
335 for (auto& meth_vals : method_to_module_and_message) {
336 IndentScope raii_serializers_indent(out);
337 string full_output_type_path = meth_vals.second.first + "." +
338 meth_vals.second.second;
339 out->Print("\"$Method$\": $Type$.FromString,\n",
340 "Method", meth_vals.first,
341 "Type", full_output_type_path);
342 }
343 out->Print("}\n");
344 out->Print("request_serializers = {\n");
345 for (auto& meth_vals : method_to_module_and_message) {
346 IndentScope raii_serializers_indent(out);
347 out->Print("\"$Method$\": lambda x: x.SerializeToString(),\n",
348 "Method", meth_vals.first);
349 }
350 out->Print("}\n");
351 out->Print("link = rear.activated_rear_link("
352 "host, port, request_serializers, response_deserializers)\n");
353 out->Print("return implementations.assemble_dynamic_inline_stub("
354 "method_implementations, link)\n");
355 }
356 return true;
357}
358
359bool PrintPreamble(const FileDescriptor* file, Printer* out) {
360 out->Print("import abc\n");
361 out->Print("from grpc._adapter import fore\n");
362 out->Print("from grpc._adapter import rear\n");
363 out->Print("from grpc.framework.assembly import implementations\n");
364 out->Print("from grpc.framework.assembly import utilities\n");
365 return true;
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800366}
367
368} // namespace
369
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800370pair<bool, string> GetServices(const FileDescriptor* file) {
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800371 string output;
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800372 {
373 // Scope the output stream so it closes and finalizes output to the string.
374 StringOutputStream output_stream(&output);
375 Printer out(&output_stream, '$');
376 if (!PrintPreamble(file, &out)) {
377 return make_pair(false, "");
378 }
379 for (int i = 0; i < file->service_count(); ++i) {
380 auto service = file->service(i);
381 if (!(PrintServicer(service, &out) &&
382 PrintServer(service, &out) &&
383 PrintStub(service, &out) &&
384 PrintServerFactory(service, &out) &&
385 PrintStubFactory(service, &out))) {
386 return make_pair(false, "");
387 }
388 }
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800389 }
Masood Malekghassemi59d9ff42015-02-23 15:28:07 -0800390 return make_pair(true, std::move(output));
Masood Malekghassemif8e297a2015-02-19 15:39:32 -0800391}
392
393} // namespace grpc_python_generator