3 * Copyright 2016 gRPC authors.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
19 #include "test/cpp/util/proto_file_parser.h"
24 #include <unordered_set>
26 #include <grpcpp/support/config.h>
32 // Match the user input method string to the full_name from method descriptor.
33 bool MethodNameMatch(const std::string& full_name, const std::string& input) {
34 std::string clean_input = input;
35 std::replace(clean_input.begin(), clean_input.end(), '/', '.');
36 if (clean_input.size() > full_name.size()) {
39 return full_name.compare(full_name.size() - clean_input.size(),
40 clean_input.size(), clean_input) == 0;
44 class ErrorPrinter : public protobuf::compiler::MultiFileErrorCollector {
46 explicit ErrorPrinter(ProtoFileParser* parser) : parser_(parser) {}
48 void AddError(const std::string& filename, int line, int column,
49 const std::string& message) override {
50 std::ostringstream oss;
51 oss << "error " << filename << " " << line << " " << column << " "
53 parser_->LogError(oss.str());
56 void AddWarning(const std::string& filename, int line, int column,
57 const std::string& message) override {
58 std::cerr << "warning " << filename << " " << line << " " << column << " "
59 << message << std::endl;
63 ProtoFileParser* parser_; // not owned
66 ProtoFileParser::ProtoFileParser(const std::shared_ptr<grpc::Channel>& channel,
67 const std::string& proto_path,
68 const std::string& protofiles)
70 dynamic_factory_(new protobuf::DynamicMessageFactory()) {
71 std::vector<std::string> service_list;
73 reflection_db_.reset(new grpc::ProtoReflectionDescriptorDatabase(channel));
74 reflection_db_->GetServices(&service_list);
77 std::unordered_set<std::string> known_services;
78 if (!protofiles.empty()) {
79 source_tree_.MapPath("", proto_path);
80 error_printer_.reset(new ErrorPrinter(this));
82 new protobuf::compiler::Importer(&source_tree_, error_printer_.get()));
84 std::string file_name;
85 std::stringstream ss(protofiles);
86 while (std::getline(ss, file_name, ',')) {
87 const auto* file_desc = importer_->Import(file_name);
89 for (int i = 0; i < file_desc->service_count(); i++) {
90 service_desc_list_.push_back(file_desc->service(i));
91 known_services.insert(file_desc->service(i)->full_name());
94 std::cerr << file_name << " not found" << std::endl;
98 file_db_.reset(new protobuf::DescriptorPoolDatabase(*importer_->pool()));
101 if (!reflection_db_ && !file_db_) {
102 LogError("No available proto database");
106 if (!reflection_db_) {
107 desc_db_ = std::move(file_db_);
108 } else if (!file_db_) {
109 desc_db_ = std::move(reflection_db_);
111 desc_db_.reset(new protobuf::MergedDescriptorDatabase(reflection_db_.get(),
115 desc_pool_.reset(new protobuf::DescriptorPool(desc_db_.get()));
117 for (auto it = service_list.begin(); it != service_list.end(); it++) {
118 if (known_services.find(*it) == known_services.end()) {
119 if (const protobuf::ServiceDescriptor* service_desc =
120 desc_pool_->FindServiceByName(*it)) {
121 service_desc_list_.push_back(service_desc);
122 known_services.insert(*it);
128 ProtoFileParser::~ProtoFileParser() {}
130 std::string ProtoFileParser::GetFullMethodName(const std::string& method) {
133 if (known_methods_.find(method) != known_methods_.end()) {
134 return known_methods_[method];
137 const protobuf::MethodDescriptor* method_descriptor = nullptr;
138 for (auto it = service_desc_list_.begin(); it != service_desc_list_.end();
140 const auto* service_desc = *it;
141 for (int j = 0; j < service_desc->method_count(); j++) {
142 const auto* method_desc = service_desc->method(j);
143 if (MethodNameMatch(method_desc->full_name(), method)) {
144 if (method_descriptor) {
145 std::ostringstream error_stream;
146 error_stream << "Ambiguous method names: ";
147 error_stream << method_descriptor->full_name() << " ";
148 error_stream << method_desc->full_name();
149 LogError(error_stream.str());
151 method_descriptor = method_desc;
155 if (!method_descriptor) {
156 LogError("Method name not found");
162 known_methods_[method] = method_descriptor->full_name();
164 return method_descriptor->full_name();
167 std::string ProtoFileParser::GetFormattedMethodName(const std::string& method) {
169 std::string formatted_method_name = GetFullMethodName(method);
173 size_t last_dot = formatted_method_name.find_last_of('.');
174 if (last_dot != std::string::npos) {
175 formatted_method_name[last_dot] = '/';
177 formatted_method_name.insert(formatted_method_name.begin(), '/');
178 return formatted_method_name;
181 std::string ProtoFileParser::GetMessageTypeFromMethod(const std::string& method,
184 std::string full_method_name = GetFullMethodName(method);
188 const protobuf::MethodDescriptor* method_desc =
189 desc_pool_->FindMethodByName(full_method_name);
191 LogError("Method not found");
195 return is_request ? method_desc->input_type()->full_name()
196 : method_desc->output_type()->full_name();
199 bool ProtoFileParser::IsStreaming(const std::string& method, bool is_request) {
202 std::string full_method_name = GetFullMethodName(method);
207 const protobuf::MethodDescriptor* method_desc =
208 desc_pool_->FindMethodByName(full_method_name);
210 LogError("Method not found");
214 return is_request ? method_desc->client_streaming()
215 : method_desc->server_streaming();
218 std::string ProtoFileParser::GetSerializedProtoFromMethod(
219 const std::string& method, const std::string& formatted_proto,
220 bool is_request, bool is_json_format) {
222 std::string message_type_name = GetMessageTypeFromMethod(method, is_request);
226 return GetSerializedProtoFromMessageType(message_type_name, formatted_proto,
230 std::string ProtoFileParser::GetFormattedStringFromMethod(
231 const std::string& method, const std::string& serialized_proto,
232 bool is_request, bool is_json_format) {
234 std::string message_type_name = GetMessageTypeFromMethod(method, is_request);
238 return GetFormattedStringFromMessageType(message_type_name, serialized_proto,
242 std::string ProtoFileParser::GetSerializedProtoFromMessageType(
243 const std::string& message_type_name, const std::string& formatted_proto,
244 bool is_json_format) {
246 std::string serialized;
247 const protobuf::Descriptor* desc =
248 desc_pool_->FindMessageTypeByName(message_type_name);
250 LogError("Message type not found");
253 std::unique_ptr<grpc::protobuf::Message> msg(
254 dynamic_factory_->GetPrototype(desc)->New());
257 if (is_json_format) {
258 ok = grpc::protobuf::json::JsonStringToMessage(formatted_proto, msg.get())
261 LogError("Failed to convert json format to proto.");
265 ok = protobuf::TextFormat::ParseFromString(formatted_proto, msg.get());
267 LogError("Failed to convert text format to proto.");
272 ok = msg->SerializeToString(&serialized);
274 LogError("Failed to serialize proto.");
280 std::string ProtoFileParser::GetFormattedStringFromMessageType(
281 const std::string& message_type_name, const std::string& serialized_proto,
282 bool is_json_format) {
284 const protobuf::Descriptor* desc =
285 desc_pool_->FindMessageTypeByName(message_type_name);
287 LogError("Message type not found");
290 std::unique_ptr<grpc::protobuf::Message> msg(
291 dynamic_factory_->GetPrototype(desc)->New());
292 if (!msg->ParseFromString(serialized_proto)) {
293 LogError("Failed to deserialize proto.");
296 std::string formatted_string;
298 if (is_json_format) {
299 grpc::protobuf::json::JsonPrintOptions jsonPrintOptions;
300 jsonPrintOptions.add_whitespace = true;
301 if (!grpc::protobuf::json::MessageToJsonString(
302 *msg.get(), &formatted_string, jsonPrintOptions)
304 LogError("Failed to print proto message to json format");
308 if (!protobuf::TextFormat::PrintToString(*msg.get(), &formatted_string)) {
309 LogError("Failed to print proto message to text format");
313 return formatted_string;
316 void ProtoFileParser::LogError(const std::string& error_msg) {
317 if (!error_msg.empty()) {
318 std::cerr << error_msg << std::endl;
323 } // namespace testing