summaryrefslogtreecommitdiffstats
path: root/contrib/libs/grpc/test/cpp
diff options
context:
space:
mode:
authorrobot-piglet <[email protected]>2023-03-23 12:15:53 +0300
committerrobot-piglet <[email protected]>2023-03-23 12:15:53 +0300
commit8d5942b8f813c0e704a166c3c83902ccceefca07 (patch)
treed717bac5cbd96eaff6a15e1c3f7b664b3b5dfce8 /contrib/libs/grpc/test/cpp
parent091daa0ca1dd4df8f596b17239c6f9a72abf3aab (diff)
Intermediate changes
Diffstat (limited to 'contrib/libs/grpc/test/cpp')
-rw-r--r--contrib/libs/grpc/test/cpp/README-iOS.md52
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/health/ya.make28
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/health_service_end2end_test.cc374
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/interceptors_util.cc216
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/interceptors_util.h354
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/server_interceptors/ya.make27
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/server_interceptors_end2end_test.cc703
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/test_health_check_service_impl.cc98
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/test_health_check_service_impl.h58
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/test_service_impl.cc635
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/test_service_impl.h500
-rw-r--r--contrib/libs/grpc/test/cpp/end2end/ya.make65
-rw-r--r--contrib/libs/grpc/test/cpp/util/byte_buffer_proto_helper.cc59
-rw-r--r--contrib/libs/grpc/test/cpp/util/byte_buffer_proto_helper.h42
-rw-r--r--contrib/libs/grpc/test/cpp/util/cli_call.cc225
-rw-r--r--contrib/libs/grpc/test/cpp/util/cli_call.h106
-rw-r--r--contrib/libs/grpc/test/cpp/util/cli_credentials.cc191
-rw-r--r--contrib/libs/grpc/test/cpp/util/cli_credentials.h55
-rw-r--r--contrib/libs/grpc/test/cpp/util/config_grpc_cli.h70
-rw-r--r--contrib/libs/grpc/test/cpp/util/grpc_tool.cc1010
-rw-r--r--contrib/libs/grpc/test/cpp/util/grpc_tool.h39
-rw-r--r--contrib/libs/grpc/test/cpp/util/proto_file_parser.cc331
-rw-r--r--contrib/libs/grpc/test/cpp/util/proto_file_parser.h135
-rw-r--r--contrib/libs/grpc/test/cpp/util/proto_reflection_descriptor_database.cc333
-rw-r--r--contrib/libs/grpc/test/cpp/util/proto_reflection_descriptor_database.h112
-rw-r--r--contrib/libs/grpc/test/cpp/util/service_describer.cc92
-rw-r--r--contrib/libs/grpc/test/cpp/util/service_describer.h43
-rw-r--r--contrib/libs/grpc/test/cpp/util/string_ref_helper.cc29
-rw-r--r--contrib/libs/grpc/test/cpp/util/string_ref_helper.h32
-rw-r--r--contrib/libs/grpc/test/cpp/util/test_config.h35
-rw-r--r--contrib/libs/grpc/test/cpp/util/test_config_cc.cc39
-rw-r--r--contrib/libs/grpc/test/cpp/util/ya.make38
32 files changed, 0 insertions, 6126 deletions
diff --git a/contrib/libs/grpc/test/cpp/README-iOS.md b/contrib/libs/grpc/test/cpp/README-iOS.md
deleted file mode 100644
index 898931085b3..00000000000
--- a/contrib/libs/grpc/test/cpp/README-iOS.md
+++ /dev/null
@@ -1,52 +0,0 @@
-## C++ tests on iOS
-
-[GTMGoogleTestRunner](https://github.com/google/google-toolbox-for-mac/blob/master/UnitTesting/GTMGoogleTestRunner.mm) is used to convert googletest cases to XCTest that can be run on iOS. GTMGoogleTestRunner doesn't execute the `main` function, so we can't have any test logic in `main`.
-However, it's ok to call `::testing::InitGoogleTest` in `main`, as `GTMGoogleTestRunner` [calls InitGoogleTest](https://github.com/google/google-toolbox-for-mac/blob/master/UnitTesting/GTMGoogleTestRunner.mm#L151).
-`grpc::testing::TestEnvironment` can also be called from `main`, as it does some test initialization (install crash handler, seed RNG) that's not strictly required to run testcases on iOS.
-
-
-## Porting exising C++ tests to run on iOS
-
-Please follow these guidelines when porting tests to run on iOS:
-
-- Tests need to use the googletest framework
-- Any setup/teardown code in `main` needs to be moved to `SetUpTestCase`/`TearDownTestCase`, and `TEST` needs to be changed to `TEST_F`.
-- [Death tests](https://github.com/google/googletest/blob/master/googletest/docs/advanced.md#death-tests) are not supported on iOS, so use the `*_IF_SUPPORTED()` macros to ensure that your code compiles on iOS.
-
-For example, the following test
-```c++
-TEST(MyTest, TestOne) {
- ASSERT_DEATH(ThisShouldDie(), "");
-}
-
-int main(int argc, char** argv) {
- grpc::testing::TestEnvironment env(argc, argv);
- ::testing::InitGoogleTest(&argc, argv);
- grpc_init();
- return RUN_ALL_TESTS();
- grpc_shutdown();
-}
-```
-
-should be changed to
-```c++
-class MyTest : public ::testing::Test {
- protected:
- static void SetUpTestCase() { grpc_init(); }
- static void TearDownTestCase() { grpc_shutdown(); }
-};
-
-TEST_F(MyTest, TestOne) {
- ASSERT_DEATH_IF_SUPPORTED(ThisShouldDie(), "");
-}
-
-int main(int argc, char** argv) {
- grpc::testing::TestEnvironment env(argc, argv);
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
-```
-
-## Limitations
-
-Due to a [limitation](https://github.com/google/google-toolbox-for-mac/blob/master/UnitTesting/GTMGoogleTestRunner.mm#L48-L56) in GTMGoogleTestRunner, `SetUpTestCase`/`TeardownTestCase` will be called before/after *every* individual test case, similar to `SetUp`/`TearDown`.
diff --git a/contrib/libs/grpc/test/cpp/end2end/health/ya.make b/contrib/libs/grpc/test/cpp/end2end/health/ya.make
deleted file mode 100644
index 85b03e58d0e..00000000000
--- a/contrib/libs/grpc/test/cpp/end2end/health/ya.make
+++ /dev/null
@@ -1,28 +0,0 @@
-GTEST_UGLY()
-
-ADDINCL(
- ${ARCADIA_BUILD_ROOT}/contrib/libs/grpc
- ${ARCADIA_ROOT}/contrib/libs/grpc
-)
-
-PEERDIR(
- contrib/libs/grpc/src/proto/grpc/health/v1
- contrib/libs/grpc/src/proto/grpc/core
- contrib/libs/grpc/src/proto/grpc/testing
- contrib/libs/grpc/src/proto/grpc/testing/duplicate
- contrib/libs/grpc/test/core/util
- contrib/libs/grpc/test/cpp/end2end
- contrib/libs/grpc/test/cpp/util
-)
-
-NO_COMPILER_WARNINGS()
-
-SRCDIR(
- contrib/libs/grpc/test/cpp/end2end
-)
-
-SRCS(
- health_service_end2end_test.cc
-)
-
-END()
diff --git a/contrib/libs/grpc/test/cpp/end2end/health_service_end2end_test.cc b/contrib/libs/grpc/test/cpp/end2end/health_service_end2end_test.cc
deleted file mode 100644
index 7fad60ddedd..00000000000
--- a/contrib/libs/grpc/test/cpp/end2end/health_service_end2end_test.cc
+++ /dev/null
@@ -1,374 +0,0 @@
-/*
- *
- * Copyright 2016 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include <memory>
-#include <mutex>
-#include <thread>
-#include <vector>
-
-#include <gtest/gtest.h>
-
-#include <grpc/grpc.h>
-#include <grpc/support/log.h>
-#include <grpcpp/channel.h>
-#include <grpcpp/client_context.h>
-#include <grpcpp/create_channel.h>
-#include <grpcpp/ext/health_check_service_server_builder_option.h>
-#include <grpcpp/health_check_service_interface.h>
-#include <grpcpp/server.h>
-#include <grpcpp/server_builder.h>
-#include <grpcpp/server_context.h>
-
-#include "src/proto/grpc/health/v1/health.grpc.pb.h"
-#include "src/proto/grpc/testing/duplicate/echo_duplicate.grpc.pb.h"
-#include "src/proto/grpc/testing/echo.grpc.pb.h"
-#include "test/core/util/port.h"
-#include "test/core/util/test_config.h"
-#include "test/cpp/end2end/test_health_check_service_impl.h"
-#include "test/cpp/end2end/test_service_impl.h"
-
-using grpc::health::v1::Health;
-using grpc::health::v1::HealthCheckRequest;
-using grpc::health::v1::HealthCheckResponse;
-
-namespace grpc {
-namespace testing {
-namespace {
-
-// A custom implementation of the health checking service interface. This is
-// used to test that it prevents the server from creating a default service and
-// also serves as an example of how to override the default service.
-class CustomHealthCheckService : public HealthCheckServiceInterface {
- public:
- explicit CustomHealthCheckService(HealthCheckServiceImpl* impl)
- : impl_(impl) {
- impl_->SetStatus("", HealthCheckResponse::SERVING);
- }
- void SetServingStatus(const TString& service_name,
- bool serving) override {
- impl_->SetStatus(service_name, serving ? HealthCheckResponse::SERVING
- : HealthCheckResponse::NOT_SERVING);
- }
-
- void SetServingStatus(bool serving) override {
- impl_->SetAll(serving ? HealthCheckResponse::SERVING
- : HealthCheckResponse::NOT_SERVING);
- }
-
- void Shutdown() override { impl_->Shutdown(); }
-
- private:
- HealthCheckServiceImpl* impl_; // not owned
-};
-
-class HealthServiceEnd2endTest : public ::testing::Test {
- protected:
- HealthServiceEnd2endTest() {}
-
- void SetUpServer(bool register_sync_test_service, bool add_async_cq,
- bool explicit_health_service,
- std::unique_ptr<HealthCheckServiceInterface> service) {
- int port = 5001; // grpc_pick_unused_port_or_die();
- server_address_ << "localhost:" << port;
-
- bool register_sync_health_service_impl =
- explicit_health_service && service != nullptr;
-
- // Setup server
- ServerBuilder builder;
- if (explicit_health_service) {
- std::unique_ptr<ServerBuilderOption> option(
- new HealthCheckServiceServerBuilderOption(std::move(service)));
- builder.SetOption(std::move(option));
- }
- builder.AddListeningPort(server_address_.str(),
- grpc::InsecureServerCredentials());
- if (register_sync_test_service) {
- // Register a sync service.
- builder.RegisterService(&echo_test_service_);
- }
- if (register_sync_health_service_impl) {
- builder.RegisterService(&health_check_service_impl_);
- }
- if (add_async_cq) {
- cq_ = builder.AddCompletionQueue();
- }
- server_ = builder.BuildAndStart();
- }
-
- void TearDown() override {
- if (server_) {
- server_->Shutdown();
- if (cq_ != nullptr) {
- cq_->Shutdown();
- }
- if (cq_thread_.joinable()) {
- cq_thread_.join();
- }
- }
- }
-
- void ResetStubs() {
- std::shared_ptr<Channel> channel = grpc::CreateChannel(
- server_address_.str(), InsecureChannelCredentials());
- hc_stub_ = grpc::health::v1::Health::NewStub(channel);
- }
-
- // When the expected_status is NOT OK, we do not care about the response.
- void SendHealthCheckRpc(const TString& service_name,
- const Status& expected_status) {
- EXPECT_FALSE(expected_status.ok());
- SendHealthCheckRpc(service_name, expected_status,
- HealthCheckResponse::UNKNOWN);
- }
-
- void SendHealthCheckRpc(
- const TString& service_name, const Status& expected_status,
- HealthCheckResponse::ServingStatus expected_serving_status) {
- HealthCheckRequest request;
- request.set_service(service_name);
- HealthCheckResponse response;
- ClientContext context;
- Status s = hc_stub_->Check(&context, request, &response);
- EXPECT_EQ(expected_status.error_code(), s.error_code());
- if (s.ok()) {
- EXPECT_EQ(expected_serving_status, response.status());
- }
- }
-
- void VerifyHealthCheckService() {
- HealthCheckServiceInterface* service = server_->GetHealthCheckService();
- EXPECT_TRUE(service != nullptr);
- const TString kHealthyService("healthy_service");
- const TString kUnhealthyService("unhealthy_service");
- const TString kNotRegisteredService("not_registered");
- service->SetServingStatus(kHealthyService, true);
- service->SetServingStatus(kUnhealthyService, false);
-
- ResetStubs();
-
- SendHealthCheckRpc("", Status::OK, HealthCheckResponse::SERVING);
- SendHealthCheckRpc(kHealthyService, Status::OK,
- HealthCheckResponse::SERVING);
- SendHealthCheckRpc(kUnhealthyService, Status::OK,
- HealthCheckResponse::NOT_SERVING);
- SendHealthCheckRpc(kNotRegisteredService,
- Status(StatusCode::NOT_FOUND, ""));
-
- service->SetServingStatus(false);
- SendHealthCheckRpc("", Status::OK, HealthCheckResponse::NOT_SERVING);
- SendHealthCheckRpc(kHealthyService, Status::OK,
- HealthCheckResponse::NOT_SERVING);
- SendHealthCheckRpc(kUnhealthyService, Status::OK,
- HealthCheckResponse::NOT_SERVING);
- SendHealthCheckRpc(kNotRegisteredService,
- Status(StatusCode::NOT_FOUND, ""));
- }
-
- void VerifyHealthCheckServiceStreaming() {
- const TString kServiceName("service_name");
- HealthCheckServiceInterface* service = server_->GetHealthCheckService();
- // Start Watch for service.
- ClientContext context;
- HealthCheckRequest request;
- request.set_service(kServiceName);
- std::unique_ptr<::grpc::ClientReaderInterface<HealthCheckResponse>> reader =
- hc_stub_->Watch(&context, request);
- // Initial response will be SERVICE_UNKNOWN.
- HealthCheckResponse response;
- EXPECT_TRUE(reader->Read(&response));
- EXPECT_EQ(response.SERVICE_UNKNOWN, response.status());
- response.Clear();
- // Now set service to NOT_SERVING and make sure we get an update.
- service->SetServingStatus(kServiceName, false);
- EXPECT_TRUE(reader->Read(&response));
- EXPECT_EQ(response.NOT_SERVING, response.status());
- response.Clear();
- // Now set service to SERVING and make sure we get another update.
- service->SetServingStatus(kServiceName, true);
- EXPECT_TRUE(reader->Read(&response));
- EXPECT_EQ(response.SERVING, response.status());
- // Finish call.
- context.TryCancel();
- }
-
- // Verify that after HealthCheckServiceInterface::Shutdown is called
- // 1. unary client will see NOT_SERVING.
- // 2. unary client still sees NOT_SERVING after a SetServing(true) is called.
- // 3. streaming (Watch) client will see an update.
- // 4. setting a new service to serving after shutdown will add the service
- // name but return NOT_SERVING to client.
- // This has to be called last.
- void VerifyHealthCheckServiceShutdown() {
- HealthCheckServiceInterface* service = server_->GetHealthCheckService();
- EXPECT_TRUE(service != nullptr);
- const TString kHealthyService("healthy_service");
- const TString kUnhealthyService("unhealthy_service");
- const TString kNotRegisteredService("not_registered");
- const TString kNewService("add_after_shutdown");
- service->SetServingStatus(kHealthyService, true);
- service->SetServingStatus(kUnhealthyService, false);
-
- ResetStubs();
-
- // Start Watch for service.
- ClientContext context;
- HealthCheckRequest request;
- request.set_service(kHealthyService);
- std::unique_ptr<::grpc::ClientReaderInterface<HealthCheckResponse>> reader =
- hc_stub_->Watch(&context, request);
-
- HealthCheckResponse response;
- EXPECT_TRUE(reader->Read(&response));
- EXPECT_EQ(response.SERVING, response.status());
-
- SendHealthCheckRpc("", Status::OK, HealthCheckResponse::SERVING);
- SendHealthCheckRpc(kHealthyService, Status::OK,
- HealthCheckResponse::SERVING);
- SendHealthCheckRpc(kUnhealthyService, Status::OK,
- HealthCheckResponse::NOT_SERVING);
- SendHealthCheckRpc(kNotRegisteredService,
- Status(StatusCode::NOT_FOUND, ""));
- SendHealthCheckRpc(kNewService, Status(StatusCode::NOT_FOUND, ""));
-
- // Shutdown health check service.
- service->Shutdown();
-
- // Watch client gets another update.
- EXPECT_TRUE(reader->Read(&response));
- EXPECT_EQ(response.NOT_SERVING, response.status());
- // Finish Watch call.
- context.TryCancel();
-
- SendHealthCheckRpc("", Status::OK, HealthCheckResponse::NOT_SERVING);
- SendHealthCheckRpc(kHealthyService, Status::OK,
- HealthCheckResponse::NOT_SERVING);
- SendHealthCheckRpc(kUnhealthyService, Status::OK,
- HealthCheckResponse::NOT_SERVING);
- SendHealthCheckRpc(kNotRegisteredService,
- Status(StatusCode::NOT_FOUND, ""));
-
- // Setting status after Shutdown has no effect.
- service->SetServingStatus(kHealthyService, true);
- SendHealthCheckRpc(kHealthyService, Status::OK,
- HealthCheckResponse::NOT_SERVING);
-
- // Adding serving status for a new service after shutdown will return
- // NOT_SERVING.
- service->SetServingStatus(kNewService, true);
- SendHealthCheckRpc(kNewService, Status::OK,
- HealthCheckResponse::NOT_SERVING);
- }
-
- TestServiceImpl echo_test_service_;
- HealthCheckServiceImpl health_check_service_impl_;
- std::unique_ptr<Health::Stub> hc_stub_;
- std::unique_ptr<ServerCompletionQueue> cq_;
- std::unique_ptr<Server> server_;
- std::ostringstream server_address_;
- std::thread cq_thread_;
-};
-
-TEST_F(HealthServiceEnd2endTest, DefaultHealthServiceDisabled) {
- EnableDefaultHealthCheckService(false);
- EXPECT_FALSE(DefaultHealthCheckServiceEnabled());
- SetUpServer(true, false, false, nullptr);
- HealthCheckServiceInterface* default_service =
- server_->GetHealthCheckService();
- EXPECT_TRUE(default_service == nullptr);
-
- ResetStubs();
-
- SendHealthCheckRpc("", Status(StatusCode::UNIMPLEMENTED, ""));
-}
-
-TEST_F(HealthServiceEnd2endTest, DefaultHealthService) {
- EnableDefaultHealthCheckService(true);
- EXPECT_TRUE(DefaultHealthCheckServiceEnabled());
- SetUpServer(true, false, false, nullptr);
- VerifyHealthCheckService();
- VerifyHealthCheckServiceStreaming();
-
- // The default service has a size limit of the service name.
- const TString kTooLongServiceName(201, 'x');
- SendHealthCheckRpc(kTooLongServiceName,
- Status(StatusCode::INVALID_ARGUMENT, ""));
-}
-
-TEST_F(HealthServiceEnd2endTest, DefaultHealthServiceShutdown) {
- EnableDefaultHealthCheckService(true);
- EXPECT_TRUE(DefaultHealthCheckServiceEnabled());
- SetUpServer(true, false, false, nullptr);
- VerifyHealthCheckServiceShutdown();
-}
-
-// Provide an empty service to disable the default service.
-TEST_F(HealthServiceEnd2endTest, ExplicitlyDisableViaOverride) {
- EnableDefaultHealthCheckService(true);
- EXPECT_TRUE(DefaultHealthCheckServiceEnabled());
- std::unique_ptr<HealthCheckServiceInterface> empty_service;
- SetUpServer(true, false, true, std::move(empty_service));
- HealthCheckServiceInterface* service = server_->GetHealthCheckService();
- EXPECT_TRUE(service == nullptr);
-
- ResetStubs();
-
- SendHealthCheckRpc("", Status(StatusCode::UNIMPLEMENTED, ""));
-}
-
-// Provide an explicit override of health checking service interface.
-TEST_F(HealthServiceEnd2endTest, ExplicitlyOverride) {
- EnableDefaultHealthCheckService(true);
- EXPECT_TRUE(DefaultHealthCheckServiceEnabled());
- std::unique_ptr<HealthCheckServiceInterface> override_service(
- new CustomHealthCheckService(&health_check_service_impl_));
- HealthCheckServiceInterface* underlying_service = override_service.get();
- SetUpServer(false, false, true, std::move(override_service));
- HealthCheckServiceInterface* service = server_->GetHealthCheckService();
- EXPECT_TRUE(service == underlying_service);
-
- ResetStubs();
-
- VerifyHealthCheckService();
- VerifyHealthCheckServiceStreaming();
-}
-
-TEST_F(HealthServiceEnd2endTest, ExplicitlyHealthServiceShutdown) {
- EnableDefaultHealthCheckService(true);
- EXPECT_TRUE(DefaultHealthCheckServiceEnabled());
- std::unique_ptr<HealthCheckServiceInterface> override_service(
- new CustomHealthCheckService(&health_check_service_impl_));
- HealthCheckServiceInterface* underlying_service = override_service.get();
- SetUpServer(false, false, true, std::move(override_service));
- HealthCheckServiceInterface* service = server_->GetHealthCheckService();
- EXPECT_TRUE(service == underlying_service);
-
- ResetStubs();
-
- VerifyHealthCheckServiceShutdown();
-}
-
-} // namespace
-} // namespace testing
-} // namespace grpc
-
-int main(int argc, char** argv) {
- grpc::testing::TestEnvironment env(argc, argv);
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/contrib/libs/grpc/test/cpp/end2end/interceptors_util.cc b/contrib/libs/grpc/test/cpp/end2end/interceptors_util.cc
deleted file mode 100644
index b6369347507..00000000000
--- a/contrib/libs/grpc/test/cpp/end2end/interceptors_util.cc
+++ /dev/null
@@ -1,216 +0,0 @@
-/*
- *
- * Copyright 2018 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include "test/cpp/end2end/interceptors_util.h"
-
-#include "y_absl/memory/memory.h"
-
-#include <util/string/cast.h>
-
-namespace grpc {
-namespace testing {
-
-std::atomic<int> PhonyInterceptor::num_times_run_;
-std::atomic<int> PhonyInterceptor::num_times_run_reverse_;
-std::atomic<int> PhonyInterceptor::num_times_cancel_;
-
-void MakeCall(const std::shared_ptr<Channel>& channel,
- const StubOptions& options) {
- auto stub = grpc::testing::EchoTestService::NewStub(channel, options);
- ClientContext ctx;
- EchoRequest req;
- req.mutable_param()->set_echo_metadata(true);
- ctx.AddMetadata("testkey", "testvalue");
- req.set_message("Hello");
- EchoResponse resp;
- Status s = stub->Echo(&ctx, req, &resp);
- EXPECT_EQ(s.ok(), true);
- EXPECT_EQ(resp.message(), "Hello");
-}
-
-void MakeClientStreamingCall(const std::shared_ptr<Channel>& channel) {
- auto stub = grpc::testing::EchoTestService::NewStub(channel);
- ClientContext ctx;
- EchoRequest req;
- req.mutable_param()->set_echo_metadata(true);
- ctx.AddMetadata("testkey", "testvalue");
- req.set_message("Hello");
- EchoResponse resp;
- string expected_resp = "";
- auto writer = stub->RequestStream(&ctx, &resp);
- for (int i = 0; i < kNumStreamingMessages; i++) {
- writer->Write(req);
- expected_resp += "Hello";
- }
- writer->WritesDone();
- Status s = writer->Finish();
- EXPECT_EQ(s.ok(), true);
- EXPECT_EQ(resp.message(), expected_resp);
-}
-
-void MakeServerStreamingCall(const std::shared_ptr<Channel>& channel) {
- auto stub = grpc::testing::EchoTestService::NewStub(channel);
- ClientContext ctx;
- EchoRequest req;
- req.mutable_param()->set_echo_metadata(true);
- ctx.AddMetadata("testkey", "testvalue");
- req.set_message("Hello");
- EchoResponse resp;
- auto reader = stub->ResponseStream(&ctx, req);
- int count = 0;
- while (reader->Read(&resp)) {
- EXPECT_EQ(resp.message(), "Hello");
- count++;
- }
- ASSERT_EQ(count, kNumStreamingMessages);
- Status s = reader->Finish();
- EXPECT_EQ(s.ok(), true);
-}
-
-void MakeBidiStreamingCall(const std::shared_ptr<Channel>& channel) {
- auto stub = grpc::testing::EchoTestService::NewStub(channel);
- ClientContext ctx;
- EchoRequest req;
- EchoResponse resp;
- ctx.AddMetadata("testkey", "testvalue");
- req.mutable_param()->set_echo_metadata(true);
- auto stream = stub->BidiStream(&ctx);
- for (auto i = 0; i < kNumStreamingMessages; i++) {
- req.set_message(TString("Hello") + ::ToString(i));
- stream->Write(req);
- stream->Read(&resp);
- EXPECT_EQ(req.message(), resp.message());
- }
- ASSERT_TRUE(stream->WritesDone());
- Status s = stream->Finish();
- EXPECT_EQ(s.ok(), true);
-}
-
-void MakeAsyncCQCall(const std::shared_ptr<Channel>& channel) {
- auto stub = grpc::testing::EchoTestService::NewStub(channel);
- CompletionQueue cq;
- EchoRequest send_request;
- EchoResponse recv_response;
- Status recv_status;
- ClientContext cli_ctx;
-
- send_request.set_message("Hello");
- cli_ctx.AddMetadata("testkey", "testvalue");
- std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader(
- stub->AsyncEcho(&cli_ctx, send_request, &cq));
- response_reader->Finish(&recv_response, &recv_status, tag(1));
- Verifier().Expect(1, true).Verify(&cq);
- EXPECT_EQ(send_request.message(), recv_response.message());
- EXPECT_TRUE(recv_status.ok());
-}
-
-void MakeAsyncCQClientStreamingCall(
- const std::shared_ptr<Channel>& /*channel*/) {
- // TODO(yashykt) : Fill this out
-}
-
-void MakeAsyncCQServerStreamingCall(const std::shared_ptr<Channel>& channel) {
- auto stub = grpc::testing::EchoTestService::NewStub(channel);
- CompletionQueue cq;
- EchoRequest send_request;
- EchoResponse recv_response;
- Status recv_status;
- ClientContext cli_ctx;
-
- cli_ctx.AddMetadata("testkey", "testvalue");
- send_request.set_message("Hello");
- std::unique_ptr<ClientAsyncReader<EchoResponse>> cli_stream(
- stub->AsyncResponseStream(&cli_ctx, send_request, &cq, tag(1)));
- Verifier().Expect(1, true).Verify(&cq);
- // Read the expected number of messages
- for (int i = 0; i < kNumStreamingMessages; i++) {
- cli_stream->Read(&recv_response, tag(2));
- Verifier().Expect(2, true).Verify(&cq);
- ASSERT_EQ(recv_response.message(), send_request.message());
- }
- // The next read should fail
- cli_stream->Read(&recv_response, tag(3));
- Verifier().Expect(3, false).Verify(&cq);
- // Get the status
- cli_stream->Finish(&recv_status, tag(4));
- Verifier().Expect(4, true).Verify(&cq);
- EXPECT_TRUE(recv_status.ok());
-}
-
-void MakeAsyncCQBidiStreamingCall(const std::shared_ptr<Channel>& /*channel*/) {
- // TODO(yashykt) : Fill this out
-}
-
-void MakeCallbackCall(const std::shared_ptr<Channel>& channel) {
- auto stub = grpc::testing::EchoTestService::NewStub(channel);
- ClientContext ctx;
- EchoRequest req;
- std::mutex mu;
- std::condition_variable cv;
- bool done = false;
- req.mutable_param()->set_echo_metadata(true);
- ctx.AddMetadata("testkey", "testvalue");
- req.set_message("Hello");
- EchoResponse resp;
- stub->async()->Echo(&ctx, &req, &resp, [&resp, &mu, &done, &cv](Status s) {
- EXPECT_EQ(s.ok(), true);
- EXPECT_EQ(resp.message(), "Hello");
- std::lock_guard<std::mutex> l(mu);
- done = true;
- cv.notify_one();
- });
- std::unique_lock<std::mutex> l(mu);
- while (!done) {
- cv.wait(l);
- }
-}
-
-bool CheckMetadata(const std::multimap<grpc::string_ref, grpc::string_ref>& map,
- const string& key, const string& value) {
- for (const auto& pair : map) {
- if (pair.first.starts_with(key) && pair.second.starts_with(value)) {
- return true;
- }
- }
- return false;
-}
-
-bool CheckMetadata(const std::multimap<TString, TString>& map,
- const string& key, const string& value) {
- for (const auto& pair : map) {
- if (pair.first == key.c_str() && pair.second == value.c_str()) {
- return true;
- }
- }
- return false;
-}
-
-std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
-CreatePhonyClientInterceptors() {
- std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
- creators;
- // Add 20 phony interceptors before hijacking interceptor
- creators.reserve(20);
- for (auto i = 0; i < 20; i++) {
- creators.push_back(y_absl::make_unique<PhonyInterceptorFactory>());
- }
- return creators;
-}
-
-} // namespace testing
-} // namespace grpc
diff --git a/contrib/libs/grpc/test/cpp/end2end/interceptors_util.h b/contrib/libs/grpc/test/cpp/end2end/interceptors_util.h
deleted file mode 100644
index 3603fa2a14b..00000000000
--- a/contrib/libs/grpc/test/cpp/end2end/interceptors_util.h
+++ /dev/null
@@ -1,354 +0,0 @@
-/*
- *
- * Copyright 2018 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include <condition_variable>
-
-#include <gtest/gtest.h>
-
-#include <grpcpp/channel.h>
-
-#include "src/proto/grpc/testing/echo.grpc.pb.h"
-#include "test/cpp/util/string_ref_helper.h"
-
-namespace grpc {
-namespace testing {
-/* This interceptor does nothing. Just keeps a global count on the number of
- * times it was invoked. */
-class PhonyInterceptor : public experimental::Interceptor {
- public:
- PhonyInterceptor() {}
-
- void Intercept(experimental::InterceptorBatchMethods* methods) override {
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_SEND_INITIAL_METADATA)) {
- num_times_run_++;
- } else if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::
- POST_RECV_INITIAL_METADATA)) {
- num_times_run_reverse_++;
- } else if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_SEND_CANCEL)) {
- num_times_cancel_++;
- }
- methods->Proceed();
- }
-
- static void Reset() {
- num_times_run_.store(0);
- num_times_run_reverse_.store(0);
- num_times_cancel_.store(0);
- }
-
- static int GetNumTimesRun() {
- EXPECT_EQ(num_times_run_.load(), num_times_run_reverse_.load());
- return num_times_run_.load();
- }
-
- static int GetNumTimesCancel() { return num_times_cancel_.load(); }
-
- private:
- static std::atomic<int> num_times_run_;
- static std::atomic<int> num_times_run_reverse_;
- static std::atomic<int> num_times_cancel_;
-};
-
-class PhonyInterceptorFactory
- : public experimental::ClientInterceptorFactoryInterface,
- public experimental::ServerInterceptorFactoryInterface {
- public:
- experimental::Interceptor* CreateClientInterceptor(
- experimental::ClientRpcInfo* /*info*/) override {
- return new PhonyInterceptor();
- }
-
- experimental::Interceptor* CreateServerInterceptor(
- experimental::ServerRpcInfo* /*info*/) override {
- return new PhonyInterceptor();
- }
-};
-
-/* This interceptor can be used to test the interception mechanism. */
-class TestInterceptor : public experimental::Interceptor {
- public:
- TestInterceptor(const TString& method, const char* suffix_for_stats,
- experimental::ClientRpcInfo* info) {
- EXPECT_EQ(info->method(), method);
-
- if (suffix_for_stats == nullptr || info->suffix_for_stats() == nullptr) {
- EXPECT_EQ(info->suffix_for_stats(), suffix_for_stats);
- } else {
- EXPECT_EQ(strcmp(info->suffix_for_stats(), suffix_for_stats), 0);
- }
- }
-
- void Intercept(experimental::InterceptorBatchMethods* methods) override {
- methods->Proceed();
- }
-};
-
-class TestInterceptorFactory
- : public experimental::ClientInterceptorFactoryInterface {
- public:
- TestInterceptorFactory(const TString& method,
- const char* suffix_for_stats)
- : method_(method), suffix_for_stats_(suffix_for_stats) {}
-
- experimental::Interceptor* CreateClientInterceptor(
- experimental::ClientRpcInfo* info) override {
- return new TestInterceptor(method_, suffix_for_stats_, info);
- }
-
- private:
- TString method_;
- const char* suffix_for_stats_;
-};
-
-/* This interceptor factory returns nullptr on interceptor creation */
-class NullInterceptorFactory
- : public experimental::ClientInterceptorFactoryInterface,
- public experimental::ServerInterceptorFactoryInterface {
- public:
- experimental::Interceptor* CreateClientInterceptor(
- experimental::ClientRpcInfo* /*info*/) override {
- return nullptr;
- }
-
- experimental::Interceptor* CreateServerInterceptor(
- experimental::ServerRpcInfo* /*info*/) override {
- return nullptr;
- }
-};
-
-class EchoTestServiceStreamingImpl : public EchoTestService::Service {
- public:
- ~EchoTestServiceStreamingImpl() override {}
-
- Status Echo(ServerContext* context, const EchoRequest* request,
- EchoResponse* response) override {
- auto client_metadata = context->client_metadata();
- for (const auto& pair : client_metadata) {
- context->AddTrailingMetadata(ToString(pair.first), ToString(pair.second));
- }
- response->set_message(request->message());
- return Status::OK;
- }
-
- Status BidiStream(
- ServerContext* context,
- grpc::ServerReaderWriter<EchoResponse, EchoRequest>* stream) override {
- EchoRequest req;
- EchoResponse resp;
- auto client_metadata = context->client_metadata();
- for (const auto& pair : client_metadata) {
- context->AddTrailingMetadata(ToString(pair.first), ToString(pair.second));
- }
-
- while (stream->Read(&req)) {
- resp.set_message(req.message());
- EXPECT_TRUE(stream->Write(resp, grpc::WriteOptions()));
- }
- return Status::OK;
- }
-
- Status RequestStream(ServerContext* context,
- ServerReader<EchoRequest>* reader,
- EchoResponse* resp) override {
- auto client_metadata = context->client_metadata();
- for (const auto& pair : client_metadata) {
- context->AddTrailingMetadata(ToString(pair.first), ToString(pair.second));
- }
-
- EchoRequest req;
- string response_str = "";
- while (reader->Read(&req)) {
- response_str += req.message();
- }
- resp->set_message(response_str);
- return Status::OK;
- }
-
- Status ResponseStream(ServerContext* context, const EchoRequest* req,
- ServerWriter<EchoResponse>* writer) override {
- auto client_metadata = context->client_metadata();
- for (const auto& pair : client_metadata) {
- context->AddTrailingMetadata(ToString(pair.first), ToString(pair.second));
- }
-
- EchoResponse resp;
- resp.set_message(req->message());
- for (int i = 0; i < 10; i++) {
- EXPECT_TRUE(writer->Write(resp));
- }
- return Status::OK;
- }
-};
-
-constexpr int kNumStreamingMessages = 10;
-
-void MakeCall(const std::shared_ptr<Channel>& channel,
- const StubOptions& options = StubOptions());
-
-void MakeClientStreamingCall(const std::shared_ptr<Channel>& channel);
-
-void MakeServerStreamingCall(const std::shared_ptr<Channel>& channel);
-
-void MakeBidiStreamingCall(const std::shared_ptr<Channel>& channel);
-
-void MakeAsyncCQCall(const std::shared_ptr<Channel>& channel);
-
-void MakeAsyncCQClientStreamingCall(const std::shared_ptr<Channel>& channel);
-
-void MakeAsyncCQServerStreamingCall(const std::shared_ptr<Channel>& channel);
-
-void MakeAsyncCQBidiStreamingCall(const std::shared_ptr<Channel>& channel);
-
-void MakeCallbackCall(const std::shared_ptr<Channel>& channel);
-
-bool CheckMetadata(const std::multimap<grpc::string_ref, grpc::string_ref>& map,
- const string& key, const string& value);
-
-bool CheckMetadata(const std::multimap<TString, TString>& map,
- const string& key, const string& value);
-
-std::vector<std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
-CreatePhonyClientInterceptors();
-
-inline void* tag(int i) { return reinterpret_cast<void*>(i); }
-inline int detag(void* p) {
- return static_cast<int>(reinterpret_cast<intptr_t>(p));
-}
-
-class Verifier {
- public:
- Verifier() : lambda_run_(false) {}
- // Expect sets the expected ok value for a specific tag
- Verifier& Expect(int i, bool expect_ok) {
- return ExpectUnless(i, expect_ok, false);
- }
- // ExpectUnless sets the expected ok value for a specific tag
- // unless the tag was already marked seen (as a result of ExpectMaybe)
- Verifier& ExpectUnless(int i, bool expect_ok, bool seen) {
- if (!seen) {
- expectations_[tag(i)] = expect_ok;
- }
- return *this;
- }
- // ExpectMaybe sets the expected ok value for a specific tag, but does not
- // require it to appear
- // If it does, sets *seen to true
- Verifier& ExpectMaybe(int i, bool expect_ok, bool* seen) {
- if (!*seen) {
- maybe_expectations_[tag(i)] = MaybeExpect{expect_ok, seen};
- }
- return *this;
- }
-
- // Next waits for 1 async tag to complete, checks its
- // expectations, and returns the tag
- int Next(CompletionQueue* cq, bool ignore_ok) {
- bool ok;
- void* got_tag;
- EXPECT_TRUE(cq->Next(&got_tag, &ok));
- GotTag(got_tag, ok, ignore_ok);
- return detag(got_tag);
- }
-
- template <typename T>
- CompletionQueue::NextStatus DoOnceThenAsyncNext(
- CompletionQueue* cq, void** got_tag, bool* ok, T deadline,
- std::function<void(void)> lambda) {
- if (lambda_run_) {
- return cq->AsyncNext(got_tag, ok, deadline);
- } else {
- lambda_run_ = true;
- return cq->DoThenAsyncNext(lambda, got_tag, ok, deadline);
- }
- }
-
- // Verify keeps calling Next until all currently set
- // expected tags are complete
- void Verify(CompletionQueue* cq) { Verify(cq, false); }
-
- // This version of Verify allows optionally ignoring the
- // outcome of the expectation
- void Verify(CompletionQueue* cq, bool ignore_ok) {
- GPR_ASSERT(!expectations_.empty() || !maybe_expectations_.empty());
- while (!expectations_.empty()) {
- Next(cq, ignore_ok);
- }
- }
-
- // This version of Verify stops after a certain deadline, and uses the
- // DoThenAsyncNext API
- // to call the lambda
- void Verify(CompletionQueue* cq,
- std::chrono::system_clock::time_point deadline,
- const std::function<void(void)>& lambda) {
- if (expectations_.empty()) {
- bool ok;
- void* got_tag;
- EXPECT_EQ(DoOnceThenAsyncNext(cq, &got_tag, &ok, deadline, lambda),
- CompletionQueue::TIMEOUT);
- } else {
- while (!expectations_.empty()) {
- bool ok;
- void* got_tag;
- EXPECT_EQ(DoOnceThenAsyncNext(cq, &got_tag, &ok, deadline, lambda),
- CompletionQueue::GOT_EVENT);
- GotTag(got_tag, ok, false);
- }
- }
- }
-
- private:
- void GotTag(void* got_tag, bool ok, bool ignore_ok) {
- auto it = expectations_.find(got_tag);
- if (it != expectations_.end()) {
- if (!ignore_ok) {
- EXPECT_EQ(it->second, ok);
- }
- expectations_.erase(it);
- } else {
- auto it2 = maybe_expectations_.find(got_tag);
- if (it2 != maybe_expectations_.end()) {
- if (it2->second.seen != nullptr) {
- EXPECT_FALSE(*it2->second.seen);
- *it2->second.seen = true;
- }
- if (!ignore_ok) {
- EXPECT_EQ(it2->second.ok, ok);
- }
- } else {
- gpr_log(GPR_ERROR, "Unexpected tag: %p", got_tag);
- abort();
- }
- }
- }
-
- struct MaybeExpect {
- bool ok;
- bool* seen;
- };
-
- std::map<void*, bool> expectations_;
- std::map<void*, MaybeExpect> maybe_expectations_;
- bool lambda_run_;
-};
-
-} // namespace testing
-} // namespace grpc
diff --git a/contrib/libs/grpc/test/cpp/end2end/server_interceptors/ya.make b/contrib/libs/grpc/test/cpp/end2end/server_interceptors/ya.make
deleted file mode 100644
index 2bdf076b4a9..00000000000
--- a/contrib/libs/grpc/test/cpp/end2end/server_interceptors/ya.make
+++ /dev/null
@@ -1,27 +0,0 @@
-GTEST_UGLY()
-
-ADDINCL(
- ${ARCADIA_BUILD_ROOT}/contrib/libs/grpc
- ${ARCADIA_ROOT}/contrib/libs/grpc
-)
-
-PEERDIR(
- contrib/libs/grpc/src/proto/grpc/core
- contrib/libs/grpc/src/proto/grpc/testing
- contrib/libs/grpc/src/proto/grpc/testing/duplicate
- contrib/libs/grpc/test/core/util
- contrib/libs/grpc/test/cpp/end2end
- contrib/libs/grpc/test/cpp/util
-)
-
-NO_COMPILER_WARNINGS()
-
-SRCDIR(
- contrib/libs/grpc/test/cpp/end2end
-)
-
-SRCS(
- server_interceptors_end2end_test.cc
-)
-
-END()
diff --git a/contrib/libs/grpc/test/cpp/end2end/server_interceptors_end2end_test.cc b/contrib/libs/grpc/test/cpp/end2end/server_interceptors_end2end_test.cc
deleted file mode 100644
index 5b631a1359e..00000000000
--- a/contrib/libs/grpc/test/cpp/end2end/server_interceptors_end2end_test.cc
+++ /dev/null
@@ -1,703 +0,0 @@
-/*
- *
- * Copyright 2018 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include <memory>
-#include <vector>
-
-#include <gtest/gtest.h>
-
-#include "y_absl/memory/memory.h"
-#include "y_absl/strings/match.h"
-
-#include <grpcpp/channel.h>
-#include <grpcpp/client_context.h>
-#include <grpcpp/create_channel.h>
-#include <grpcpp/generic/generic_stub.h>
-#include <grpcpp/impl/codegen/proto_utils.h>
-#include <grpcpp/server.h>
-#include <grpcpp/server_builder.h>
-#include <grpcpp/server_context.h>
-#include <grpcpp/support/server_interceptor.h>
-
-#include "src/proto/grpc/testing/echo.grpc.pb.h"
-#include "test/core/util/port.h"
-#include "test/core/util/test_config.h"
-#include "test/cpp/end2end/interceptors_util.h"
-#include "test/cpp/end2end/test_service_impl.h"
-#include "test/cpp/util/byte_buffer_proto_helper.h"
-
-namespace grpc {
-namespace testing {
-namespace {
-
-class LoggingInterceptor : public experimental::Interceptor {
- public:
- explicit LoggingInterceptor(experimental::ServerRpcInfo* info) {
- info_ = info;
-
- // Check the method name and compare to the type
- const char* method = info->method();
- experimental::ServerRpcInfo::Type type = info->type();
-
- // Check that we use one of our standard methods with expected type.
- // Also allow the health checking service.
- // We accept BIDI_STREAMING for Echo in case it's an AsyncGenericService
- // being tested (the GenericRpc test).
- // The empty method is for the Unimplemented requests that arise
- // when draining the CQ.
- EXPECT_TRUE(
- strstr(method, "/grpc.health") == method ||
- (strcmp(method, "/grpc.testing.EchoTestService/Echo") == 0 &&
- (type == experimental::ServerRpcInfo::Type::UNARY ||
- type == experimental::ServerRpcInfo::Type::BIDI_STREAMING)) ||
- (strcmp(method, "/grpc.testing.EchoTestService/RequestStream") == 0 &&
- type == experimental::ServerRpcInfo::Type::CLIENT_STREAMING) ||
- (strcmp(method, "/grpc.testing.EchoTestService/ResponseStream") == 0 &&
- type == experimental::ServerRpcInfo::Type::SERVER_STREAMING) ||
- (strcmp(method, "/grpc.testing.EchoTestService/BidiStream") == 0 &&
- type == experimental::ServerRpcInfo::Type::BIDI_STREAMING) ||
- strcmp(method, "/grpc.testing.EchoTestService/Unimplemented") == 0 ||
- (strcmp(method, "") == 0 &&
- type == experimental::ServerRpcInfo::Type::BIDI_STREAMING));
- }
-
- void Intercept(experimental::InterceptorBatchMethods* methods) override {
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_SEND_INITIAL_METADATA)) {
- auto* map = methods->GetSendInitialMetadata();
- // Got nothing better to do here for now
- EXPECT_EQ(map->size(), static_cast<unsigned>(0));
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_SEND_MESSAGE)) {
- EchoRequest req;
- auto* buffer = methods->GetSerializedSendMessage();
- auto copied_buffer = *buffer;
- EXPECT_TRUE(
- SerializationTraits<EchoRequest>::Deserialize(&copied_buffer, &req)
- .ok());
- EXPECT_TRUE(req.message().find("Hello") == 0);
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_SEND_STATUS)) {
- auto* map = methods->GetSendTrailingMetadata();
- bool found = false;
- // Check that we received the metadata as an echo
- for (const auto& pair : *map) {
- found = y_absl::StartsWith(pair.first, "testkey") &&
- y_absl::StartsWith(pair.second, "testvalue");
- if (found) break;
- }
- EXPECT_EQ(found, true);
- auto status = methods->GetSendStatus();
- EXPECT_EQ(status.ok(), true);
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::POST_RECV_INITIAL_METADATA)) {
- auto* map = methods->GetRecvInitialMetadata();
- bool found = false;
- // Check that we received the metadata as an echo
- for (const auto& pair : *map) {
- found = pair.first.find("testkey") == 0 &&
- pair.second.find("testvalue") == 0;
- if (found) break;
- }
- EXPECT_EQ(found, true);
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::POST_RECV_MESSAGE)) {
- EchoResponse* resp =
- static_cast<EchoResponse*>(methods->GetRecvMessage());
- if (resp != nullptr) {
- EXPECT_TRUE(resp->message().find("Hello") == 0);
- }
- }
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::POST_RECV_CLOSE)) {
- // Got nothing interesting to do here
- }
- methods->Proceed();
- }
-
- private:
- experimental::ServerRpcInfo* info_;
-};
-
-class LoggingInterceptorFactory
- : public experimental::ServerInterceptorFactoryInterface {
- public:
- experimental::Interceptor* CreateServerInterceptor(
- experimental::ServerRpcInfo* info) override {
- return new LoggingInterceptor(info);
- }
-};
-
-// Test if SendMessage function family works as expected for sync/callback apis
-class SyncSendMessageTester : public experimental::Interceptor {
- public:
- explicit SyncSendMessageTester(experimental::ServerRpcInfo* /*info*/) {}
-
- void Intercept(experimental::InterceptorBatchMethods* methods) override {
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_SEND_MESSAGE)) {
- string old_msg =
- static_cast<const EchoRequest*>(methods->GetSendMessage())->message();
- EXPECT_EQ(old_msg.find("Hello"), 0u);
- new_msg_.set_message(TString("World" + old_msg).c_str());
- methods->ModifySendMessage(&new_msg_);
- }
- methods->Proceed();
- }
-
- private:
- EchoRequest new_msg_;
-};
-
-class SyncSendMessageTesterFactory
- : public experimental::ServerInterceptorFactoryInterface {
- public:
- experimental::Interceptor* CreateServerInterceptor(
- experimental::ServerRpcInfo* info) override {
- return new SyncSendMessageTester(info);
- }
-};
-
-// Test if SendMessage function family works as expected for sync/callback apis
-class SyncSendMessageVerifier : public experimental::Interceptor {
- public:
- explicit SyncSendMessageVerifier(experimental::ServerRpcInfo* /*info*/) {}
-
- void Intercept(experimental::InterceptorBatchMethods* methods) override {
- if (methods->QueryInterceptionHookPoint(
- experimental::InterceptionHookPoints::PRE_SEND_MESSAGE)) {
- // Make sure that the changes made in SyncSendMessageTester persisted
- string old_msg =
- static_cast<const EchoRequest*>(methods->GetSendMessage())->message();
- EXPECT_EQ(old_msg.find("World"), 0u);
-
- // Remove the "World" part of the string that we added earlier
- new_msg_.set_message(old_msg.erase(0, 5));
- methods->ModifySendMessage(&new_msg_);
-
- // LoggingInterceptor verifies that changes got reverted
- }
- methods->Proceed();
- }
-
- private:
- EchoRequest new_msg_;
-};
-
-class SyncSendMessageVerifierFactory
- : public experimental::ServerInterceptorFactoryInterface {
- public:
- experimental::Interceptor* CreateServerInterceptor(
- experimental::ServerRpcInfo* info) override {
- return new SyncSendMessageVerifier(info);
- }
-};
-
-void MakeBidiStreamingCall(const std::shared_ptr<Channel>& channel) {
- auto stub = grpc::testing::EchoTestService::NewStub(channel);
- ClientContext ctx;
- EchoRequest req;
- EchoResponse resp;
- ctx.AddMetadata("testkey", "testvalue");
- auto stream = stub->BidiStream(&ctx);
- for (auto i = 0; i < 10; i++) {
- req.set_message("Hello" + ::ToString(i));
- stream->Write(req);
- stream->Read(&resp);
- EXPECT_EQ(req.message(), resp.message());
- }
- ASSERT_TRUE(stream->WritesDone());
- Status s = stream->Finish();
- EXPECT_EQ(s.ok(), true);
-}
-
-class ServerInterceptorsEnd2endSyncUnaryTest : public ::testing::Test {
- protected:
- ServerInterceptorsEnd2endSyncUnaryTest() {
- int port = 5004; // grpc_pick_unused_port_or_die();
-
- ServerBuilder builder;
- server_address_ = "localhost:" + ::ToString(port);
- builder.AddListeningPort(server_address_, InsecureServerCredentials());
- builder.RegisterService(&service_);
-
- std::vector<
- std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
- creators;
- creators.push_back(
- std::unique_ptr<experimental::ServerInterceptorFactoryInterface>(
- new SyncSendMessageTesterFactory()));
- creators.push_back(
- std::unique_ptr<experimental::ServerInterceptorFactoryInterface>(
- new SyncSendMessageVerifierFactory()));
- creators.push_back(
- std::unique_ptr<experimental::ServerInterceptorFactoryInterface>(
- new LoggingInterceptorFactory()));
- // Add 20 phony interceptor factories and null interceptor factories
- for (auto i = 0; i < 20; i++) {
- creators.push_back(y_absl::make_unique<PhonyInterceptorFactory>());
- creators.push_back(y_absl::make_unique<NullInterceptorFactory>());
- }
- builder.experimental().SetInterceptorCreators(std::move(creators));
- server_ = builder.BuildAndStart();
- }
- TString server_address_;
- TestServiceImpl service_;
- std::unique_ptr<Server> server_;
-};
-
-TEST_F(ServerInterceptorsEnd2endSyncUnaryTest, UnaryTest) {
- ChannelArguments args;
- PhonyInterceptor::Reset();
- auto channel =
- grpc::CreateChannel(server_address_, InsecureChannelCredentials());
- MakeCall(channel);
- // Make sure all 20 phony interceptors were run
- EXPECT_EQ(PhonyInterceptor::GetNumTimesRun(), 20);
-}
-
-class ServerInterceptorsEnd2endSyncStreamingTest : public ::testing::Test {
- protected:
- ServerInterceptorsEnd2endSyncStreamingTest() {
- int port = 5005; // grpc_pick_unused_port_or_die();
-
- ServerBuilder builder;
- server_address_ = "localhost:" + ::ToString(port);
- builder.AddListeningPort(server_address_, InsecureServerCredentials());
- builder.RegisterService(&service_);
-
- std::vector<
- std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
- creators;
- creators.push_back(
- std::unique_ptr<experimental::ServerInterceptorFactoryInterface>(
- new SyncSendMessageTesterFactory()));
- creators.push_back(
- std::unique_ptr<experimental::ServerInterceptorFactoryInterface>(
- new SyncSendMessageVerifierFactory()));
- creators.push_back(
- std::unique_ptr<experimental::ServerInterceptorFactoryInterface>(
- new LoggingInterceptorFactory()));
- for (auto i = 0; i < 20; i++) {
- creators.push_back(y_absl::make_unique<PhonyInterceptorFactory>());
- }
- builder.experimental().SetInterceptorCreators(std::move(creators));
- server_ = builder.BuildAndStart();
- }
- TString server_address_;
- EchoTestServiceStreamingImpl service_;
- std::unique_ptr<Server> server_;
-};
-
-TEST_F(ServerInterceptorsEnd2endSyncStreamingTest, ClientStreamingTest) {
- ChannelArguments args;
- PhonyInterceptor::Reset();
- auto channel =
- grpc::CreateChannel(server_address_, InsecureChannelCredentials());
- MakeClientStreamingCall(channel);
- // Make sure all 20 phony interceptors were run
- EXPECT_EQ(PhonyInterceptor::GetNumTimesRun(), 20);
-}
-
-TEST_F(ServerInterceptorsEnd2endSyncStreamingTest, ServerStreamingTest) {
- ChannelArguments args;
- PhonyInterceptor::Reset();
- auto channel =
- grpc::CreateChannel(server_address_, InsecureChannelCredentials());
- MakeServerStreamingCall(channel);
- // Make sure all 20 phony interceptors were run
- EXPECT_EQ(PhonyInterceptor::GetNumTimesRun(), 20);
-}
-
-TEST_F(ServerInterceptorsEnd2endSyncStreamingTest, BidiStreamingTest) {
- ChannelArguments args;
- PhonyInterceptor::Reset();
- auto channel =
- grpc::CreateChannel(server_address_, InsecureChannelCredentials());
- MakeBidiStreamingCall(channel);
- // Make sure all 20 phony interceptors were run
- EXPECT_EQ(PhonyInterceptor::GetNumTimesRun(), 20);
-}
-
-class ServerInterceptorsAsyncEnd2endTest : public ::testing::Test {};
-
-TEST_F(ServerInterceptorsAsyncEnd2endTest, UnaryTest) {
- PhonyInterceptor::Reset();
- int port = 5006; // grpc_pick_unused_port_or_die();
- string server_address = "localhost:" + ::ToString(port);
- ServerBuilder builder;
- EchoTestService::AsyncService service;
- builder.AddListeningPort(server_address, InsecureServerCredentials());
- builder.RegisterService(&service);
- std::vector<std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
- creators;
- creators.push_back(
- std::unique_ptr<experimental::ServerInterceptorFactoryInterface>(
- new LoggingInterceptorFactory()));
- for (auto i = 0; i < 20; i++) {
- creators.push_back(y_absl::make_unique<PhonyInterceptorFactory>());
- }
- builder.experimental().SetInterceptorCreators(std::move(creators));
- auto cq = builder.AddCompletionQueue();
- auto server = builder.BuildAndStart();
-
- ChannelArguments args;
- auto channel =
- grpc::CreateChannel(server_address, InsecureChannelCredentials());
- auto stub = grpc::testing::EchoTestService::NewStub(channel);
-
- EchoRequest send_request;
- EchoRequest recv_request;
- EchoResponse send_response;
- EchoResponse recv_response;
- Status recv_status;
-
- ClientContext cli_ctx;
- ServerContext srv_ctx;
- grpc::ServerAsyncResponseWriter<EchoResponse> response_writer(&srv_ctx);
-
- send_request.set_message("Hello");
- cli_ctx.AddMetadata("testkey", "testvalue");
- std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader(
- stub->AsyncEcho(&cli_ctx, send_request, cq.get()));
-
- service.RequestEcho(&srv_ctx, &recv_request, &response_writer, cq.get(),
- cq.get(), tag(2));
-
- response_reader->Finish(&recv_response, &recv_status, tag(4));
-
- Verifier().Expect(2, true).Verify(cq.get());
- EXPECT_EQ(send_request.message(), recv_request.message());
-
- EXPECT_TRUE(CheckMetadata(srv_ctx.client_metadata(), "testkey", "testvalue"));
- srv_ctx.AddTrailingMetadata("testkey", "testvalue");
-
- send_response.set_message(recv_request.message());
- response_writer.Finish(send_response, Status::OK, tag(3));
- Verifier().Expect(3, true).Expect(4, true).Verify(cq.get());
-
- EXPECT_EQ(send_response.message(), recv_response.message());
- EXPECT_TRUE(recv_status.ok());
- EXPECT_TRUE(CheckMetadata(cli_ctx.GetServerTrailingMetadata(), "testkey",
- "testvalue"));
-
- // Make sure all 20 phony interceptors were run
- EXPECT_EQ(PhonyInterceptor::GetNumTimesRun(), 20);
-
- server->Shutdown();
- cq->Shutdown();
- void* ignored_tag;
- bool ignored_ok;
- while (cq->Next(&ignored_tag, &ignored_ok)) {
- }
- // grpc_recycle_unused_port(port);
-}
-
-TEST_F(ServerInterceptorsAsyncEnd2endTest, BidiStreamingTest) {
- PhonyInterceptor::Reset();
- int port = 5007; // grpc_pick_unused_port_or_die();
- string server_address = "localhost:" + ::ToString(port);
- ServerBuilder builder;
- EchoTestService::AsyncService service;
- builder.AddListeningPort(server_address, InsecureServerCredentials());
- builder.RegisterService(&service);
- std::vector<std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
- creators;
- creators.push_back(
- std::unique_ptr<experimental::ServerInterceptorFactoryInterface>(
- new LoggingInterceptorFactory()));
- for (auto i = 0; i < 20; i++) {
- creators.push_back(y_absl::make_unique<PhonyInterceptorFactory>());
- }
- builder.experimental().SetInterceptorCreators(std::move(creators));
- auto cq = builder.AddCompletionQueue();
- auto server = builder.BuildAndStart();
-
- ChannelArguments args;
- auto channel =
- grpc::CreateChannel(server_address, InsecureChannelCredentials());
- auto stub = grpc::testing::EchoTestService::NewStub(channel);
-
- EchoRequest send_request;
- EchoRequest recv_request;
- EchoResponse send_response;
- EchoResponse recv_response;
- Status recv_status;
-
- ClientContext cli_ctx;
- ServerContext srv_ctx;
- grpc::ServerAsyncReaderWriter<EchoResponse, EchoRequest> srv_stream(&srv_ctx);
-
- send_request.set_message("Hello");
- cli_ctx.AddMetadata("testkey", "testvalue");
- std::unique_ptr<ClientAsyncReaderWriter<EchoRequest, EchoResponse>>
- cli_stream(stub->AsyncBidiStream(&cli_ctx, cq.get(), tag(1)));
-
- service.RequestBidiStream(&srv_ctx, &srv_stream, cq.get(), cq.get(), tag(2));
-
- Verifier().Expect(1, true).Expect(2, true).Verify(cq.get());
-
- EXPECT_TRUE(CheckMetadata(srv_ctx.client_metadata(), "testkey", "testvalue"));
- srv_ctx.AddTrailingMetadata("testkey", "testvalue");
-
- cli_stream->Write(send_request, tag(3));
- srv_stream.Read(&recv_request, tag(4));
- Verifier().Expect(3, true).Expect(4, true).Verify(cq.get());
- EXPECT_EQ(send_request.message(), recv_request.message());
-
- send_response.set_message(recv_request.message());
- srv_stream.Write(send_response, tag(5));
- cli_stream->Read(&recv_response, tag(6));
- Verifier().Expect(5, true).Expect(6, true).Verify(cq.get());
- EXPECT_EQ(send_response.message(), recv_response.message());
-
- cli_stream->WritesDone(tag(7));
- srv_stream.Read(&recv_request, tag(8));
- Verifier().Expect(7, true).Expect(8, false).Verify(cq.get());
-
- srv_stream.Finish(Status::OK, tag(9));
- cli_stream->Finish(&recv_status, tag(10));
- Verifier().Expect(9, true).Expect(10, true).Verify(cq.get());
-
- EXPECT_TRUE(recv_status.ok());
- EXPECT_TRUE(CheckMetadata(cli_ctx.GetServerTrailingMetadata(), "testkey",
- "testvalue"));
-
- // Make sure all 20 phony interceptors were run
- EXPECT_EQ(PhonyInterceptor::GetNumTimesRun(), 20);
-
- server->Shutdown();
- cq->Shutdown();
- void* ignored_tag;
- bool ignored_ok;
- while (cq->Next(&ignored_tag, &ignored_ok)) {
- }
- // grpc_recycle_unused_port(port);
-}
-
-TEST_F(ServerInterceptorsAsyncEnd2endTest, GenericRPCTest) {
- PhonyInterceptor::Reset();
- int port = 5008; // grpc_pick_unused_port_or_die();
- string server_address = "localhost:" + ::ToString(port);
- ServerBuilder builder;
- AsyncGenericService service;
- builder.AddListeningPort(server_address, InsecureServerCredentials());
- builder.RegisterAsyncGenericService(&service);
- std::vector<std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
- creators;
- creators.reserve(20);
- for (auto i = 0; i < 20; i++) {
- creators.push_back(y_absl::make_unique<PhonyInterceptorFactory>());
- }
- builder.experimental().SetInterceptorCreators(std::move(creators));
- auto srv_cq = builder.AddCompletionQueue();
- CompletionQueue cli_cq;
- auto server = builder.BuildAndStart();
-
- ChannelArguments args;
- auto channel =
- grpc::CreateChannel(server_address, InsecureChannelCredentials());
- GenericStub generic_stub(channel);
-
- const TString kMethodName("/grpc.cpp.test.util.EchoTestService/Echo");
- EchoRequest send_request;
- EchoRequest recv_request;
- EchoResponse send_response;
- EchoResponse recv_response;
- Status recv_status;
-
- ClientContext cli_ctx;
- GenericServerContext srv_ctx;
- GenericServerAsyncReaderWriter stream(&srv_ctx);
-
- // The string needs to be long enough to test heap-based slice.
- send_request.set_message("Hello");
- cli_ctx.AddMetadata("testkey", "testvalue");
-
- CompletionQueue* cq = srv_cq.get();
- std::thread request_call([cq]() { Verifier().Expect(4, true).Verify(cq); });
- std::unique_ptr<GenericClientAsyncReaderWriter> call =
- generic_stub.PrepareCall(&cli_ctx, kMethodName, &cli_cq);
- call->StartCall(tag(1));
- Verifier().Expect(1, true).Verify(&cli_cq);
- std::unique_ptr<ByteBuffer> send_buffer =
- SerializeToByteBuffer(&send_request);
- call->Write(*send_buffer, tag(2));
- // Send ByteBuffer can be destroyed after calling Write.
- send_buffer.reset();
- Verifier().Expect(2, true).Verify(&cli_cq);
- call->WritesDone(tag(3));
- Verifier().Expect(3, true).Verify(&cli_cq);
-
- service.RequestCall(&srv_ctx, &stream, srv_cq.get(), srv_cq.get(), tag(4));
-
- request_call.join();
- EXPECT_EQ(kMethodName, srv_ctx.method());
- EXPECT_TRUE(CheckMetadata(srv_ctx.client_metadata(), "testkey", "testvalue"));
- srv_ctx.AddTrailingMetadata("testkey", "testvalue");
-
- ByteBuffer recv_buffer;
- stream.Read(&recv_buffer, tag(5));
- Verifier().Expect(5, true).Verify(srv_cq.get());
- EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_request));
- EXPECT_EQ(send_request.message(), recv_request.message());
-
- send_response.set_message(recv_request.message());
- send_buffer = SerializeToByteBuffer(&send_response);
- stream.Write(*send_buffer, tag(6));
- send_buffer.reset();
- Verifier().Expect(6, true).Verify(srv_cq.get());
-
- stream.Finish(Status::OK, tag(7));
- // Shutdown srv_cq before we try to get the tag back, to verify that the
- // interception API handles completion queue shutdowns that take place before
- // all the tags are returned
- srv_cq->Shutdown();
- Verifier().Expect(7, true).Verify(srv_cq.get());
-
- recv_buffer.Clear();
- call->Read(&recv_buffer, tag(8));
- Verifier().Expect(8, true).Verify(&cli_cq);
- EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_response));
-
- call->Finish(&recv_status, tag(9));
- cli_cq.Shutdown();
- Verifier().Expect(9, true).Verify(&cli_cq);
-
- EXPECT_EQ(send_response.message(), recv_response.message());
- EXPECT_TRUE(recv_status.ok());
- EXPECT_TRUE(CheckMetadata(cli_ctx.GetServerTrailingMetadata(), "testkey",
- "testvalue"));
-
- // Make sure all 20 phony interceptors were run
- EXPECT_EQ(PhonyInterceptor::GetNumTimesRun(), 20);
-
- server->Shutdown();
- void* ignored_tag;
- bool ignored_ok;
- while (cli_cq.Next(&ignored_tag, &ignored_ok)) {
- }
- while (srv_cq->Next(&ignored_tag, &ignored_ok)) {
- }
- // grpc_recycle_unused_port(port);
-}
-
-TEST_F(ServerInterceptorsAsyncEnd2endTest, UnimplementedRpcTest) {
- PhonyInterceptor::Reset();
- int port = 5009; // grpc_pick_unused_port_or_die();
- string server_address = "localhost:" + ::ToString(port);
- ServerBuilder builder;
- builder.AddListeningPort(server_address, InsecureServerCredentials());
- std::vector<std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
- creators;
- creators.reserve(20);
- for (auto i = 0; i < 20; i++) {
- creators.push_back(y_absl::make_unique<PhonyInterceptorFactory>());
- }
- builder.experimental().SetInterceptorCreators(std::move(creators));
- auto cq = builder.AddCompletionQueue();
- auto server = builder.BuildAndStart();
-
- ChannelArguments args;
- std::shared_ptr<Channel> channel =
- grpc::CreateChannel(server_address, InsecureChannelCredentials());
- std::unique_ptr<grpc::testing::UnimplementedEchoService::Stub> stub;
- stub = grpc::testing::UnimplementedEchoService::NewStub(channel);
- EchoRequest send_request;
- EchoResponse recv_response;
- Status recv_status;
-
- ClientContext cli_ctx;
- send_request.set_message("Hello");
- std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader(
- stub->AsyncUnimplemented(&cli_ctx, send_request, cq.get()));
-
- response_reader->Finish(&recv_response, &recv_status, tag(4));
- Verifier().Expect(4, true).Verify(cq.get());
-
- EXPECT_EQ(StatusCode::UNIMPLEMENTED, recv_status.error_code());
- EXPECT_EQ("", recv_status.error_message());
-
- // Make sure all 20 phony interceptors were run
- EXPECT_EQ(PhonyInterceptor::GetNumTimesRun(), 20);
-
- server->Shutdown();
- cq->Shutdown();
- void* ignored_tag;
- bool ignored_ok;
- while (cq->Next(&ignored_tag, &ignored_ok)) {
- }
- // grpc_recycle_unused_port(port);
-}
-
-class ServerInterceptorsSyncUnimplementedEnd2endTest : public ::testing::Test {
-};
-
-TEST_F(ServerInterceptorsSyncUnimplementedEnd2endTest, UnimplementedRpcTest) {
- PhonyInterceptor::Reset();
- int port = 5010; // grpc_pick_unused_port_or_die();
- string server_address = "localhost:" + ::ToString(port);
- ServerBuilder builder;
- TestServiceImpl service;
- builder.RegisterService(&service);
- builder.AddListeningPort(server_address, InsecureServerCredentials());
- std::vector<std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
- creators;
- creators.reserve(20);
- for (auto i = 0; i < 20; i++) {
- creators.push_back(y_absl::make_unique<PhonyInterceptorFactory>());
- }
- builder.experimental().SetInterceptorCreators(std::move(creators));
- auto server = builder.BuildAndStart();
-
- ChannelArguments args;
- std::shared_ptr<Channel> channel =
- grpc::CreateChannel(server_address, InsecureChannelCredentials());
- std::unique_ptr<grpc::testing::UnimplementedEchoService::Stub> stub;
- stub = grpc::testing::UnimplementedEchoService::NewStub(channel);
- EchoRequest send_request;
- EchoResponse recv_response;
-
- ClientContext cli_ctx;
- send_request.set_message("Hello");
- Status recv_status =
- stub->Unimplemented(&cli_ctx, send_request, &recv_response);
-
- EXPECT_EQ(StatusCode::UNIMPLEMENTED, recv_status.error_code());
- EXPECT_EQ("", recv_status.error_message());
-
- // Make sure all 20 phony interceptors were run
- EXPECT_EQ(PhonyInterceptor::GetNumTimesRun(), 20);
-
- server->Shutdown();
- // grpc_recycle_unused_port(port);
-}
-
-} // namespace
-} // namespace testing
-} // namespace grpc
-
-int main(int argc, char** argv) {
- grpc::testing::TestEnvironment env(argc, argv);
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/contrib/libs/grpc/test/cpp/end2end/test_health_check_service_impl.cc b/contrib/libs/grpc/test/cpp/end2end/test_health_check_service_impl.cc
deleted file mode 100644
index 5b212cba313..00000000000
--- a/contrib/libs/grpc/test/cpp/end2end/test_health_check_service_impl.cc
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- *
- * Copyright 2018 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include "test/cpp/end2end/test_health_check_service_impl.h"
-
-#include <grpc/grpc.h>
-
-using grpc::health::v1::HealthCheckRequest;
-using grpc::health::v1::HealthCheckResponse;
-
-namespace grpc {
-namespace testing {
-
-Status HealthCheckServiceImpl::Check(ServerContext* /*context*/,
- const HealthCheckRequest* request,
- HealthCheckResponse* response) {
- std::lock_guard<std::mutex> lock(mu_);
- auto iter = status_map_.find(request->service());
- if (iter == status_map_.end()) {
- return Status(StatusCode::NOT_FOUND, "");
- }
- response->set_status(iter->second);
- return Status::OK;
-}
-
-Status HealthCheckServiceImpl::Watch(
- ServerContext* context, const HealthCheckRequest* request,
- ::grpc::ServerWriter<HealthCheckResponse>* writer) {
- auto last_state = HealthCheckResponse::UNKNOWN;
- while (!context->IsCancelled()) {
- {
- std::lock_guard<std::mutex> lock(mu_);
- HealthCheckResponse response;
- auto iter = status_map_.find(request->service());
- if (iter == status_map_.end()) {
- response.set_status(response.SERVICE_UNKNOWN);
- } else {
- response.set_status(iter->second);
- }
- if (response.status() != last_state) {
- writer->Write(response, ::grpc::WriteOptions());
- last_state = response.status();
- }
- }
- gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC),
- gpr_time_from_millis(1000, GPR_TIMESPAN)));
- }
- return Status::OK;
-}
-
-void HealthCheckServiceImpl::SetStatus(
- const TString& service_name,
- HealthCheckResponse::ServingStatus status) {
- std::lock_guard<std::mutex> lock(mu_);
- if (shutdown_) {
- status = HealthCheckResponse::NOT_SERVING;
- }
- status_map_[service_name] = status;
-}
-
-void HealthCheckServiceImpl::SetAll(HealthCheckResponse::ServingStatus status) {
- std::lock_guard<std::mutex> lock(mu_);
- if (shutdown_) {
- return;
- }
- for (auto iter = status_map_.begin(); iter != status_map_.end(); ++iter) {
- iter->second = status;
- }
-}
-
-void HealthCheckServiceImpl::Shutdown() {
- std::lock_guard<std::mutex> lock(mu_);
- if (shutdown_) {
- return;
- }
- shutdown_ = true;
- for (auto iter = status_map_.begin(); iter != status_map_.end(); ++iter) {
- iter->second = HealthCheckResponse::NOT_SERVING;
- }
-}
-
-} // namespace testing
-} // namespace grpc
diff --git a/contrib/libs/grpc/test/cpp/end2end/test_health_check_service_impl.h b/contrib/libs/grpc/test/cpp/end2end/test_health_check_service_impl.h
deleted file mode 100644
index d370e4693a5..00000000000
--- a/contrib/libs/grpc/test/cpp/end2end/test_health_check_service_impl.h
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- *
- * Copyright 2018 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-#ifndef GRPC_TEST_CPP_END2END_TEST_HEALTH_CHECK_SERVICE_IMPL_H
-#define GRPC_TEST_CPP_END2END_TEST_HEALTH_CHECK_SERVICE_IMPL_H
-
-#include <map>
-#include <mutex>
-
-#include <grpcpp/server_context.h>
-#include <grpcpp/support/status.h>
-
-#include "src/proto/grpc/health/v1/health.grpc.pb.h"
-
-namespace grpc {
-namespace testing {
-
-// A sample sync implementation of the health checking service. This does the
-// same thing as the default one.
-class HealthCheckServiceImpl : public health::v1::Health::Service {
- public:
- Status Check(ServerContext* context,
- const health::v1::HealthCheckRequest* request,
- health::v1::HealthCheckResponse* response) override;
- Status Watch(ServerContext* context,
- const health::v1::HealthCheckRequest* request,
- ServerWriter<health::v1::HealthCheckResponse>* writer) override;
- void SetStatus(const TString& service_name,
- health::v1::HealthCheckResponse::ServingStatus status);
- void SetAll(health::v1::HealthCheckResponse::ServingStatus status);
-
- void Shutdown();
-
- private:
- std::mutex mu_;
- bool shutdown_ = false;
- std::map<const TString, health::v1::HealthCheckResponse::ServingStatus>
- status_map_;
-};
-
-} // namespace testing
-} // namespace grpc
-
-#endif // GRPC_TEST_CPP_END2END_TEST_HEALTH_CHECK_SERVICE_IMPL_H
diff --git a/contrib/libs/grpc/test/cpp/end2end/test_service_impl.cc b/contrib/libs/grpc/test/cpp/end2end/test_service_impl.cc
deleted file mode 100644
index 7a5856806e5..00000000000
--- a/contrib/libs/grpc/test/cpp/end2end/test_service_impl.cc
+++ /dev/null
@@ -1,635 +0,0 @@
-/*
- *
- * Copyright 2016 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include "test/cpp/end2end/test_service_impl.h"
-
-#include <util/generic/string.h>
-#include <thread>
-
-#include <gtest/gtest.h>
-
-#include <grpc/support/log.h>
-#include <grpcpp/alarm.h>
-#include <grpcpp/security/credentials.h>
-#include <grpcpp/server_context.h>
-
-#include "src/proto/grpc/testing/echo.grpc.pb.h"
-#include "test/cpp/util/string_ref_helper.h"
-
-using std::chrono::system_clock;
-
-namespace grpc {
-namespace testing {
-namespace internal {
-
-// When echo_deadline is requested, deadline seen in the ServerContext is set in
-// the response in seconds.
-void MaybeEchoDeadline(ServerContextBase* context, const EchoRequest* request,
- EchoResponse* response) {
- if (request->has_param() && request->param().echo_deadline()) {
- gpr_timespec deadline = gpr_inf_future(GPR_CLOCK_REALTIME);
- if (context->deadline() != system_clock::time_point::max()) {
- Timepoint2Timespec(context->deadline(), &deadline);
- }
- response->mutable_param()->set_request_deadline(deadline.tv_sec);
- }
-}
-
-void CheckServerAuthContext(const ServerContextBase* context,
- const TString& expected_transport_security_type,
- const TString& expected_client_identity) {
- std::shared_ptr<const AuthContext> auth_ctx = context->auth_context();
- std::vector<grpc::string_ref> tst =
- auth_ctx->FindPropertyValues("transport_security_type");
- EXPECT_EQ(1u, tst.size());
- EXPECT_EQ(expected_transport_security_type.c_str(), ToString(tst[0]));
- if (expected_client_identity.empty()) {
- EXPECT_TRUE(auth_ctx->GetPeerIdentityPropertyName().empty());
- EXPECT_TRUE(auth_ctx->GetPeerIdentity().empty());
- EXPECT_FALSE(auth_ctx->IsPeerAuthenticated());
- } else {
- auto identity = auth_ctx->GetPeerIdentity();
- EXPECT_TRUE(auth_ctx->IsPeerAuthenticated());
- EXPECT_EQ(1u, identity.size());
- EXPECT_EQ(expected_client_identity.c_str(), ToString(identity[0]));
- }
-}
-
-// Returns the number of pairs in metadata that exactly match the given
-// key-value pair. Returns -1 if the pair wasn't found.
-int MetadataMatchCount(
- const std::multimap<grpc::string_ref, grpc::string_ref>& metadata,
- const TString& key, const TString& value) {
- int count = 0;
- for (const auto& metadatum : metadata) {
- if (ToString(metadatum.first) == key &&
- ToString(metadatum.second) == value) {
- count++;
- }
- }
- return count;
-}
-
-int GetIntValueFromMetadataHelper(
- const char* key,
- const std::multimap<grpc::string_ref, grpc::string_ref>& metadata,
- int default_value) {
- if (metadata.find(key) != metadata.end()) {
- std::istringstream iss(ToString(metadata.find(key)->second));
- iss >> default_value;
- gpr_log(GPR_INFO, "%s : %d", key, default_value);
- }
-
- return default_value;
-}
-
-int GetIntValueFromMetadata(
- const char* key,
- const std::multimap<grpc::string_ref, grpc::string_ref>& metadata,
- int default_value) {
- return GetIntValueFromMetadataHelper(key, metadata, default_value);
-}
-
-void ServerTryCancel(ServerContext* context) {
- EXPECT_FALSE(context->IsCancelled());
- context->TryCancel();
- gpr_log(GPR_INFO, "Server called TryCancel() to cancel the request");
- // Now wait until it's really canceled
- while (!context->IsCancelled()) {
- gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
- gpr_time_from_micros(1000, GPR_TIMESPAN)));
- }
-}
-
-void ServerTryCancelNonblocking(CallbackServerContext* context) {
- EXPECT_FALSE(context->IsCancelled());
- context->TryCancel();
- gpr_log(GPR_INFO,
- "Server called TryCancelNonblocking() to cancel the request");
-}
-
-} // namespace internal
-
-ServerUnaryReactor* CallbackTestServiceImpl::Echo(
- CallbackServerContext* context, const EchoRequest* request,
- EchoResponse* response) {
- class Reactor : public ::grpc::ServerUnaryReactor {
- public:
- Reactor(CallbackTestServiceImpl* service, CallbackServerContext* ctx,
- const EchoRequest* request, EchoResponse* response)
- : service_(service), ctx_(ctx), req_(request), resp_(response) {
- // It should be safe to call IsCancelled here, even though we don't know
- // the result. Call it asynchronously to see if we trigger any data races.
- // Join it in OnDone (technically that could be blocking but shouldn't be
- // for very long).
- async_cancel_check_ = std::thread([this] { (void)ctx_->IsCancelled(); });
-
- started_ = true;
-
- if (request->has_param() &&
- request->param().server_notify_client_when_started()) {
- service->signaller_.SignalClientThatRpcStarted();
- // Block on the "wait to continue" decision in a different thread since
- // we can't tie up an EM thread with blocking events. We can join it in
- // OnDone since it would definitely be done by then.
- rpc_wait_thread_ = std::thread([this] {
- service_->signaller_.ServerWaitToContinue();
- StartRpc();
- });
- } else {
- StartRpc();
- }
- }
-
- void StartRpc() {
- if (req_->has_param() && req_->param().server_sleep_us() > 0) {
- // Set an alarm for that much time
- alarm_.Set(
- gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC),
- gpr_time_from_micros(req_->param().server_sleep_us(),
- GPR_TIMESPAN)),
- [this](bool ok) { NonDelayed(ok); });
- return;
- }
- NonDelayed(true);
- }
- void OnSendInitialMetadataDone(bool ok) override {
- EXPECT_TRUE(ok);
- initial_metadata_sent_ = true;
- }
- void OnCancel() override {
- EXPECT_TRUE(started_);
- EXPECT_TRUE(ctx_->IsCancelled());
- on_cancel_invoked_ = true;
- std::lock_guard<std::mutex> l(cancel_mu_);
- cancel_cv_.notify_one();
- }
- void OnDone() override {
- if (req_->has_param() && req_->param().echo_metadata_initially()) {
- EXPECT_TRUE(initial_metadata_sent_);
- }
- EXPECT_EQ(ctx_->IsCancelled(), on_cancel_invoked_);
- // Validate that finishing with a non-OK status doesn't cause cancellation
- if (req_->has_param() && req_->param().has_expected_error()) {
- EXPECT_FALSE(on_cancel_invoked_);
- }
- async_cancel_check_.join();
- if (rpc_wait_thread_.joinable()) {
- rpc_wait_thread_.join();
- }
- if (finish_when_cancelled_.joinable()) {
- finish_when_cancelled_.join();
- }
- delete this;
- }
-
- private:
- void NonDelayed(bool ok) {
- if (!ok) {
- EXPECT_TRUE(ctx_->IsCancelled());
- Finish(Status::CANCELLED);
- return;
- }
- if (req_->has_param() && req_->param().server_die()) {
- gpr_log(GPR_ERROR, "The request should not reach application handler.");
- GPR_ASSERT(0);
- }
- if (req_->has_param() && req_->param().has_expected_error()) {
- const auto& error = req_->param().expected_error();
- Finish(Status(static_cast<StatusCode>(error.code()),
- error.error_message(), error.binary_error_details()));
- return;
- }
- int server_try_cancel = internal::GetIntValueFromMetadata(
- kServerTryCancelRequest, ctx_->client_metadata(), DO_NOT_CANCEL);
- if (server_try_cancel != DO_NOT_CANCEL) {
- // Since this is a unary RPC, by the time this server handler is called,
- // the 'request' message is already read from the client. So the
- // scenarios in server_try_cancel don't make much sense. Just cancel the
- // RPC as long as server_try_cancel is not DO_NOT_CANCEL
- EXPECT_FALSE(ctx_->IsCancelled());
- ctx_->TryCancel();
- gpr_log(GPR_INFO, "Server called TryCancel() to cancel the request");
- FinishWhenCancelledAsync();
- return;
- }
- resp_->set_message(req_->message());
- internal::MaybeEchoDeadline(ctx_, req_, resp_);
- if (service_->host_) {
- resp_->mutable_param()->set_host(*service_->host_);
- }
- if (req_->has_param() && req_->param().client_cancel_after_us()) {
- {
- std::unique_lock<std::mutex> lock(service_->mu_);
- service_->signal_client_ = true;
- }
- FinishWhenCancelledAsync();
- return;
- } else if (req_->has_param() && req_->param().server_cancel_after_us()) {
- alarm_.Set(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
- gpr_time_from_micros(
- req_->param().server_cancel_after_us(),
- GPR_TIMESPAN)),
- [this](bool) { Finish(Status::CANCELLED); });
- return;
- } else if (!req_->has_param() || !req_->param().skip_cancelled_check()) {
- EXPECT_FALSE(ctx_->IsCancelled());
- }
-
- if (req_->has_param() && req_->param().echo_metadata_initially()) {
- const std::multimap<grpc::string_ref, grpc::string_ref>&
- client_metadata = ctx_->client_metadata();
- for (const auto& metadatum : client_metadata) {
- ctx_->AddInitialMetadata(ToString(metadatum.first),
- ToString(metadatum.second));
- }
- StartSendInitialMetadata();
- }
-
- if (req_->has_param() && req_->param().echo_metadata()) {
- const std::multimap<grpc::string_ref, grpc::string_ref>&
- client_metadata = ctx_->client_metadata();
- for (const auto& metadatum : client_metadata) {
- ctx_->AddTrailingMetadata(ToString(metadatum.first),
- ToString(metadatum.second));
- }
- // Terminate rpc with error and debug info in trailer.
- if (req_->param().debug_info().stack_entries_size() ||
- !req_->param().debug_info().detail().empty()) {
- TString serialized_debug_info =
- req_->param().debug_info().SerializeAsString();
- ctx_->AddTrailingMetadata(kDebugInfoTrailerKey,
- serialized_debug_info);
- Finish(Status::CANCELLED);
- return;
- }
- }
- if (req_->has_param() &&
- (req_->param().expected_client_identity().length() > 0 ||
- req_->param().check_auth_context())) {
- internal::CheckServerAuthContext(
- ctx_, req_->param().expected_transport_security_type(),
- req_->param().expected_client_identity());
- }
- if (req_->has_param() && req_->param().response_message_length() > 0) {
- resp_->set_message(
- TString(req_->param().response_message_length(), '\0'));
- }
- if (req_->has_param() && req_->param().echo_peer()) {
- resp_->mutable_param()->set_peer(ctx_->peer().c_str());
- }
- Finish(Status::OK);
- }
- void FinishWhenCancelledAsync() {
- finish_when_cancelled_ = std::thread([this] {
- std::unique_lock<std::mutex> l(cancel_mu_);
- cancel_cv_.wait(l, [this] { return ctx_->IsCancelled(); });
- Finish(Status::CANCELLED);
- });
- }
-
- CallbackTestServiceImpl* const service_;
- CallbackServerContext* const ctx_;
- const EchoRequest* const req_;
- EchoResponse* const resp_;
- Alarm alarm_;
- std::mutex cancel_mu_;
- std::condition_variable cancel_cv_;
- bool initial_metadata_sent_ = false;
- bool started_ = false;
- bool on_cancel_invoked_ = false;
- std::thread async_cancel_check_;
- std::thread rpc_wait_thread_;
- std::thread finish_when_cancelled_;
- };
-
- return new Reactor(this, context, request, response);
-}
-
-ServerUnaryReactor* CallbackTestServiceImpl::CheckClientInitialMetadata(
- CallbackServerContext* context, const SimpleRequest42*, SimpleResponse42*) {
- class Reactor : public ::grpc::ServerUnaryReactor {
- public:
- explicit Reactor(CallbackServerContext* ctx) {
- EXPECT_EQ(internal::MetadataMatchCount(ctx->client_metadata(),
- kCheckClientInitialMetadataKey,
- kCheckClientInitialMetadataVal),
- 1);
- EXPECT_EQ(ctx->client_metadata().count(kCheckClientInitialMetadataKey),
- 1u);
- Finish(Status::OK);
- }
- void OnDone() override { delete this; }
- };
-
- return new Reactor(context);
-}
-
-ServerReadReactor<EchoRequest>* CallbackTestServiceImpl::RequestStream(
- CallbackServerContext* context, EchoResponse* response) {
- // If 'server_try_cancel' is set in the metadata, the RPC is cancelled by
- // the server by calling ServerContext::TryCancel() depending on the
- // value:
- // CANCEL_BEFORE_PROCESSING: The RPC is cancelled before the server
- // reads any message from the client CANCEL_DURING_PROCESSING: The RPC
- // is cancelled while the server is reading messages from the client
- // CANCEL_AFTER_PROCESSING: The RPC is cancelled after the server reads
- // all the messages from the client
- int server_try_cancel = internal::GetIntValueFromMetadata(
- kServerTryCancelRequest, context->client_metadata(), DO_NOT_CANCEL);
- if (server_try_cancel == CANCEL_BEFORE_PROCESSING) {
- internal::ServerTryCancelNonblocking(context);
- // Don't need to provide a reactor since the RPC is canceled
- return nullptr;
- }
-
- class Reactor : public ::grpc::ServerReadReactor<EchoRequest> {
- public:
- Reactor(CallbackServerContext* ctx, EchoResponse* response,
- int server_try_cancel)
- : ctx_(ctx),
- response_(response),
- server_try_cancel_(server_try_cancel) {
- EXPECT_NE(server_try_cancel, CANCEL_BEFORE_PROCESSING);
- response->set_message("");
-
- if (server_try_cancel_ == CANCEL_DURING_PROCESSING) {
- ctx->TryCancel();
- // Don't wait for it here
- }
- StartRead(&request_);
- setup_done_ = true;
- }
- void OnDone() override { delete this; }
- void OnCancel() override {
- EXPECT_TRUE(setup_done_);
- EXPECT_TRUE(ctx_->IsCancelled());
- FinishOnce(Status::CANCELLED);
- }
- void OnReadDone(bool ok) override {
- if (ok) {
- response_->mutable_message()->append(request_.message());
- num_msgs_read_++;
- StartRead(&request_);
- } else {
- gpr_log(GPR_INFO, "Read: %d messages", num_msgs_read_);
-
- if (server_try_cancel_ == CANCEL_DURING_PROCESSING) {
- // Let OnCancel recover this
- return;
- }
- if (server_try_cancel_ == CANCEL_AFTER_PROCESSING) {
- internal::ServerTryCancelNonblocking(ctx_);
- return;
- }
- FinishOnce(Status::OK);
- }
- }
-
- private:
- void FinishOnce(const Status& s) {
- std::lock_guard<std::mutex> l(finish_mu_);
- if (!finished_) {
- Finish(s);
- finished_ = true;
- }
- }
-
- CallbackServerContext* const ctx_;
- EchoResponse* const response_;
- EchoRequest request_;
- int num_msgs_read_{0};
- int server_try_cancel_;
- std::mutex finish_mu_;
- bool finished_{false};
- bool setup_done_{false};
- };
-
- return new Reactor(context, response, server_try_cancel);
-}
-
-// Return 'kNumResponseStreamMsgs' messages.
-// TODO(yangg) make it generic by adding a parameter into EchoRequest
-ServerWriteReactor<EchoResponse>* CallbackTestServiceImpl::ResponseStream(
- CallbackServerContext* context, const EchoRequest* request) {
- // If 'server_try_cancel' is set in the metadata, the RPC is cancelled by
- // the server by calling ServerContext::TryCancel() depending on the
- // value:
- // CANCEL_BEFORE_PROCESSING: The RPC is cancelled before the server
- // reads any message from the client CANCEL_DURING_PROCESSING: The RPC
- // is cancelled while the server is reading messages from the client
- // CANCEL_AFTER_PROCESSING: The RPC is cancelled after the server reads
- // all the messages from the client
- int server_try_cancel = internal::GetIntValueFromMetadata(
- kServerTryCancelRequest, context->client_metadata(), DO_NOT_CANCEL);
- if (server_try_cancel == CANCEL_BEFORE_PROCESSING) {
- internal::ServerTryCancelNonblocking(context);
- }
-
- class Reactor : public ::grpc::ServerWriteReactor<EchoResponse> {
- public:
- Reactor(CallbackServerContext* ctx, const EchoRequest* request,
- int server_try_cancel)
- : ctx_(ctx), request_(request), server_try_cancel_(server_try_cancel) {
- server_coalescing_api_ = internal::GetIntValueFromMetadata(
- kServerUseCoalescingApi, ctx->client_metadata(), 0);
- server_responses_to_send_ = internal::GetIntValueFromMetadata(
- kServerResponseStreamsToSend, ctx->client_metadata(),
- kServerDefaultResponseStreamsToSend);
- if (server_try_cancel_ == CANCEL_DURING_PROCESSING) {
- ctx->TryCancel();
- }
- if (server_try_cancel_ != CANCEL_BEFORE_PROCESSING) {
- if (num_msgs_sent_ < server_responses_to_send_) {
- NextWrite();
- }
- }
- setup_done_ = true;
- }
- void OnDone() override { delete this; }
- void OnCancel() override {
- EXPECT_TRUE(setup_done_);
- EXPECT_TRUE(ctx_->IsCancelled());
- FinishOnce(Status::CANCELLED);
- }
- void OnWriteDone(bool /*ok*/) override {
- if (num_msgs_sent_ < server_responses_to_send_) {
- NextWrite();
- } else if (server_coalescing_api_ != 0) {
- // We would have already done Finish just after the WriteLast
- } else if (server_try_cancel_ == CANCEL_DURING_PROCESSING) {
- // Let OnCancel recover this
- } else if (server_try_cancel_ == CANCEL_AFTER_PROCESSING) {
- internal::ServerTryCancelNonblocking(ctx_);
- } else {
- FinishOnce(Status::OK);
- }
- }
-
- private:
- void FinishOnce(const Status& s) {
- std::lock_guard<std::mutex> l(finish_mu_);
- if (!finished_) {
- Finish(s);
- finished_ = true;
- }
- }
-
- void NextWrite() {
- response_.set_message(request_->message() +
- ::ToString(num_msgs_sent_));
- if (num_msgs_sent_ == server_responses_to_send_ - 1 &&
- server_coalescing_api_ != 0) {
- {
- std::lock_guard<std::mutex> l(finish_mu_);
- if (!finished_) {
- num_msgs_sent_++;
- StartWriteLast(&response_, WriteOptions());
- }
- }
- // If we use WriteLast, we shouldn't wait before attempting Finish
- FinishOnce(Status::OK);
- } else {
- std::lock_guard<std::mutex> l(finish_mu_);
- if (!finished_) {
- num_msgs_sent_++;
- StartWrite(&response_);
- }
- }
- }
- CallbackServerContext* const ctx_;
- const EchoRequest* const request_;
- EchoResponse response_;
- int num_msgs_sent_{0};
- int server_try_cancel_;
- int server_coalescing_api_;
- int server_responses_to_send_;
- std::mutex finish_mu_;
- bool finished_{false};
- bool setup_done_{false};
- };
- return new Reactor(context, request, server_try_cancel);
-}
-
-ServerBidiReactor<EchoRequest, EchoResponse>*
-CallbackTestServiceImpl::BidiStream(CallbackServerContext* context) {
- class Reactor : public ::grpc::ServerBidiReactor<EchoRequest, EchoResponse> {
- public:
- explicit Reactor(CallbackServerContext* ctx) : ctx_(ctx) {
- // If 'server_try_cancel' is set in the metadata, the RPC is cancelled by
- // the server by calling ServerContext::TryCancel() depending on the
- // value:
- // CANCEL_BEFORE_PROCESSING: The RPC is cancelled before the server
- // reads any message from the client CANCEL_DURING_PROCESSING: The RPC
- // is cancelled while the server is reading messages from the client
- // CANCEL_AFTER_PROCESSING: The RPC is cancelled after the server reads
- // all the messages from the client
- server_try_cancel_ = internal::GetIntValueFromMetadata(
- kServerTryCancelRequest, ctx->client_metadata(), DO_NOT_CANCEL);
- server_write_last_ = internal::GetIntValueFromMetadata(
- kServerFinishAfterNReads, ctx->client_metadata(), 0);
- client_try_cancel_ = static_cast<bool>(internal::GetIntValueFromMetadata(
- kClientTryCancelRequest, ctx->client_metadata(), 0));
- if (server_try_cancel_ == CANCEL_BEFORE_PROCESSING) {
- internal::ServerTryCancelNonblocking(ctx);
- } else {
- if (server_try_cancel_ == CANCEL_DURING_PROCESSING) {
- ctx->TryCancel();
- }
- StartRead(&request_);
- }
- setup_done_ = true;
- }
- void OnDone() override {
- {
- // Use the same lock as finish to make sure that OnDone isn't inlined.
- std::lock_guard<std::mutex> l(finish_mu_);
- EXPECT_TRUE(finished_);
- finish_thread_.join();
- }
- delete this;
- }
- void OnCancel() override {
- EXPECT_TRUE(setup_done_);
- EXPECT_TRUE(ctx_->IsCancelled());
- FinishOnce(Status::CANCELLED);
- }
- void OnReadDone(bool ok) override {
- if (ok) {
- num_msgs_read_++;
- response_.set_message(request_.message());
- std::lock_guard<std::mutex> l(finish_mu_);
- if (!finished_) {
- if (num_msgs_read_ == server_write_last_) {
- StartWriteLast(&response_, WriteOptions());
- // If we use WriteLast, we shouldn't wait before attempting Finish
- } else {
- StartWrite(&response_);
- return;
- }
- }
- } else if (client_try_cancel_) {
- EXPECT_TRUE(ctx_->IsCancelled());
- }
-
- if (server_try_cancel_ == CANCEL_DURING_PROCESSING) {
- // Let OnCancel handle this
- } else if (server_try_cancel_ == CANCEL_AFTER_PROCESSING) {
- internal::ServerTryCancelNonblocking(ctx_);
- } else {
- FinishOnce(Status::OK);
- }
- }
- void OnWriteDone(bool /*ok*/) override {
- std::lock_guard<std::mutex> l(finish_mu_);
- if (!finished_) {
- StartRead(&request_);
- }
- }
-
- private:
- void FinishOnce(const Status& s) {
- std::lock_guard<std::mutex> l(finish_mu_);
- if (!finished_) {
- finished_ = true;
- // Finish asynchronously to make sure that there are no deadlocks.
- finish_thread_ = std::thread([this, s] {
- std::lock_guard<std::mutex> l(finish_mu_);
- Finish(s);
- });
- }
- }
-
- CallbackServerContext* const ctx_;
- EchoRequest request_;
- EchoResponse response_;
- int num_msgs_read_{0};
- int server_try_cancel_;
- int server_write_last_;
- std::mutex finish_mu_;
- bool finished_{false};
- bool setup_done_{false};
- std::thread finish_thread_;
- bool client_try_cancel_ = false;
- };
-
- return new Reactor(context);
-}
-
-} // namespace testing
-} // namespace grpc
diff --git a/contrib/libs/grpc/test/cpp/end2end/test_service_impl.h b/contrib/libs/grpc/test/cpp/end2end/test_service_impl.h
deleted file mode 100644
index 9983b70ac41..00000000000
--- a/contrib/libs/grpc/test/cpp/end2end/test_service_impl.h
+++ /dev/null
@@ -1,500 +0,0 @@
-/*
- *
- * Copyright 2016 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_TEST_CPP_END2END_TEST_SERVICE_IMPL_H
-#define GRPC_TEST_CPP_END2END_TEST_SERVICE_IMPL_H
-
-#include <condition_variable>
-#include <memory>
-#include <mutex>
-#include <util/generic/string.h>
-#include <thread>
-
-#include <gtest/gtest.h>
-
-#include <grpc/grpc.h>
-#include <grpc/support/log.h>
-#include <grpcpp/alarm.h>
-#include <grpcpp/security/credentials.h>
-#include <grpcpp/server_context.h>
-
-#include "src/proto/grpc/testing/echo.grpc.pb.h"
-#include "test/cpp/util/string_ref_helper.h"
-
-#include <util/string/cast.h>
-
-namespace grpc {
-namespace testing {
-
-const int kServerDefaultResponseStreamsToSend = 3;
-const char* const kServerResponseStreamsToSend = "server_responses_to_send";
-const char* const kServerTryCancelRequest = "server_try_cancel";
-const char* const kClientTryCancelRequest = "client_try_cancel";
-const char* const kDebugInfoTrailerKey = "debug-info-bin";
-const char* const kServerFinishAfterNReads = "server_finish_after_n_reads";
-const char* const kServerUseCoalescingApi = "server_use_coalescing_api";
-const char* const kCheckClientInitialMetadataKey = "custom_client_metadata";
-const char* const kCheckClientInitialMetadataVal = "Value for client metadata";
-
-typedef enum {
- DO_NOT_CANCEL = 0,
- CANCEL_BEFORE_PROCESSING,
- CANCEL_DURING_PROCESSING,
- CANCEL_AFTER_PROCESSING
-} ServerTryCancelRequestPhase;
-
-namespace internal {
-// When echo_deadline is requested, deadline seen in the ServerContext is set in
-// the response in seconds.
-void MaybeEchoDeadline(ServerContextBase* context, const EchoRequest* request,
- EchoResponse* response);
-
-void CheckServerAuthContext(const ServerContextBase* context,
- const TString& expected_transport_security_type,
- const TString& expected_client_identity);
-
-// Returns the number of pairs in metadata that exactly match the given
-// key-value pair. Returns -1 if the pair wasn't found.
-int MetadataMatchCount(
- const std::multimap<grpc::string_ref, grpc::string_ref>& metadata,
- const TString& key, const TString& value);
-
-int GetIntValueFromMetadataHelper(
- const char* key,
- const std::multimap<grpc::string_ref, grpc::string_ref>& metadata,
- int default_value);
-
-int GetIntValueFromMetadata(
- const char* key,
- const std::multimap<grpc::string_ref, grpc::string_ref>& metadata,
- int default_value);
-
-void ServerTryCancel(ServerContext* context);
-} // namespace internal
-
-class TestServiceSignaller {
- public:
- void ClientWaitUntilRpcStarted() {
- std::unique_lock<std::mutex> lock(mu_);
- cv_rpc_started_.wait(lock, [this] { return rpc_started_; });
- }
- void ServerWaitToContinue() {
- std::unique_lock<std::mutex> lock(mu_);
- cv_server_continue_.wait(lock, [this] { return server_should_continue_; });
- }
- void SignalClientThatRpcStarted() {
- std::unique_lock<std::mutex> lock(mu_);
- rpc_started_ = true;
- cv_rpc_started_.notify_one();
- }
- void SignalServerToContinue() {
- std::unique_lock<std::mutex> lock(mu_);
- server_should_continue_ = true;
- cv_server_continue_.notify_one();
- }
-
- private:
- std::mutex mu_;
- std::condition_variable cv_rpc_started_;
- bool rpc_started_ /* GUARDED_BY(mu_) */ = false;
- std::condition_variable cv_server_continue_;
- bool server_should_continue_ /* GUARDED_BY(mu_) */ = false;
-};
-
-template <typename RpcService>
-class TestMultipleServiceImpl : public RpcService {
- public:
- TestMultipleServiceImpl() : signal_client_(false), host_() {}
- explicit TestMultipleServiceImpl(const TString& host)
- : signal_client_(false), host_(new TString(host)) {}
-
- Status Echo(ServerContext* context, const EchoRequest* request,
- EchoResponse* response) {
- if (request->has_param() &&
- request->param().server_notify_client_when_started()) {
- signaller_.SignalClientThatRpcStarted();
- signaller_.ServerWaitToContinue();
- }
-
- // A bit of sleep to make sure that short deadline tests fail
- if (request->has_param() && request->param().server_sleep_us() > 0) {
- gpr_sleep_until(
- gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC),
- gpr_time_from_micros(request->param().server_sleep_us(),
- GPR_TIMESPAN)));
- }
-
- if (request->has_param() && request->param().server_die()) {
- gpr_log(GPR_ERROR, "The request should not reach application handler.");
- GPR_ASSERT(0);
- }
- if (request->has_param() && request->param().has_expected_error()) {
- const auto& error = request->param().expected_error();
- return Status(static_cast<StatusCode>(error.code()),
- error.error_message(), error.binary_error_details());
- }
- int server_try_cancel = internal::GetIntValueFromMetadata(
- kServerTryCancelRequest, context->client_metadata(), DO_NOT_CANCEL);
- if (server_try_cancel > DO_NOT_CANCEL) {
- // Since this is a unary RPC, by the time this server handler is called,
- // the 'request' message is already read from the client. So the scenarios
- // in server_try_cancel don't make much sense. Just cancel the RPC as long
- // as server_try_cancel is not DO_NOT_CANCEL
- internal::ServerTryCancel(context);
- return Status::CANCELLED;
- }
-
- response->set_message(request->message());
- internal::MaybeEchoDeadline(context, request, response);
- if (host_) {
- response->mutable_param()->set_host(*host_);
- }
- if (request->has_param() && request->param().client_cancel_after_us()) {
- {
- std::unique_lock<std::mutex> lock(mu_);
- signal_client_ = true;
- ++rpcs_waiting_for_client_cancel_;
- }
- while (!context->IsCancelled()) {
- gpr_sleep_until(gpr_time_add(
- gpr_now(GPR_CLOCK_REALTIME),
- gpr_time_from_micros(request->param().client_cancel_after_us(),
- GPR_TIMESPAN)));
- }
- {
- std::unique_lock<std::mutex> lock(mu_);
- --rpcs_waiting_for_client_cancel_;
- }
- return Status::CANCELLED;
- } else if (request->has_param() &&
- request->param().server_cancel_after_us()) {
- gpr_sleep_until(gpr_time_add(
- gpr_now(GPR_CLOCK_REALTIME),
- gpr_time_from_micros(request->param().server_cancel_after_us(),
- GPR_TIMESPAN)));
- return Status::CANCELLED;
- } else if (!request->has_param() ||
- !request->param().skip_cancelled_check()) {
- EXPECT_FALSE(context->IsCancelled());
- }
-
- if (request->has_param() && request->param().echo_metadata_initially()) {
- const std::multimap<grpc::string_ref, grpc::string_ref>& client_metadata =
- context->client_metadata();
- for (const auto& metadatum : client_metadata) {
- context->AddInitialMetadata(::ToString(metadatum.first),
- ::ToString(metadatum.second));
- }
- }
-
- if (request->has_param() && request->param().echo_metadata()) {
- const std::multimap<grpc::string_ref, grpc::string_ref>& client_metadata =
- context->client_metadata();
- for (const auto& metadatum : client_metadata) {
- context->AddTrailingMetadata(::ToString(metadatum.first),
- ::ToString(metadatum.second));
- }
- // Terminate rpc with error and debug info in trailer.
- if (request->param().debug_info().stack_entries_size() ||
- !request->param().debug_info().detail().empty()) {
- TString serialized_debug_info =
- request->param().debug_info().SerializeAsString();
- context->AddTrailingMetadata(kDebugInfoTrailerKey,
- serialized_debug_info);
- return Status::CANCELLED;
- }
- }
- if (request->has_param() &&
- (request->param().expected_client_identity().length() > 0 ||
- request->param().check_auth_context())) {
- internal::CheckServerAuthContext(
- context, request->param().expected_transport_security_type(),
- request->param().expected_client_identity());
- }
- if (request->has_param() &&
- request->param().response_message_length() > 0) {
- response->set_message(
- TString(request->param().response_message_length(), '\0'));
- }
- if (request->has_param() && request->param().echo_peer()) {
- response->mutable_param()->set_peer(context->peer());
- }
- return Status::OK;
- }
-
- Status Echo1(ServerContext* context, const EchoRequest* request,
- EchoResponse* response) {
- return Echo(context, request, response);
- }
-
- Status Echo2(ServerContext* context, const EchoRequest* request,
- EchoResponse* response) {
- return Echo(context, request, response);
- }
-
- Status CheckClientInitialMetadata(ServerContext* context,
- const SimpleRequest42* /*request*/,
- SimpleResponse42* /*response*/) {
- EXPECT_EQ(internal::MetadataMatchCount(context->client_metadata(),
- kCheckClientInitialMetadataKey,
- kCheckClientInitialMetadataVal),
- 1);
- EXPECT_EQ(1u,
- context->client_metadata().count(kCheckClientInitialMetadataKey));
- return Status::OK;
- }
-
- // Unimplemented is left unimplemented to test the returned error.
-
- Status RequestStream(ServerContext* context,
- ServerReader<EchoRequest>* reader,
- EchoResponse* response) {
- // If 'server_try_cancel' is set in the metadata, the RPC is cancelled by
- // the server by calling ServerContext::TryCancel() depending on the value:
- // CANCEL_BEFORE_PROCESSING: The RPC is cancelled before the server reads
- // any message from the client
- // CANCEL_DURING_PROCESSING: The RPC is cancelled while the server is
- // reading messages from the client
- // CANCEL_AFTER_PROCESSING: The RPC is cancelled after the server reads
- // all the messages from the client
- int server_try_cancel = internal::GetIntValueFromMetadata(
- kServerTryCancelRequest, context->client_metadata(), DO_NOT_CANCEL);
-
- EchoRequest request;
- response->set_message("");
-
- if (server_try_cancel == CANCEL_BEFORE_PROCESSING) {
- internal::ServerTryCancel(context);
- return Status::CANCELLED;
- }
-
- std::thread* server_try_cancel_thd = nullptr;
- if (server_try_cancel == CANCEL_DURING_PROCESSING) {
- server_try_cancel_thd =
- new std::thread([context] { internal::ServerTryCancel(context); });
- }
-
- int num_msgs_read = 0;
- while (reader->Read(&request)) {
- response->mutable_message()->append(request.message());
- }
- gpr_log(GPR_INFO, "Read: %d messages", num_msgs_read);
-
- if (server_try_cancel_thd != nullptr) {
- server_try_cancel_thd->join();
- delete server_try_cancel_thd;
- return Status::CANCELLED;
- }
-
- if (server_try_cancel == CANCEL_AFTER_PROCESSING) {
- internal::ServerTryCancel(context);
- return Status::CANCELLED;
- }
-
- return Status::OK;
- }
-
- // Return 'kNumResponseStreamMsgs' messages.
- // TODO(yangg) make it generic by adding a parameter into EchoRequest
- Status ResponseStream(ServerContext* context, const EchoRequest* request,
- ServerWriter<EchoResponse>* writer) {
- // If server_try_cancel is set in the metadata, the RPC is cancelled by the
- // server by calling ServerContext::TryCancel() depending on the value:
- // CANCEL_BEFORE_PROCESSING: The RPC is cancelled before the server writes
- // any messages to the client
- // CANCEL_DURING_PROCESSING: The RPC is cancelled while the server is
- // writing messages to the client
- // CANCEL_AFTER_PROCESSING: The RPC is cancelled after the server writes
- // all the messages to the client
- int server_try_cancel = internal::GetIntValueFromMetadata(
- kServerTryCancelRequest, context->client_metadata(), DO_NOT_CANCEL);
-
- int server_coalescing_api = internal::GetIntValueFromMetadata(
- kServerUseCoalescingApi, context->client_metadata(), 0);
-
- int server_responses_to_send = internal::GetIntValueFromMetadata(
- kServerResponseStreamsToSend, context->client_metadata(),
- kServerDefaultResponseStreamsToSend);
-
- if (server_try_cancel == CANCEL_BEFORE_PROCESSING) {
- internal::ServerTryCancel(context);
- return Status::CANCELLED;
- }
-
- EchoResponse response;
- std::thread* server_try_cancel_thd = nullptr;
- if (server_try_cancel == CANCEL_DURING_PROCESSING) {
- server_try_cancel_thd =
- new std::thread([context] { internal::ServerTryCancel(context); });
- }
-
- for (int i = 0; i < server_responses_to_send; i++) {
- response.set_message(request->message() + ::ToString(i));
- if (i == server_responses_to_send - 1 && server_coalescing_api != 0) {
- writer->WriteLast(response, WriteOptions());
- } else {
- writer->Write(response);
- }
- }
-
- if (server_try_cancel_thd != nullptr) {
- server_try_cancel_thd->join();
- delete server_try_cancel_thd;
- return Status::CANCELLED;
- }
-
- if (server_try_cancel == CANCEL_AFTER_PROCESSING) {
- internal::ServerTryCancel(context);
- return Status::CANCELLED;
- }
-
- return Status::OK;
- }
-
- Status BidiStream(ServerContext* context,
- ServerReaderWriter<EchoResponse, EchoRequest>* stream) {
- // If server_try_cancel is set in the metadata, the RPC is cancelled by the
- // server by calling ServerContext::TryCancel() depending on the value:
- // CANCEL_BEFORE_PROCESSING: The RPC is cancelled before the server reads/
- // writes any messages from/to the client
- // CANCEL_DURING_PROCESSING: The RPC is cancelled while the server is
- // reading/writing messages from/to the client
- // CANCEL_AFTER_PROCESSING: The RPC is cancelled after the server
- // reads/writes all messages from/to the client
- int server_try_cancel = internal::GetIntValueFromMetadata(
- kServerTryCancelRequest, context->client_metadata(), DO_NOT_CANCEL);
-
- int client_try_cancel = static_cast<bool>(internal::GetIntValueFromMetadata(
- kClientTryCancelRequest, context->client_metadata(), 0));
-
- EchoRequest request;
- EchoResponse response;
-
- if (server_try_cancel == CANCEL_BEFORE_PROCESSING) {
- internal::ServerTryCancel(context);
- return Status::CANCELLED;
- }
-
- std::thread* server_try_cancel_thd = nullptr;
- if (server_try_cancel == CANCEL_DURING_PROCESSING) {
- server_try_cancel_thd =
- new std::thread([context] { internal::ServerTryCancel(context); });
- }
-
- // kServerFinishAfterNReads suggests after how many reads, the server should
- // write the last message and send status (coalesced using WriteLast)
- int server_write_last = internal::GetIntValueFromMetadata(
- kServerFinishAfterNReads, context->client_metadata(), 0);
-
- int read_counts = 0;
- while (stream->Read(&request)) {
- read_counts++;
- gpr_log(GPR_INFO, "recv msg %s", request.message().c_str());
- response.set_message(request.message());
- if (read_counts == server_write_last) {
- stream->WriteLast(response, WriteOptions());
- break;
- } else {
- stream->Write(response);
- }
- }
-
- if (client_try_cancel) {
- EXPECT_TRUE(context->IsCancelled());
- }
-
- if (server_try_cancel_thd != nullptr) {
- server_try_cancel_thd->join();
- delete server_try_cancel_thd;
- return Status::CANCELLED;
- }
-
- if (server_try_cancel == CANCEL_AFTER_PROCESSING) {
- internal::ServerTryCancel(context);
- return Status::CANCELLED;
- }
-
- return Status::OK;
- }
-
- // Unimplemented is left unimplemented to test the returned error.
- bool signal_client() {
- std::unique_lock<std::mutex> lock(mu_);
- return signal_client_;
- }
- void ClientWaitUntilRpcStarted() { signaller_.ClientWaitUntilRpcStarted(); }
- void SignalServerToContinue() { signaller_.SignalServerToContinue(); }
- uint64_t RpcsWaitingForClientCancel() {
- std::unique_lock<std::mutex> lock(mu_);
- return rpcs_waiting_for_client_cancel_;
- }
-
- private:
- bool signal_client_;
- std::mutex mu_;
- TestServiceSignaller signaller_;
- std::unique_ptr<TString> host_;
- uint64_t rpcs_waiting_for_client_cancel_ = 0;
-};
-
-class CallbackTestServiceImpl
- : public ::grpc::testing::EchoTestService::CallbackService {
- public:
- CallbackTestServiceImpl() : signal_client_(false), host_() {}
- explicit CallbackTestServiceImpl(const TString& host)
- : signal_client_(false), host_(new TString(host)) {}
-
- ServerUnaryReactor* Echo(CallbackServerContext* context,
- const EchoRequest* request,
- EchoResponse* response) override;
-
- ServerUnaryReactor* CheckClientInitialMetadata(CallbackServerContext* context,
- const SimpleRequest42*,
- SimpleResponse42*) override;
-
- ServerReadReactor<EchoRequest>* RequestStream(
- CallbackServerContext* context, EchoResponse* response) override;
-
- ServerWriteReactor<EchoResponse>* ResponseStream(
- CallbackServerContext* context, const EchoRequest* request) override;
-
- ServerBidiReactor<EchoRequest, EchoResponse>* BidiStream(
- CallbackServerContext* context) override;
-
- // Unimplemented is left unimplemented to test the returned error.
- bool signal_client() {
- std::unique_lock<std::mutex> lock(mu_);
- return signal_client_;
- }
- void ClientWaitUntilRpcStarted() { signaller_.ClientWaitUntilRpcStarted(); }
- void SignalServerToContinue() { signaller_.SignalServerToContinue(); }
-
- private:
- bool signal_client_;
- std::mutex mu_;
- TestServiceSignaller signaller_;
- std::unique_ptr<TString> host_;
-};
-
-using TestServiceImpl =
- TestMultipleServiceImpl<::grpc::testing::EchoTestService::Service>;
-
-} // namespace testing
-} // namespace grpc
-
-#endif // GRPC_TEST_CPP_END2END_TEST_SERVICE_IMPL_H
diff --git a/contrib/libs/grpc/test/cpp/end2end/ya.make b/contrib/libs/grpc/test/cpp/end2end/ya.make
deleted file mode 100644
index 409a5fa720c..00000000000
--- a/contrib/libs/grpc/test/cpp/end2end/ya.make
+++ /dev/null
@@ -1,65 +0,0 @@
-LIBRARY()
-
-LICENSE(Apache-2.0)
-
-LICENSE_TEXTS(.yandex_meta/licenses.list.txt)
-
-PEERDIR(
- contrib/libs/grpc/src/proto/grpc/health/v1
- contrib/libs/grpc/src/proto/grpc/testing
- contrib/libs/grpc/src/proto/grpc/testing/duplicate
- contrib/libs/grpc/test/cpp/util
- contrib/libs/grpc
- contrib/restricted/googletest/googlemock
- contrib/restricted/googletest/googletest
-)
-
-ADDINCL(
- ${ARCADIA_BUILD_ROOT}/contrib/libs/grpc
- contrib/libs/grpc
-)
-
-NO_COMPILER_WARNINGS()
-
-SRCS(
- # async_end2end_test.cc
- # channelz_service_test.cc
- # client_callback_end2end_test.cc
- # client_crash_test.cc
- # client_crash_test_server.cc
- # client_interceptors_end2end_test.cc
- # client_lb_end2end_test.cc lb needs opencensus, not enabled.
- # end2end_test.cc
- # exception_test.cc
- # filter_end2end_test.cc
- # generic_end2end_test.cc
- # grpclb_end2end_test.cc lb needs opencensus, not enabled.
- # health_service_end2end_test.cc
- # hybrid_end2end_test.cc
- interceptors_util.cc
- # mock_test.cc
- # nonblocking_test.cc
- # proto_server_reflection_test.cc
- # raw_end2end_test.cc
- # server_builder_plugin_test.cc
- # server_crash_test.cc
- # server_crash_test_client.cc
- # server_early_return_test.cc
- # server_interceptors_end2end_test.cc
- # server_load_reporting_end2end_test.cc
- # shutdown_test.cc
- # streaming_throughput_test.cc
- test_health_check_service_impl.cc
- test_service_impl.cc
- # thread_stress_test.cc
- # time_change_test.cc
-)
-
-END()
-
-RECURSE_FOR_TESTS(
- health
- server_interceptors
- # Needs new gtest
- # thread
-)
diff --git a/contrib/libs/grpc/test/cpp/util/byte_buffer_proto_helper.cc b/contrib/libs/grpc/test/cpp/util/byte_buffer_proto_helper.cc
deleted file mode 100644
index 4ddbf701ba6..00000000000
--- a/contrib/libs/grpc/test/cpp/util/byte_buffer_proto_helper.cc
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- *
- * Copyright 2016 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include "test/cpp/util/byte_buffer_proto_helper.h"
-
-#include "y_absl/memory/memory.h"
-
-namespace grpc {
-namespace testing {
-
-bool ParseFromByteBuffer(ByteBuffer* buffer, grpc::protobuf::Message* message) {
- std::vector<Slice> slices;
- (void)buffer->Dump(&slices);
- TString buf;
- buf.reserve(buffer->Length());
- for (auto s = slices.begin(); s != slices.end(); s++) {
- buf.append(reinterpret_cast<const char*>(s->begin()), s->size());
- }
- return message->ParseFromString(buf);
-}
-
-std::unique_ptr<ByteBuffer> SerializeToByteBuffer(
- grpc::protobuf::Message* message) {
- TString buf;
- message->SerializeToString(&buf);
- Slice slice(buf);
- return y_absl::make_unique<ByteBuffer>(&slice, 1);
-}
-
-bool SerializeToByteBufferInPlace(grpc::protobuf::Message* message,
- ByteBuffer* buffer) {
- TString buf;
- if (!message->SerializeToString(&buf)) {
- return false;
- }
- buffer->Clear();
- Slice slice(buf);
- ByteBuffer tmp(&slice, 1);
- buffer->Swap(&tmp);
- return true;
-}
-
-} // namespace testing
-} // namespace grpc
diff --git a/contrib/libs/grpc/test/cpp/util/byte_buffer_proto_helper.h b/contrib/libs/grpc/test/cpp/util/byte_buffer_proto_helper.h
deleted file mode 100644
index 3d01fb24686..00000000000
--- a/contrib/libs/grpc/test/cpp/util/byte_buffer_proto_helper.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- *
- * Copyright 2016 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_TEST_CPP_UTIL_BYTE_BUFFER_PROTO_HELPER_H
-#define GRPC_TEST_CPP_UTIL_BYTE_BUFFER_PROTO_HELPER_H
-
-#include <memory>
-
-#include <grpcpp/impl/codegen/config_protobuf.h>
-#include <grpcpp/support/byte_buffer.h>
-
-namespace grpc {
-namespace testing {
-
-bool ParseFromByteBuffer(ByteBuffer* buffer,
- ::grpc::protobuf::Message* message);
-
-std::unique_ptr<ByteBuffer> SerializeToByteBuffer(
- ::grpc::protobuf::Message* message);
-
-bool SerializeToByteBufferInPlace(::grpc::protobuf::Message* message,
- ByteBuffer* buffer);
-
-} // namespace testing
-} // namespace grpc
-
-#endif // GRPC_TEST_CPP_UTIL_BYTE_BUFFER_PROTO_HELPER_H
diff --git a/contrib/libs/grpc/test/cpp/util/cli_call.cc b/contrib/libs/grpc/test/cpp/util/cli_call.cc
deleted file mode 100644
index 575cc00c36f..00000000000
--- a/contrib/libs/grpc/test/cpp/util/cli_call.cc
+++ /dev/null
@@ -1,225 +0,0 @@
-/*
- *
- * Copyright 2015 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include "test/cpp/util/cli_call.h"
-
-#include <cmath>
-#include <iostream>
-#include <utility>
-
-#include <grpc/grpc.h>
-#include <grpc/slice.h>
-#include <grpc/support/log.h>
-#include <grpcpp/channel.h>
-#include <grpcpp/client_context.h>
-#include <grpcpp/support/byte_buffer.h>
-
-namespace grpc {
-namespace testing {
-namespace {
-void* tag(intptr_t t) { return reinterpret_cast<void*>(t); }
-} // namespace
-
-Status CliCall::Call(const TString& request, TString* response,
- IncomingMetadataContainer* server_initial_metadata,
- IncomingMetadataContainer* server_trailing_metadata) {
- Write(request);
- WritesDone();
- if (!Read(response, server_initial_metadata)) {
- fprintf(stderr, "Failed to read response.\n");
- }
- return Finish(server_trailing_metadata);
-}
-
-CliCall::CliCall(const std::shared_ptr<grpc::Channel>& channel,
- const TString& method,
- const OutgoingMetadataContainer& metadata, CliArgs args)
- : stub_(new grpc::GenericStub(channel)) {
- gpr_mu_init(&write_mu_);
- gpr_cv_init(&write_cv_);
- if (!metadata.empty()) {
- for (OutgoingMetadataContainer::const_iterator iter = metadata.begin();
- iter != metadata.end(); ++iter) {
- ctx_.AddMetadata(iter->first, iter->second);
- }
- }
-
- // Set deadline if timeout > 0 (default value -1 if no timeout specified)
- if (args.timeout > 0) {
- int64_t timeout_in_ns = ceil(args.timeout * 1e9);
-
- // Convert timeout (in nanoseconds) to a deadline
- auto deadline =
- gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC),
- gpr_time_from_nanos(timeout_in_ns, GPR_TIMESPAN));
- ctx_.set_deadline(deadline);
- } else if (args.timeout != -1) {
- fprintf(
- stderr,
- "WARNING: Non-positive timeout value, skipping setting deadline.\n");
- }
-
- call_ = stub_->PrepareCall(&ctx_, method, &cq_);
- call_->StartCall(tag(1));
- void* got_tag;
- bool ok;
- cq_.Next(&got_tag, &ok);
- GPR_ASSERT(ok);
-}
-
-CliCall::~CliCall() {
- gpr_cv_destroy(&write_cv_);
- gpr_mu_destroy(&write_mu_);
-}
-
-void CliCall::Write(const TString& request) {
- void* got_tag;
- bool ok;
-
- gpr_slice s = gpr_slice_from_copied_buffer(request.data(), request.size());
- grpc::Slice req_slice(s, grpc::Slice::STEAL_REF);
- grpc::ByteBuffer send_buffer(&req_slice, 1);
- call_->Write(send_buffer, tag(2));
- cq_.Next(&got_tag, &ok);
- GPR_ASSERT(ok);
-}
-
-bool CliCall::Read(TString* response,
- IncomingMetadataContainer* server_initial_metadata) {
- void* got_tag;
- bool ok;
-
- grpc::ByteBuffer recv_buffer;
- call_->Read(&recv_buffer, tag(3));
-
- if (!cq_.Next(&got_tag, &ok) || !ok) {
- return false;
- }
- std::vector<grpc::Slice> slices;
- GPR_ASSERT(recv_buffer.Dump(&slices).ok());
-
- response->clear();
- for (size_t i = 0; i < slices.size(); i++) {
- response->append(reinterpret_cast<const char*>(slices[i].begin()),
- slices[i].size());
- }
- if (server_initial_metadata) {
- *server_initial_metadata = ctx_.GetServerInitialMetadata();
- }
- return true;
-}
-
-void CliCall::WritesDone() {
- void* got_tag;
- bool ok;
-
- call_->WritesDone(tag(4));
- cq_.Next(&got_tag, &ok);
- GPR_ASSERT(ok);
-}
-
-void CliCall::WriteAndWait(const TString& request) {
- grpc::Slice req_slice(request);
- grpc::ByteBuffer send_buffer(&req_slice, 1);
-
- gpr_mu_lock(&write_mu_);
- call_->Write(send_buffer, tag(2));
- write_done_ = false;
- while (!write_done_) {
- gpr_cv_wait(&write_cv_, &write_mu_, gpr_inf_future(GPR_CLOCK_MONOTONIC));
- }
- gpr_mu_unlock(&write_mu_);
-}
-
-void CliCall::WritesDoneAndWait() {
- gpr_mu_lock(&write_mu_);
- call_->WritesDone(tag(4));
- write_done_ = false;
- while (!write_done_) {
- gpr_cv_wait(&write_cv_, &write_mu_, gpr_inf_future(GPR_CLOCK_MONOTONIC));
- }
- gpr_mu_unlock(&write_mu_);
-}
-
-bool CliCall::ReadAndMaybeNotifyWrite(
- TString* response, IncomingMetadataContainer* server_initial_metadata) {
- void* got_tag;
- bool ok;
- grpc::ByteBuffer recv_buffer;
-
- call_->Read(&recv_buffer, tag(3));
- bool cq_result = cq_.Next(&got_tag, &ok);
-
- while (got_tag != tag(3)) {
- gpr_mu_lock(&write_mu_);
- write_done_ = true;
- gpr_cv_signal(&write_cv_);
- gpr_mu_unlock(&write_mu_);
-
- cq_result = cq_.Next(&got_tag, &ok);
- if (got_tag == tag(2)) {
- GPR_ASSERT(ok);
- }
- }
-
- if (!cq_result || !ok) {
- // If the RPC is ended on the server side, we should still wait for the
- // pending write on the client side to be done.
- if (!ok) {
- gpr_mu_lock(&write_mu_);
- if (!write_done_) {
- cq_.Next(&got_tag, &ok);
- GPR_ASSERT(got_tag != tag(2));
- write_done_ = true;
- gpr_cv_signal(&write_cv_);
- }
- gpr_mu_unlock(&write_mu_);
- }
- return false;
- }
-
- std::vector<grpc::Slice> slices;
- GPR_ASSERT(recv_buffer.Dump(&slices).ok());
- response->clear();
- for (size_t i = 0; i < slices.size(); i++) {
- response->append(reinterpret_cast<const char*>(slices[i].begin()),
- slices[i].size());
- }
- if (server_initial_metadata) {
- *server_initial_metadata = ctx_.GetServerInitialMetadata();
- }
- return true;
-}
-
-Status CliCall::Finish(IncomingMetadataContainer* server_trailing_metadata) {
- void* got_tag;
- bool ok;
- grpc::Status status;
-
- call_->Finish(&status, tag(5));
- cq_.Next(&got_tag, &ok);
- GPR_ASSERT(ok);
- if (server_trailing_metadata) {
- *server_trailing_metadata = ctx_.GetServerTrailingMetadata();
- }
-
- return status;
-}
-
-} // namespace testing
-} // namespace grpc
diff --git a/contrib/libs/grpc/test/cpp/util/cli_call.h b/contrib/libs/grpc/test/cpp/util/cli_call.h
deleted file mode 100644
index 330c752f430..00000000000
--- a/contrib/libs/grpc/test/cpp/util/cli_call.h
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- *
- * Copyright 2015 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_TEST_CPP_UTIL_CLI_CALL_H
-#define GRPC_TEST_CPP_UTIL_CLI_CALL_H
-
-#include <map>
-
-#include <grpcpp/channel.h>
-#include <grpcpp/completion_queue.h>
-#include <grpcpp/generic/generic_stub.h>
-#include <grpcpp/support/status.h>
-#include <grpcpp/support/string_ref.h>
-
-namespace grpc {
-
-class ClientContext;
-
-struct CliArgs {
- double timeout = -1;
-};
-
-namespace testing {
-
-// CliCall handles the sending and receiving of generic messages given the name
-// of the remote method. This class is only used by GrpcTool. Its thread-safe
-// and thread-unsafe methods should not be used together.
-class CliCall final {
- public:
- typedef std::multimap<TString, TString> OutgoingMetadataContainer;
- typedef std::multimap<grpc::string_ref, grpc::string_ref>
- IncomingMetadataContainer;
-
- CliCall(const std::shared_ptr<grpc::Channel>& channel,
- const TString& method, const OutgoingMetadataContainer& metadata,
- CliArgs args);
- CliCall(const std::shared_ptr<grpc::Channel>& channel,
- const TString& method, const OutgoingMetadataContainer& metadata)
- : CliCall(channel, method, metadata, CliArgs{}) {}
-
- ~CliCall();
-
- // Perform an unary generic RPC.
- Status Call(const TString& request, TString* response,
- IncomingMetadataContainer* server_initial_metadata,
- IncomingMetadataContainer* server_trailing_metadata);
-
- // Send a generic request message in a synchronous manner. NOT thread-safe.
- void Write(const TString& request);
-
- // Send a generic request message in a synchronous manner. NOT thread-safe.
- void WritesDone();
-
- // Receive a generic response message in a synchronous manner.NOT thread-safe.
- bool Read(TString* response,
- IncomingMetadataContainer* server_initial_metadata);
-
- // Thread-safe write. Must be used with ReadAndMaybeNotifyWrite. Send out a
- // generic request message and wait for ReadAndMaybeNotifyWrite to finish it.
- void WriteAndWait(const TString& request);
-
- // Thread-safe WritesDone. Must be used with ReadAndMaybeNotifyWrite. Send out
- // WritesDone for gereneric request messages and wait for
- // ReadAndMaybeNotifyWrite to finish it.
- void WritesDoneAndWait();
-
- // Thread-safe Read. Blockingly receive a generic response message. Notify
- // writes if they are finished when this read is waiting for a resposne.
- bool ReadAndMaybeNotifyWrite(
- TString* response,
- IncomingMetadataContainer* server_initial_metadata);
-
- // Finish the RPC.
- Status Finish(IncomingMetadataContainer* server_trailing_metadata);
-
- TString peer() const { return ctx_.peer(); }
-
- private:
- std::unique_ptr<grpc::GenericStub> stub_;
- grpc::ClientContext ctx_;
- std::unique_ptr<grpc::GenericClientAsyncReaderWriter> call_;
- grpc::CompletionQueue cq_;
- gpr_mu write_mu_;
- gpr_cv write_cv_; // Protected by write_mu_;
- bool write_done_; // Portected by write_mu_;
-};
-
-} // namespace testing
-} // namespace grpc
-
-#endif // GRPC_TEST_CPP_UTIL_CLI_CALL_H
diff --git a/contrib/libs/grpc/test/cpp/util/cli_credentials.cc b/contrib/libs/grpc/test/cpp/util/cli_credentials.cc
deleted file mode 100644
index 0b28fe9d0ce..00000000000
--- a/contrib/libs/grpc/test/cpp/util/cli_credentials.cc
+++ /dev/null
@@ -1,191 +0,0 @@
-/*
- *
- * Copyright 2016 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include "test/cpp/util/cli_credentials.h"
-
-#include "y_absl/flags/flag.h"
-
-#include <grpc/slice.h>
-#include <grpc/support/log.h>
-#include <grpcpp/impl/codegen/slice.h>
-
-#include "src/core/lib/iomgr/load_file.h"
-
-Y_ABSL_RETIRED_FLAG(bool, enable_ssl, false,
- "Replaced by --channel_creds_type=ssl.");
-Y_ABSL_RETIRED_FLAG(bool, use_auth, false,
- "Replaced by --channel_creds_type=gdc.");
-Y_ABSL_RETIRED_FLAG(TString, access_token, "",
- "Replaced by --call_creds=access_token=<token>.");
-Y_ABSL_FLAG(
- TString, ssl_target, "",
- "If not empty, treat the server host name as this for ssl/tls certificate "
- "validation.");
-Y_ABSL_FLAG(
- TString, ssl_client_cert, "",
- "If not empty, load this PEM formatted client certificate file. Requires "
- "use of --ssl_client_key.");
-Y_ABSL_FLAG(TString, ssl_client_key, "",
- "If not empty, load this PEM formatted private key. Requires use of "
- "--ssl_client_cert");
-Y_ABSL_FLAG(
- TString, local_connect_type, "local_tcp",
- "The type of local connections for which local channel credentials will "
- "be applied. Should be local_tcp or uds.");
-Y_ABSL_FLAG(
- TString, channel_creds_type, "",
- "The channel creds type: insecure, ssl, gdc (Google Default Credentials), "
- "alts, or local.");
-Y_ABSL_FLAG(
- TString, call_creds, "",
- "Call credentials to use: none (default), or access_token=<token>. If "
- "provided, the call creds are composited on top of channel creds.");
-
-namespace grpc {
-namespace testing {
-
-namespace {
-
-const char ACCESS_TOKEN_PREFIX[] = "access_token=";
-constexpr int ACCESS_TOKEN_PREFIX_LEN =
- sizeof(ACCESS_TOKEN_PREFIX) / sizeof(*ACCESS_TOKEN_PREFIX) - 1;
-
-bool IsAccessToken(const TString& auth) {
- return auth.length() > ACCESS_TOKEN_PREFIX_LEN &&
- auth.compare(0, ACCESS_TOKEN_PREFIX_LEN, ACCESS_TOKEN_PREFIX) == 0;
-}
-
-TString AccessToken(const TString& auth) {
- if (!IsAccessToken(auth)) {
- return "";
- }
- return TString(auth.c_str(), ACCESS_TOKEN_PREFIX_LEN);
-}
-
-} // namespace
-
-TString CliCredentials::GetDefaultChannelCredsType() const {
- return "insecure";
-}
-
-TString CliCredentials::GetDefaultCallCreds() const { return "none"; }
-
-std::shared_ptr<grpc::ChannelCredentials>
-CliCredentials::GetChannelCredentials() const {
- if (y_absl::GetFlag(FLAGS_channel_creds_type) == "insecure") {
- return grpc::InsecureChannelCredentials();
- } else if (y_absl::GetFlag(FLAGS_channel_creds_type) == "ssl") {
- grpc::SslCredentialsOptions ssl_creds_options;
- // TODO(@Capstan): This won't affect Google Default Credentials using SSL.
- if (!y_absl::GetFlag(FLAGS_ssl_client_cert).empty()) {
- grpc_slice cert_slice = grpc_empty_slice();
- GRPC_LOG_IF_ERROR(
- "load_file",
- grpc_load_file(y_absl::GetFlag(FLAGS_ssl_client_cert).c_str(), 1,
- &cert_slice));
- ssl_creds_options.pem_cert_chain =
- grpc::StringFromCopiedSlice(cert_slice);
- grpc_slice_unref(cert_slice);
- }
- if (!y_absl::GetFlag(FLAGS_ssl_client_key).empty()) {
- grpc_slice key_slice = grpc_empty_slice();
- GRPC_LOG_IF_ERROR(
- "load_file",
- grpc_load_file(y_absl::GetFlag(FLAGS_ssl_client_key).c_str(), 1,
- &key_slice));
- ssl_creds_options.pem_private_key =
- grpc::StringFromCopiedSlice(key_slice);
- grpc_slice_unref(key_slice);
- }
- return grpc::SslCredentials(ssl_creds_options);
- } else if (y_absl::GetFlag(FLAGS_channel_creds_type) == "gdc") {
- return grpc::GoogleDefaultCredentials();
- } else if (y_absl::GetFlag(FLAGS_channel_creds_type) == "alts") {
- return grpc::experimental::AltsCredentials(
- grpc::experimental::AltsCredentialsOptions());
- } else if (y_absl::GetFlag(FLAGS_channel_creds_type) == "local") {
- if (y_absl::GetFlag(FLAGS_local_connect_type) == "local_tcp") {
- return grpc::experimental::LocalCredentials(LOCAL_TCP);
- } else if (y_absl::GetFlag(FLAGS_local_connect_type) == "uds") {
- return grpc::experimental::LocalCredentials(UDS);
- } else {
- fprintf(stderr,
- "--local_connect_type=%s invalid; must be local_tcp or uds.\n",
- y_absl::GetFlag(FLAGS_local_connect_type).c_str());
- }
- }
- fprintf(stderr,
- "--channel_creds_type=%s invalid; must be insecure, ssl, gdc, "
- "alts, or local.\n",
- y_absl::GetFlag(FLAGS_channel_creds_type).c_str());
- return std::shared_ptr<grpc::ChannelCredentials>();
-}
-
-std::shared_ptr<grpc::CallCredentials> CliCredentials::GetCallCredentials()
- const {
- if (IsAccessToken(y_absl::GetFlag(FLAGS_call_creds))) {
- return grpc::AccessTokenCredentials(
- AccessToken(y_absl::GetFlag(FLAGS_call_creds)));
- }
- if (y_absl::GetFlag(FLAGS_call_creds) == "none") {
- // Nothing to do; creds, if any, are baked into the channel.
- return std::shared_ptr<grpc::CallCredentials>();
- }
- fprintf(stderr,
- "--call_creds=%s invalid; must be none "
- "or access_token=<token>.\n",
- y_absl::GetFlag(FLAGS_call_creds).c_str());
- return std::shared_ptr<grpc::CallCredentials>();
-}
-
-std::shared_ptr<grpc::ChannelCredentials> CliCredentials::GetCredentials()
- const {
- if (y_absl::GetFlag(FLAGS_call_creds).empty()) {
- y_absl::SetFlag(&FLAGS_call_creds, GetDefaultCallCreds());
- }
- if (y_absl::GetFlag(FLAGS_channel_creds_type).empty()) {
- y_absl::SetFlag(&FLAGS_channel_creds_type, GetDefaultChannelCredsType());
- }
- std::shared_ptr<grpc::ChannelCredentials> channel_creds =
- GetChannelCredentials();
- // Composite any call-type credentials on top of the base channel.
- std::shared_ptr<grpc::CallCredentials> call_creds = GetCallCredentials();
- return (channel_creds == nullptr || call_creds == nullptr)
- ? channel_creds
- : grpc::CompositeChannelCredentials(channel_creds, call_creds);
-}
-
-TString CliCredentials::GetCredentialUsage() const {
- return " --ssl_target ; Set server host for ssl validation\n"
- " --ssl_client_cert ; Client cert for ssl\n"
- " --ssl_client_key ; Client private key for ssl\n"
- " --local_connect_type ; Set to local_tcp or uds\n"
- " --channel_creds_type ; Set to insecure, ssl, gdc, alts, or "
- "local\n"
- " --call_creds ; Set to none, or"
- " access_token=<token>\n";
-}
-
-TString CliCredentials::GetSslTargetNameOverride() const {
- bool use_ssl = y_absl::GetFlag(FLAGS_channel_creds_type) == "ssl" ||
- y_absl::GetFlag(FLAGS_channel_creds_type) == "gdc";
- return use_ssl ? y_absl::GetFlag(FLAGS_ssl_target) : "";
-}
-
-} // namespace testing
-} // namespace grpc
diff --git a/contrib/libs/grpc/test/cpp/util/cli_credentials.h b/contrib/libs/grpc/test/cpp/util/cli_credentials.h
deleted file mode 100644
index a60d5c2c10d..00000000000
--- a/contrib/libs/grpc/test/cpp/util/cli_credentials.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- *
- * Copyright 2016 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_TEST_CPP_UTIL_CLI_CREDENTIALS_H
-#define GRPC_TEST_CPP_UTIL_CLI_CREDENTIALS_H
-
-#include <grpcpp/security/credentials.h>
-#include <grpcpp/support/config.h>
-
-namespace grpc {
-namespace testing {
-
-class CliCredentials {
- public:
- virtual ~CliCredentials() {}
- std::shared_ptr<grpc::ChannelCredentials> GetCredentials() const;
- virtual TString GetCredentialUsage() const;
- virtual TString GetSslTargetNameOverride() const;
-
- protected:
- // Returns the appropriate channel_creds_type value for the set of legacy
- // flag arguments.
- virtual TString GetDefaultChannelCredsType() const;
- // Returns the appropriate call_creds value for the set of legacy flag
- // arguments.
- virtual TString GetDefaultCallCreds() const;
- // Returns the base transport channel credentials. Child classes can override
- // to support additional channel_creds_types unknown to this base class.
- virtual std::shared_ptr<grpc::ChannelCredentials> GetChannelCredentials()
- const;
- // Returns call credentials to composite onto the base transport channel
- // credentials. Child classes can override to support additional
- // authentication flags unknown to this base class.
- virtual std::shared_ptr<grpc::CallCredentials> GetCallCredentials() const;
-};
-
-} // namespace testing
-} // namespace grpc
-
-#endif // GRPC_TEST_CPP_UTIL_CLI_CREDENTIALS_H
diff --git a/contrib/libs/grpc/test/cpp/util/config_grpc_cli.h b/contrib/libs/grpc/test/cpp/util/config_grpc_cli.h
deleted file mode 100644
index 358884196df..00000000000
--- a/contrib/libs/grpc/test/cpp/util/config_grpc_cli.h
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- *
- * Copyright 2016 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_TEST_CPP_UTIL_CONFIG_GRPC_CLI_H
-#define GRPC_TEST_CPP_UTIL_CONFIG_GRPC_CLI_H
-
-#include <grpcpp/impl/codegen/config_protobuf.h>
-
-#ifndef GRPC_CUSTOM_DYNAMICMESSAGEFACTORY
-#include <google/protobuf/dynamic_message.h>
-#define GRPC_CUSTOM_DYNAMICMESSAGEFACTORY \
- ::google::protobuf::DynamicMessageFactory
-#endif
-
-#ifndef GRPC_CUSTOM_DESCRIPTORPOOLDATABASE
-#include <google/protobuf/descriptor.h>
-#define GRPC_CUSTOM_DESCRIPTORPOOLDATABASE \
- ::google::protobuf::DescriptorPoolDatabase
-#define GRPC_CUSTOM_MERGEDDESCRIPTORDATABASE \
- ::google::protobuf::MergedDescriptorDatabase
-#endif
-
-#ifndef GRPC_CUSTOM_TEXTFORMAT
-#include <google/protobuf/text_format.h>
-#define GRPC_CUSTOM_TEXTFORMAT ::google::protobuf::TextFormat
-#endif
-
-#ifndef GRPC_CUSTOM_DISKSOURCETREE
-#include <google/protobuf/compiler/importer.h>
-#define GRPC_CUSTOM_DISKSOURCETREE ::google::protobuf::compiler::DiskSourceTree
-#define GRPC_CUSTOM_IMPORTER ::google::protobuf::compiler::Importer
-#define GRPC_CUSTOM_MULTIFILEERRORCOLLECTOR \
- ::google::protobuf::compiler::MultiFileErrorCollector
-#endif
-
-namespace grpc {
-namespace protobuf {
-
-typedef GRPC_CUSTOM_DYNAMICMESSAGEFACTORY DynamicMessageFactory;
-
-typedef GRPC_CUSTOM_DESCRIPTORPOOLDATABASE DescriptorPoolDatabase;
-typedef GRPC_CUSTOM_MERGEDDESCRIPTORDATABASE MergedDescriptorDatabase;
-
-typedef GRPC_CUSTOM_TEXTFORMAT TextFormat;
-
-namespace compiler {
-typedef GRPC_CUSTOM_DISKSOURCETREE DiskSourceTree;
-typedef GRPC_CUSTOM_IMPORTER Importer;
-typedef GRPC_CUSTOM_MULTIFILEERRORCOLLECTOR MultiFileErrorCollector;
-} // namespace compiler
-
-} // namespace protobuf
-} // namespace grpc
-
-#endif // GRPC_TEST_CPP_UTIL_CONFIG_GRPC_CLI_H
diff --git a/contrib/libs/grpc/test/cpp/util/grpc_tool.cc b/contrib/libs/grpc/test/cpp/util/grpc_tool.cc
deleted file mode 100644
index 9ea30f32ede..00000000000
--- a/contrib/libs/grpc/test/cpp/util/grpc_tool.cc
+++ /dev/null
@@ -1,1010 +0,0 @@
-/*
- *
- * Copyright 2016 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include <grpc/support/port_platform.h>
-
-#include "test/cpp/util/grpc_tool.h"
-
-#include <cstdio>
-#include <fstream>
-#include <iostream>
-#include <memory>
-#include <sstream>
-#include <util/generic/string.h>
-#include <thread>
-
-#include "y_absl/flags/flag.h"
-#include "y_absl/memory/memory.h"
-
-#include <grpc/grpc.h>
-#include <grpcpp/channel.h>
-#include <grpcpp/create_channel.h>
-#include <grpcpp/grpcpp.h>
-#include <grpcpp/security/credentials.h>
-#include <grpcpp/support/string_ref.h>
-
-#include "test/cpp/util/cli_call.h"
-#include "test/cpp/util/proto_file_parser.h"
-#include "test/cpp/util/proto_reflection_descriptor_database.h"
-#include "test/cpp/util/service_describer.h"
-
-#if GPR_WINDOWS
-#include <io.h>
-#else
-#include <unistd.h>
-#endif
-
-Y_ABSL_FLAG(bool, l, false, "Use a long listing format");
-Y_ABSL_FLAG(bool, remotedb, true,
- "Use server types to parse and format messages");
-Y_ABSL_FLAG(TString, metadata, "",
- "Metadata to send to server, in the form of key1:val1:key2:val2");
-Y_ABSL_FLAG(TString, proto_path, ".",
- "Path to look for the proto file. "
- "Multiple paths can be separated by " GRPC_CLI_PATH_SEPARATOR);
-Y_ABSL_FLAG(TString, protofiles, "", "Name of the proto file.");
-Y_ABSL_FLAG(bool, binary_input, false, "Input in binary format");
-Y_ABSL_FLAG(bool, binary_output, false, "Output in binary format");
-Y_ABSL_FLAG(TString, default_service_config, "",
- "Default service config to use on the channel, if non-empty. Note "
- "that this will be ignored if the name resolver returns a service "
- "config.");
-Y_ABSL_FLAG(bool, display_peer_address, false,
- "Log the peer socket address of the connection that each RPC is made "
- "on to stderr.");
-Y_ABSL_FLAG(bool, json_input, false, "Input in json format");
-Y_ABSL_FLAG(bool, json_output, false, "Output in json format");
-Y_ABSL_FLAG(TString, infile, "", "Input file (default is stdin)");
-Y_ABSL_FLAG(bool, batch, false,
- "Input contains multiple requests. Please do not use this to send "
- "more than a few RPCs. gRPC CLI has very different performance "
- "characteristics compared with normal RPC calls which make it "
- "unsuitable for loadtesting or significant production traffic.");
-// TODO(Capstan): Consider using y_absl::Duration
-Y_ABSL_FLAG(double, timeout, -1,
- "Specify timeout in seconds, used to set the deadline for all "
- "RPCs. The default value of -1 means no deadline has been set.");
-
-namespace grpc {
-namespace testing {
-namespace {
-
-class GrpcTool {
- public:
- explicit GrpcTool();
- virtual ~GrpcTool() {}
-
- bool Help(int argc, const char** argv, const CliCredentials& cred,
- const GrpcToolOutputCallback& callback);
- bool CallMethod(int argc, const char** argv, const CliCredentials& cred,
- const GrpcToolOutputCallback& callback);
- bool ListServices(int argc, const char** argv, const CliCredentials& cred,
- const GrpcToolOutputCallback& callback);
- bool PrintType(int argc, const char** argv, const CliCredentials& cred,
- const GrpcToolOutputCallback& callback);
- // TODO(zyc): implement the following methods
- // bool ListServices(int argc, const char** argv, GrpcToolOutputCallback
- // callback);
- // bool PrintTypeId(int argc, const char** argv, GrpcToolOutputCallback
- // callback);
- bool ParseMessage(int argc, const char** argv, const CliCredentials& cred,
- const GrpcToolOutputCallback& callback);
- bool ToText(int argc, const char** argv, const CliCredentials& cred,
- const GrpcToolOutputCallback& callback);
- bool ToJson(int argc, const char** argv, const CliCredentials& cred,
- const GrpcToolOutputCallback& callback);
- bool ToBinary(int argc, const char** argv, const CliCredentials& cred,
- const GrpcToolOutputCallback& callback);
-
- void SetPrintCommandMode(int exit_status) {
- print_command_usage_ = true;
- usage_exit_status_ = exit_status;
- }
-
- private:
- void CommandUsage(const TString& usage) const;
- bool print_command_usage_;
- int usage_exit_status_;
- const TString cred_usage_;
-};
-
-template <typename T>
-std::function<bool(GrpcTool*, int, const char**, const CliCredentials&,
- GrpcToolOutputCallback)>
-BindWith5Args(T&& func) {
- return std::bind(std::forward<T>(func), std::placeholders::_1,
- std::placeholders::_2, std::placeholders::_3,
- std::placeholders::_4, std::placeholders::_5);
-}
-
-template <typename T>
-size_t ArraySize(T& a) {
- return ((sizeof(a) / sizeof(*(a))) /
- static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))));
-}
-
-void ParseMetadataFlag(
- std::multimap<TString, TString>* client_metadata) {
- if (y_absl::GetFlag(FLAGS_metadata).empty()) {
- return;
- }
- std::vector<TString> fields;
- const char delim = ':';
- const char escape = '\\';
- size_t cur = -1;
- std::stringstream ss;
- while (++cur < y_absl::GetFlag(FLAGS_metadata).length()) {
- switch (y_absl::GetFlag(FLAGS_metadata).at(cur)) {
- case escape:
- if (cur < y_absl::GetFlag(FLAGS_metadata).length() - 1) {
- char c = y_absl::GetFlag(FLAGS_metadata).at(++cur);
- if (c == delim || c == escape) {
- ss << c;
- continue;
- }
- }
- fprintf(stderr, "Failed to parse metadata flag.\n");
- exit(1);
- case delim:
- fields.push_back(ss.str());
- ss.str("");
- ss.clear();
- break;
- default:
- ss << y_absl::GetFlag(FLAGS_metadata).at(cur);
- }
- }
- fields.push_back(ss.str());
- if (fields.size() % 2) {
- fprintf(stderr, "Failed to parse metadata flag.\n");
- exit(1);
- }
- for (size_t i = 0; i < fields.size(); i += 2) {
- client_metadata->insert(
- std::pair<TString, TString>(fields[i], fields[i + 1]));
- }
-}
-
-template <typename T>
-void PrintMetadata(const T& m, const TString& message) {
- if (m.empty()) {
- return;
- }
- fprintf(stderr, "%s\n", message.c_str());
- TString pair;
- for (typename T::const_iterator iter = m.begin(); iter != m.end(); ++iter) {
- pair.clear();
- pair.append(iter->first.data(), iter->first.size());
- pair.append(" : ");
- pair.append(iter->second.data(), iter->second.size());
- fprintf(stderr, "%s\n", pair.c_str());
- }
-}
-
-void ReadResponse(CliCall* call, const TString& method_name,
- const GrpcToolOutputCallback& callback,
- ProtoFileParser* parser, gpr_mu* parser_mu, bool print_mode) {
- TString serialized_response_proto;
- std::multimap<grpc::string_ref, grpc::string_ref> server_initial_metadata;
-
- for (bool receive_initial_metadata = true; call->ReadAndMaybeNotifyWrite(
- &serialized_response_proto,
- receive_initial_metadata ? &server_initial_metadata : nullptr);
- receive_initial_metadata = false) {
- fprintf(stderr, "got response.\n");
- if (!y_absl::GetFlag(FLAGS_binary_output)) {
- gpr_mu_lock(parser_mu);
- serialized_response_proto = parser->GetFormattedStringFromMethod(
- method_name, serialized_response_proto, false /* is_request */,
- y_absl::GetFlag(FLAGS_json_output));
- if (parser->HasError() && print_mode) {
- fprintf(stderr, "Failed to parse response.\n");
- }
- gpr_mu_unlock(parser_mu);
- }
- if (receive_initial_metadata) {
- PrintMetadata(server_initial_metadata,
- "Received initial metadata from server:");
- }
- if (!callback(serialized_response_proto) && print_mode) {
- fprintf(stderr, "Failed to output response.\n");
- }
- }
-}
-
-std::shared_ptr<grpc::Channel> CreateCliChannel(
- const TString& server_address, const CliCredentials& cred) {
- grpc::ChannelArguments args;
- if (!cred.GetSslTargetNameOverride().empty()) {
- args.SetSslTargetNameOverride(cred.GetSslTargetNameOverride());
- }
- if (!y_absl::GetFlag(FLAGS_default_service_config).empty()) {
- args.SetString(GRPC_ARG_SERVICE_CONFIG,
- y_absl::GetFlag(FLAGS_default_service_config).c_str());
- }
- // See |GRPC_ARG_MAX_METADATA_SIZE| in |grpc_types.h|.
- // Set to large enough size (10M) that should work for most use cases.
- args.SetInt(GRPC_ARG_MAX_METADATA_SIZE, 10 * 1024 * 1024);
- return ::grpc::CreateCustomChannel(server_address, cred.GetCredentials(),
- args);
-}
-
-struct Command {
- const char* command;
- std::function<bool(GrpcTool*, int, const char**, const CliCredentials&,
- GrpcToolOutputCallback)>
- function;
- int min_args;
- int max_args;
-};
-
-const Command ops[] = {
- {"help", BindWith5Args(&GrpcTool::Help), 0, INT_MAX},
- {"ls", BindWith5Args(&GrpcTool::ListServices), 1, 3},
- {"list", BindWith5Args(&GrpcTool::ListServices), 1, 3},
- {"call", BindWith5Args(&GrpcTool::CallMethod), 2, 3},
- {"type", BindWith5Args(&GrpcTool::PrintType), 2, 2},
- {"parse", BindWith5Args(&GrpcTool::ParseMessage), 2, 3},
- {"totext", BindWith5Args(&GrpcTool::ToText), 2, 3},
- {"tobinary", BindWith5Args(&GrpcTool::ToBinary), 2, 3},
- {"tojson", BindWith5Args(&GrpcTool::ToJson), 2, 3},
-};
-
-void Usage(const TString& msg) {
- fprintf(
- stderr,
- "%s\n"
- " grpc_cli ls ... ; List services\n"
- " grpc_cli call ... ; Call method\n"
- " grpc_cli type ... ; Print type\n"
- " grpc_cli parse ... ; Parse message\n"
- " grpc_cli totext ... ; Convert binary message to text\n"
- " grpc_cli tojson ... ; Convert binary message to json\n"
- " grpc_cli tobinary ... ; Convert text message to binary\n"
- " grpc_cli help ... ; Print this message, or per-command usage\n"
- "\n",
- msg.c_str());
-
- exit(1);
-}
-
-const Command* FindCommand(const TString& name) {
- for (int i = 0; i < static_cast<int>(ArraySize(ops)); i++) {
- if (name == ops[i].command) {
- return &ops[i];
- }
- }
- return nullptr;
-}
-} // namespace
-
-int GrpcToolMainLib(int argc, const char** argv, const CliCredentials& cred,
- const GrpcToolOutputCallback& callback) {
- if (argc < 2) {
- Usage("No command specified");
- }
-
- TString command = argv[1];
- argc -= 2;
- argv += 2;
-
- const Command* cmd = FindCommand(command);
- if (cmd != nullptr) {
- GrpcTool grpc_tool;
- if (argc < cmd->min_args || argc > cmd->max_args) {
- // Force the command to print its usage message
- fprintf(stderr, "\nWrong number of arguments for %s\n", command.c_str());
- grpc_tool.SetPrintCommandMode(1);
- return cmd->function(&grpc_tool, -1, nullptr, cred, callback);
- }
- const bool ok = cmd->function(&grpc_tool, argc, argv, cred, callback);
- return ok ? 0 : 1;
- } else {
- Usage("Invalid command '" + TString(command.c_str()) + "'");
- }
- return 1;
-}
-
-GrpcTool::GrpcTool() : print_command_usage_(false), usage_exit_status_(0) {}
-
-void GrpcTool::CommandUsage(const TString& usage) const {
- if (print_command_usage_) {
- fprintf(stderr, "\n%s%s\n", usage.c_str(),
- (usage.empty() || usage[usage.size() - 1] != '\n') ? "\n" : "");
- exit(usage_exit_status_);
- }
-}
-
-bool GrpcTool::Help(int argc, const char** argv, const CliCredentials& cred,
- const GrpcToolOutputCallback& callback) {
- CommandUsage(
- "Print help\n"
- " grpc_cli help [subcommand]\n");
-
- if (argc == 0) {
- Usage("");
- } else {
- const Command* cmd = FindCommand(argv[0]);
- if (cmd == nullptr) {
- Usage("Unknown command '" + TString(argv[0]) + "'");
- }
- SetPrintCommandMode(0);
- cmd->function(this, -1, nullptr, cred, callback);
- }
- return true;
-}
-
-bool GrpcTool::ListServices(int argc, const char** argv,
- const CliCredentials& cred,
- const GrpcToolOutputCallback& callback) {
- CommandUsage(
- "List services\n"
- " grpc_cli ls <address> [<service>[/<method>]]\n"
- " <address> ; host:port\n"
- " <service> ; Exported service name\n"
- " <method> ; Method name\n"
- " --l ; Use a long listing format\n"
- " --outfile ; Output filename (defaults to stdout)\n" +
- cred.GetCredentialUsage());
-
- TString server_address(argv[0]);
- std::shared_ptr<grpc::Channel> channel =
- CreateCliChannel(server_address, cred);
- grpc::ProtoReflectionDescriptorDatabase desc_db(channel);
- grpc::protobuf::DescriptorPool desc_pool(&desc_db);
-
- std::vector<TString> service_list;
- if (!desc_db.GetServices(&service_list)) {
- fprintf(stderr, "Received an error when querying services endpoint.\n");
- return false;
- }
-
- // If no service is specified, dump the list of services.
- TString output;
- if (argc < 2) {
- // List all services, if --l is passed, then include full description,
- // otherwise include a summarized list only.
- if (y_absl::GetFlag(FLAGS_l)) {
- output = DescribeServiceList(service_list, desc_pool);
- } else {
- for (auto it = service_list.begin(); it != service_list.end(); it++) {
- auto const& service = *it;
- output.append(service);
- output.append("\n");
- }
- }
- } else {
- std::string service_name;
- std::string method_name;
- std::stringstream ss(argv[1]);
-
- // Remove leading slashes.
- while (ss.peek() == '/') {
- ss.get();
- }
-
- // Parse service and method names. Support the following patterns:
- // Service
- // Service Method
- // Service.Method
- // Service/Method
- if (argc == 3) {
- std::getline(ss, service_name, '/');
- method_name = argv[2];
- } else {
- if (std::getline(ss, service_name, '/')) {
- std::getline(ss, method_name);
- }
- }
-
- const grpc::protobuf::ServiceDescriptor* service =
- desc_pool.FindServiceByName(google::protobuf::string(service_name));
- if (service != nullptr) {
- if (method_name.empty()) {
- output = y_absl::GetFlag(FLAGS_l) ? DescribeService(service)
- : SummarizeService(service);
- } else {
- method_name.insert(0, ".");
- method_name.insert(0, service_name);
- const grpc::protobuf::MethodDescriptor* method =
- desc_pool.FindMethodByName(google::protobuf::string(method_name));
- if (method != nullptr) {
- output = y_absl::GetFlag(FLAGS_l) ? DescribeMethod(method)
- : SummarizeMethod(method);
- } else {
- fprintf(stderr, "Method %s not found in service %s.\n",
- method_name.c_str(), service_name.c_str());
- return false;
- }
- }
- } else {
- if (!method_name.empty()) {
- fprintf(stderr, "Service %s not found.\n", service_name.c_str());
- return false;
- } else {
- const grpc::protobuf::MethodDescriptor* method =
- desc_pool.FindMethodByName(google::protobuf::string(service_name));
- if (method != nullptr) {
- output = y_absl::GetFlag(FLAGS_l) ? DescribeMethod(method)
- : SummarizeMethod(method);
- } else {
- fprintf(stderr, "Service or method %s not found.\n",
- service_name.c_str());
- return false;
- }
- }
- }
- }
- return callback(output);
-}
-
-bool GrpcTool::PrintType(int /*argc*/, const char** argv,
- const CliCredentials& cred,
- const GrpcToolOutputCallback& callback) {
- CommandUsage(
- "Print type\n"
- " grpc_cli type <address> <type>\n"
- " <address> ; host:port\n"
- " <type> ; Protocol buffer type name\n" +
- cred.GetCredentialUsage());
-
- TString server_address(argv[0]);
- std::shared_ptr<grpc::Channel> channel =
- CreateCliChannel(server_address, cred);
- grpc::ProtoReflectionDescriptorDatabase desc_db(channel);
- grpc::protobuf::DescriptorPool desc_pool(&desc_db);
-
- TString output;
- const grpc::protobuf::Descriptor* descriptor =
- desc_pool.FindMessageTypeByName(argv[1]);
- if (descriptor != nullptr) {
- output = descriptor->DebugString();
- } else {
- fprintf(stderr, "Type %s not found.\n", argv[1]);
- return false;
- }
- return callback(output);
-}
-
-bool GrpcTool::CallMethod(int argc, const char** argv,
- const CliCredentials& cred,
- const GrpcToolOutputCallback& callback) {
- CommandUsage(
- "Call method\n"
- " grpc_cli call <address> <service>[.<method>] <request>\n"
- " <address> ; host:port\n"
- " <service> ; Exported service name\n"
- " <method> ; Method name\n"
- " <request> ; Text protobuffer (overrides infile)\n"
- " --protofiles ; Comma separated proto files used as a"
- " fallback when parsing request/response\n"
- " --proto_path ; The search paths of proto files"
- " (" GRPC_CLI_PATH_SEPARATOR
- " separated), valid only when --protofiles is given\n"
- " --noremotedb ; Don't attempt to use reflection service"
- " at all\n"
- " --metadata ; The metadata to be sent to the server\n"
- " --infile ; Input filename (defaults to stdin)\n"
- " --outfile ; Output filename (defaults to stdout)\n"
- " --binary_input ; Input in binary format\n"
- " --binary_output ; Output in binary format\n"
- " --json_input ; Input in json format\n"
- " --json_output ; Output in json format\n"
- " --timeout ; Specify timeout (in seconds), used to "
- "set the deadline for RPCs. The default value of -1 means no "
- "deadline has been set.\n" +
- cred.GetCredentialUsage());
-
- std::stringstream output_ss;
- TString request_text;
- TString server_address(argv[0]);
- TString method_name(argv[1]);
- TString formatted_method_name;
- std::unique_ptr<ProtoFileParser> parser;
- TString serialized_request_proto;
- CliArgs cli_args;
- cli_args.timeout = y_absl::GetFlag(FLAGS_timeout);
- bool print_mode = false;
-
- std::shared_ptr<grpc::Channel> channel =
- CreateCliChannel(server_address, cred);
-
- if (!y_absl::GetFlag(FLAGS_binary_input) ||
- !y_absl::GetFlag(FLAGS_binary_output)) {
- parser = y_absl::make_unique<grpc::testing::ProtoFileParser>(
- y_absl::GetFlag(FLAGS_remotedb) ? channel : nullptr,
- y_absl::GetFlag(FLAGS_proto_path), y_absl::GetFlag(FLAGS_protofiles));
- if (parser->HasError()) {
- fprintf(
- stderr,
- "Failed to find remote reflection service and local proto files.\n");
- return false;
- }
- }
-
- if (y_absl::GetFlag(FLAGS_binary_input)) {
- formatted_method_name = method_name;
- } else {
- formatted_method_name = parser->GetFormattedMethodName(method_name);
- if (parser->HasError()) {
- fprintf(stderr, "Failed to find method %s in proto files.\n",
- method_name.c_str());
- }
- }
-
- if (argc == 3) {
- request_text = argv[2];
- }
-
- if (parser->IsStreaming(method_name, true /* is_request */)) {
- std::istream* input_stream;
- std::ifstream input_file;
-
- if (y_absl::GetFlag(FLAGS_batch)) {
- fprintf(stderr, "Batch mode for streaming RPC is not supported.\n");
- return false;
- }
-
- std::multimap<TString, TString> client_metadata;
- ParseMetadataFlag(&client_metadata);
- PrintMetadata(client_metadata, "Sending client initial metadata:");
-
- CliCall call(channel, formatted_method_name, client_metadata, cli_args);
- if (y_absl::GetFlag(FLAGS_display_peer_address)) {
- fprintf(stderr, "New call for method_name:%s has peer address:|%s|\n",
- formatted_method_name.c_str(), call.peer().c_str());
- }
-
- if (y_absl::GetFlag(FLAGS_infile).empty()) {
- if (isatty(fileno(stdin))) {
- print_mode = true;
- fprintf(stderr, "reading streaming request message from stdin...\n");
- }
- input_stream = &std::cin;
- } else {
- input_file.open(y_absl::GetFlag(FLAGS_infile),
- std::ios::in | std::ios::binary);
- input_stream = &input_file;
- }
-
- gpr_mu parser_mu;
- gpr_mu_init(&parser_mu);
- std::thread read_thread(ReadResponse, &call, method_name, callback,
- parser.get(), &parser_mu, print_mode);
-
- std::stringstream request_ss;
- std::string line;
- while (!request_text.empty() ||
- (!input_stream->eof() && getline(*input_stream, line))) {
- if (!request_text.empty()) {
- if (y_absl::GetFlag(FLAGS_binary_input)) {
- serialized_request_proto = request_text;
- request_text.clear();
- } else {
- gpr_mu_lock(&parser_mu);
- serialized_request_proto = parser->GetSerializedProtoFromMethod(
- method_name, request_text, true /* is_request */,
- y_absl::GetFlag(FLAGS_json_input));
- request_text.clear();
- if (parser->HasError()) {
- if (print_mode) {
- fprintf(stderr, "Failed to parse request.\n");
- }
- gpr_mu_unlock(&parser_mu);
- continue;
- }
- gpr_mu_unlock(&parser_mu);
- }
-
- call.WriteAndWait(serialized_request_proto);
- if (print_mode) {
- fprintf(stderr, "Request sent.\n");
- }
- } else {
- if (line.length() == 0) {
- request_text = request_ss.str();
- request_ss.str(TString());
- request_ss.clear();
- } else {
- request_ss << line << ' ';
- }
- }
- }
- if (input_file.is_open()) {
- input_file.close();
- }
-
- call.WritesDoneAndWait();
- read_thread.join();
- gpr_mu_destroy(&parser_mu);
-
- std::multimap<grpc::string_ref, grpc::string_ref> server_trailing_metadata;
- Status status = call.Finish(&server_trailing_metadata);
- PrintMetadata(server_trailing_metadata,
- "Received trailing metadata from server:");
-
- if (status.ok()) {
- fprintf(stderr, "Stream RPC succeeded with OK status\n");
- return true;
- } else {
- fprintf(stderr, "Rpc failed with status code %d, error message: %s\n",
- status.error_code(), status.error_message().c_str());
- return false;
- }
-
- } else { // parser->IsStreaming(method_name, true /* is_request */)
- if (y_absl::GetFlag(FLAGS_batch)) {
- if (parser->IsStreaming(method_name, false /* is_request */)) {
- fprintf(stderr, "Batch mode for streaming RPC is not supported.\n");
- return false;
- }
-
- std::istream* input_stream;
- std::ifstream input_file;
-
- if (y_absl::GetFlag(FLAGS_infile).empty()) {
- if (isatty(fileno(stdin))) {
- print_mode = true;
- fprintf(stderr, "reading request messages from stdin...\n");
- }
- input_stream = &std::cin;
- } else {
- input_file.open(y_absl::GetFlag(FLAGS_infile),
- std::ios::in | std::ios::binary);
- input_stream = &input_file;
- }
-
- std::multimap<TString, TString> client_metadata;
- ParseMetadataFlag(&client_metadata);
- if (print_mode) {
- PrintMetadata(client_metadata, "Sending client initial metadata:");
- }
-
- std::stringstream request_ss;
- std::string line;
- while (!request_text.empty() ||
- (!input_stream->eof() && getline(*input_stream, line))) {
- if (!request_text.empty()) {
- if (y_absl::GetFlag(FLAGS_binary_input)) {
- serialized_request_proto = request_text;
- request_text.clear();
- } else {
- serialized_request_proto = parser->GetSerializedProtoFromMethod(
- method_name, request_text, true /* is_request */,
- y_absl::GetFlag(FLAGS_json_input));
- request_text.clear();
- if (parser->HasError()) {
- if (print_mode) {
- fprintf(stderr, "Failed to parse request.\n");
- }
- continue;
- }
- }
-
- TString serialized_response_proto;
- std::multimap<grpc::string_ref, grpc::string_ref>
- server_initial_metadata, server_trailing_metadata;
- CliCall call(channel, formatted_method_name, client_metadata,
- cli_args);
- if (y_absl::GetFlag(FLAGS_display_peer_address)) {
- fprintf(stderr,
- "New call for method_name:%s has peer address:|%s|\n",
- formatted_method_name.c_str(), call.peer().c_str());
- }
- call.Write(serialized_request_proto);
- call.WritesDone();
- if (!call.Read(&serialized_response_proto,
- &server_initial_metadata)) {
- fprintf(stderr, "Failed to read response.\n");
- }
- Status status = call.Finish(&server_trailing_metadata);
-
- if (status.ok()) {
- if (print_mode) {
- fprintf(stderr, "Rpc succeeded with OK status.\n");
- PrintMetadata(server_initial_metadata,
- "Received initial metadata from server:");
- PrintMetadata(server_trailing_metadata,
- "Received trailing metadata from server:");
- }
-
- if (y_absl::GetFlag(FLAGS_binary_output)) {
- if (!callback(serialized_response_proto)) {
- break;
- }
- } else {
- TString response_text = parser->GetFormattedStringFromMethod(
- method_name, serialized_response_proto,
- false /* is_request */, y_absl::GetFlag(FLAGS_json_output));
-
- if (parser->HasError() && print_mode) {
- fprintf(stderr, "Failed to parse response.\n");
- } else {
- if (!callback(response_text)) {
- break;
- }
- }
- }
- } else {
- if (print_mode) {
- fprintf(stderr,
- "Rpc failed with status code %d, error message: %s\n",
- status.error_code(), status.error_message().c_str());
- }
- }
- } else {
- if (line.length() == 0) {
- request_text = request_ss.str();
- request_ss.str(TString());
- request_ss.clear();
- } else {
- request_ss << line << ' ';
- }
- }
- }
-
- if (input_file.is_open()) {
- input_file.close();
- }
-
- return true;
- }
-
- if (argc == 3) {
- if (!y_absl::GetFlag(FLAGS_infile).empty()) {
- fprintf(stderr, "warning: request given in argv, ignoring --infile\n");
- }
- } else {
- std::stringstream input_stream;
- if (y_absl::GetFlag(FLAGS_infile).empty()) {
- if (isatty(fileno(stdin))) {
- fprintf(stderr, "reading request message from stdin...\n");
- }
- input_stream << std::cin.rdbuf();
- } else {
- std::ifstream input_file(y_absl::GetFlag(FLAGS_infile),
- std::ios::in | std::ios::binary);
- input_stream << input_file.rdbuf();
- input_file.close();
- }
- request_text = input_stream.str();
- }
-
- if (y_absl::GetFlag(FLAGS_binary_input)) {
- serialized_request_proto = request_text;
- } else {
- serialized_request_proto = parser->GetSerializedProtoFromMethod(
- method_name, request_text, true /* is_request */,
- y_absl::GetFlag(FLAGS_json_input));
- if (parser->HasError()) {
- fprintf(stderr, "Failed to parse request.\n");
- return false;
- }
- }
- fprintf(stderr, "connecting to %s\n", server_address.c_str());
-
- TString serialized_response_proto;
- std::multimap<TString, TString> client_metadata;
- std::multimap<grpc::string_ref, grpc::string_ref> server_initial_metadata,
- server_trailing_metadata;
- ParseMetadataFlag(&client_metadata);
- PrintMetadata(client_metadata, "Sending client initial metadata:");
-
- CliCall call(channel, formatted_method_name, client_metadata, cli_args);
- if (y_absl::GetFlag(FLAGS_display_peer_address)) {
- fprintf(stderr, "New call for method_name:%s has peer address:|%s|\n",
- formatted_method_name.c_str(), call.peer().c_str());
- }
- call.Write(serialized_request_proto);
- call.WritesDone();
-
- for (bool receive_initial_metadata = true; call.Read(
- &serialized_response_proto,
- receive_initial_metadata ? &server_initial_metadata : nullptr);
- receive_initial_metadata = false) {
- if (!y_absl::GetFlag(FLAGS_binary_output)) {
- serialized_response_proto = parser->GetFormattedStringFromMethod(
- method_name, serialized_response_proto, false /* is_request */,
- y_absl::GetFlag(FLAGS_json_output));
- if (parser->HasError()) {
- fprintf(stderr, "Failed to parse response.\n");
- return false;
- }
- }
-
- if (receive_initial_metadata) {
- PrintMetadata(server_initial_metadata,
- "Received initial metadata from server:");
- }
- if (!callback(serialized_response_proto)) {
- return false;
- }
- }
- Status status = call.Finish(&server_trailing_metadata);
- PrintMetadata(server_trailing_metadata,
- "Received trailing metadata from server:");
- if (status.ok()) {
- fprintf(stderr, "Rpc succeeded with OK status\n");
- return true;
- } else {
- fprintf(stderr, "Rpc failed with status code %d, error message: %s\n",
- status.error_code(), status.error_message().c_str());
- return false;
- }
- }
- GPR_UNREACHABLE_CODE(return false);
-}
-
-bool GrpcTool::ParseMessage(int argc, const char** argv,
- const CliCredentials& cred,
- const GrpcToolOutputCallback& callback) {
- CommandUsage(
- "Parse message\n"
- " grpc_cli parse <address> <type> [<message>]\n"
- " <address> ; host:port\n"
- " <type> ; Protocol buffer type name\n"
- " <message> ; Text protobuffer (overrides --infile)\n"
- " --protofiles ; Comma separated proto files used as a"
- " fallback when parsing request/response\n"
- " --proto_path ; The search paths of proto files"
- " (" GRPC_CLI_PATH_SEPARATOR
- " separated), valid only when --protofiles is given\n"
- " --noremotedb ; Don't attempt to use reflection service"
- " at all\n"
- " --infile ; Input filename (defaults to stdin)\n"
- " --outfile ; Output filename (defaults to stdout)\n"
- " --binary_input ; Input in binary format\n"
- " --binary_output ; Output in binary format\n"
- " --json_input ; Input in json format\n"
- " --json_output ; Output in json format\n" +
- cred.GetCredentialUsage());
-
- std::stringstream output_ss;
- TString message_text;
- TString server_address(argv[0]);
- TString type_name(argv[1]);
- std::unique_ptr<grpc::testing::ProtoFileParser> parser;
- TString serialized_request_proto;
-
- if (argc == 3) {
- message_text = argv[2];
- if (!y_absl::GetFlag(FLAGS_infile).empty()) {
- fprintf(stderr, "warning: message given in argv, ignoring --infile.\n");
- }
- } else {
- std::stringstream input_stream;
- if (y_absl::GetFlag(FLAGS_infile).empty()) {
- if (isatty(fileno(stdin))) {
- fprintf(stderr, "reading request message from stdin...\n");
- }
- input_stream << std::cin.rdbuf();
- } else {
- std::ifstream input_file(y_absl::GetFlag(FLAGS_infile),
- std::ios::in | std::ios::binary);
- input_stream << input_file.rdbuf();
- input_file.close();
- }
- message_text = input_stream.str();
- }
-
- if (!y_absl::GetFlag(FLAGS_binary_input) ||
- !y_absl::GetFlag(FLAGS_binary_output)) {
- std::shared_ptr<grpc::Channel> channel =
- CreateCliChannel(server_address, cred);
- parser = y_absl::make_unique<grpc::testing::ProtoFileParser>(
- y_absl::GetFlag(FLAGS_remotedb) ? channel : nullptr,
- y_absl::GetFlag(FLAGS_proto_path), y_absl::GetFlag(FLAGS_protofiles));
- if (parser->HasError()) {
- fprintf(
- stderr,
- "Failed to find remote reflection service and local proto files.\n");
- return false;
- }
- }
-
- if (y_absl::GetFlag(FLAGS_binary_input)) {
- serialized_request_proto = message_text;
- } else {
- serialized_request_proto = parser->GetSerializedProtoFromMessageType(
- type_name, message_text, y_absl::GetFlag(FLAGS_json_input));
- if (parser->HasError()) {
- fprintf(stderr, "Failed to serialize the message.\n");
- return false;
- }
- }
-
- if (y_absl::GetFlag(FLAGS_binary_output)) {
- output_ss << serialized_request_proto;
- } else {
- TString output_text;
- output_text = parser->GetFormattedStringFromMessageType(
- type_name, serialized_request_proto, y_absl::GetFlag(FLAGS_json_output));
- if (parser->HasError()) {
- fprintf(stderr, "Failed to deserialize the message.\n");
- return false;
- }
-
- output_ss << output_text << std::endl;
- }
-
- return callback(output_ss.str());
-}
-
-bool GrpcTool::ToText(int argc, const char** argv, const CliCredentials& cred,
- const GrpcToolOutputCallback& callback) {
- CommandUsage(
- "Convert binary message to text\n"
- " grpc_cli totext <protofiles> <type>\n"
- " <protofiles> ; Comma separated list of proto files\n"
- " <type> ; Protocol buffer type name\n"
- " --proto_path ; The search paths of proto files"
- " (" GRPC_CLI_PATH_SEPARATOR
- " separated)\n"
- " --infile ; Input filename (defaults to stdin)\n"
- " --outfile ; Output filename (defaults to stdout)\n");
-
- y_absl::SetFlag(&FLAGS_protofiles, argv[0]);
- y_absl::SetFlag(&FLAGS_remotedb, false);
- y_absl::SetFlag(&FLAGS_binary_input, true);
- y_absl::SetFlag(&FLAGS_binary_output, false);
- return ParseMessage(argc, argv, cred, callback);
-}
-
-bool GrpcTool::ToJson(int argc, const char** argv, const CliCredentials& cred,
- const GrpcToolOutputCallback& callback) {
- CommandUsage(
- "Convert binary message to json\n"
- " grpc_cli tojson <protofiles> <type>\n"
- " <protofiles> ; Comma separated list of proto files\n"
- " <type> ; Protocol buffer type name\n"
- " --proto_path ; The search paths of proto files"
- " (" GRPC_CLI_PATH_SEPARATOR
- " separated)\n"
- " --infile ; Input filename (defaults to stdin)\n"
- " --outfile ; Output filename (defaults to stdout)\n");
-
- y_absl::SetFlag(&FLAGS_protofiles, argv[0]);
- y_absl::SetFlag(&FLAGS_remotedb, false);
- y_absl::SetFlag(&FLAGS_binary_input, true);
- y_absl::SetFlag(&FLAGS_binary_output, false);
- y_absl::SetFlag(&FLAGS_json_output, true);
- return ParseMessage(argc, argv, cred, callback);
-}
-
-bool GrpcTool::ToBinary(int argc, const char** argv, const CliCredentials& cred,
- const GrpcToolOutputCallback& callback) {
- CommandUsage(
- "Convert text message to binary\n"
- " grpc_cli tobinary <protofiles> <type> [<message>]\n"
- " <protofiles> ; Comma separated list of proto files\n"
- " <type> ; Protocol buffer type name\n"
- " --proto_path ; The search paths of proto files"
- " (" GRPC_CLI_PATH_SEPARATOR
- " separated)\n"
- " --infile ; Input filename (defaults to stdin)\n"
- " --outfile ; Output filename (defaults to stdout)\n");
-
- y_absl::SetFlag(&FLAGS_protofiles, argv[0]);
- y_absl::SetFlag(&FLAGS_remotedb, false);
- y_absl::SetFlag(&FLAGS_binary_input, false);
- y_absl::SetFlag(&FLAGS_binary_output, true);
- return ParseMessage(argc, argv, cred, callback);
-}
-
-} // namespace testing
-} // namespace grpc
diff --git a/contrib/libs/grpc/test/cpp/util/grpc_tool.h b/contrib/libs/grpc/test/cpp/util/grpc_tool.h
deleted file mode 100644
index 7fbbe35c9ec..00000000000
--- a/contrib/libs/grpc/test/cpp/util/grpc_tool.h
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- *
- * Copyright 2016 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_TEST_CPP_UTIL_GRPC_TOOL_H
-#define GRPC_TEST_CPP_UTIL_GRPC_TOOL_H
-
-#include <functional>
-
-#include <grpcpp/support/config.h>
-
-#include "test/cpp/util/cli_credentials.h"
-
-namespace grpc {
-namespace testing {
-
-typedef std::function<bool(const TString&)> GrpcToolOutputCallback;
-
-int GrpcToolMainLib(int argc, const char** argv, const CliCredentials& cred,
- const GrpcToolOutputCallback& callback);
-
-} // namespace testing
-} // namespace grpc
-
-#endif // GRPC_TEST_CPP_UTIL_GRPC_TOOL_H
diff --git a/contrib/libs/grpc/test/cpp/util/proto_file_parser.cc b/contrib/libs/grpc/test/cpp/util/proto_file_parser.cc
deleted file mode 100644
index c324a7688bd..00000000000
--- a/contrib/libs/grpc/test/cpp/util/proto_file_parser.cc
+++ /dev/null
@@ -1,331 +0,0 @@
-/*
- *
- * Copyright 2016 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include "test/cpp/util/proto_file_parser.h"
-
-#include <algorithm>
-#include <iostream>
-#include <sstream>
-#include <unordered_set>
-
-#include "y_absl/memory/memory.h"
-#include "y_absl/strings/str_split.h"
-
-#include <grpcpp/support/config.h>
-
-namespace grpc {
-namespace testing {
-namespace {
-
-// Match the user input method string to the full_name from method descriptor.
-bool MethodNameMatch(const TString& full_name, const TString& input) {
- TString clean_input = input;
- std::replace(clean_input.begin(), clean_input.vend(), '/', '.');
- if (clean_input.size() > full_name.size()) {
- return false;
- }
- return full_name.compare(full_name.size() - clean_input.size(),
- clean_input.size(), clean_input) == 0;
-}
-} // namespace
-
-class ErrorPrinter : public protobuf::compiler::MultiFileErrorCollector {
- public:
- explicit ErrorPrinter(ProtoFileParser* parser) : parser_(parser) {}
-
- void AddError(const google::protobuf::string& filename, int line, int column,
- const google::protobuf::string& message) override {
- std::ostringstream oss;
- oss << "error " << filename << " " << line << " " << column << " "
- << message << "\n";
- parser_->LogError(oss.str());
- }
-
- void AddWarning(const google::protobuf::string& filename, int line, int column,
- const google::protobuf::string& message) override {
- std::cerr << "warning " << filename << " " << line << " " << column << " "
- << message << std::endl;
- }
-
- private:
- ProtoFileParser* parser_; // not owned
-};
-
-ProtoFileParser::ProtoFileParser(const std::shared_ptr<grpc::Channel>& channel,
- const TString& proto_path,
- const TString& protofiles)
- : has_error_(false),
- dynamic_factory_(new protobuf::DynamicMessageFactory()) {
- std::vector<TString> service_list;
- if (channel) {
- reflection_db_ =
- y_absl::make_unique<grpc::ProtoReflectionDescriptorDatabase>(channel);
- reflection_db_->GetServices(&service_list);
- }
-
- std::unordered_set<TString> known_services;
- if (!protofiles.empty()) {
- for (const y_absl::string_view single_path : y_absl::StrSplit(
- proto_path, GRPC_CLI_PATH_SEPARATOR, y_absl::AllowEmpty())) {
- source_tree_.MapPath("", google::protobuf::string(single_path));
- }
- error_printer_ = y_absl::make_unique<ErrorPrinter>(this);
- importer_ = y_absl::make_unique<protobuf::compiler::Importer>(
- &source_tree_, error_printer_.get());
-
- std::string file_name;
- std::stringstream ss(protofiles);
- while (std::getline(ss, file_name, ',')) {
- const auto* file_desc = importer_->Import(google::protobuf::string(file_name));
- if (file_desc) {
- for (int i = 0; i < file_desc->service_count(); i++) {
- service_desc_list_.push_back(file_desc->service(i));
- known_services.insert(file_desc->service(i)->full_name());
- }
- } else {
- std::cerr << file_name << " not found" << std::endl;
- }
- }
-
- file_db_ =
- y_absl::make_unique<protobuf::DescriptorPoolDatabase>(*importer_->pool());
- }
-
- if (!reflection_db_ && !file_db_) {
- LogError("No available proto database");
- return;
- }
-
- if (!reflection_db_) {
- desc_db_ = std::move(file_db_);
- } else if (!file_db_) {
- desc_db_ = std::move(reflection_db_);
- } else {
- desc_db_ = y_absl::make_unique<protobuf::MergedDescriptorDatabase>(
- reflection_db_.get(), file_db_.get());
- }
-
- desc_pool_ = y_absl::make_unique<protobuf::DescriptorPool>(desc_db_.get());
-
- for (auto it = service_list.begin(); it != service_list.end(); it++) {
- if (known_services.find(*it) == known_services.end()) {
- if (const protobuf::ServiceDescriptor* service_desc =
- desc_pool_->FindServiceByName(google::protobuf::string(*it))) {
- service_desc_list_.push_back(service_desc);
- known_services.insert(*it);
- }
- }
- }
-}
-
-ProtoFileParser::~ProtoFileParser() {}
-
-TString ProtoFileParser::GetFullMethodName(const TString& method) {
- has_error_ = false;
-
- if (known_methods_.find(method) != known_methods_.end()) {
- return known_methods_[method];
- }
-
- const protobuf::MethodDescriptor* method_descriptor = nullptr;
- for (auto it = service_desc_list_.begin(); it != service_desc_list_.end();
- it++) {
- const auto* service_desc = *it;
- for (int j = 0; j < service_desc->method_count(); j++) {
- const auto* method_desc = service_desc->method(j);
- if (MethodNameMatch(method_desc->full_name(), method)) {
- if (method_descriptor) {
- std::ostringstream error_stream;
- error_stream << "Ambiguous method names: ";
- error_stream << method_descriptor->full_name() << " ";
- error_stream << method_desc->full_name();
- LogError(error_stream.str());
- }
- method_descriptor = method_desc;
- }
- }
- }
- if (!method_descriptor) {
- LogError("Method name not found");
- }
- if (has_error_) {
- return "";
- }
-
- known_methods_[method] = method_descriptor->full_name();
-
- return method_descriptor->full_name();
-}
-
-TString ProtoFileParser::GetFormattedMethodName(const TString& method) {
- has_error_ = false;
- TString formatted_method_name = GetFullMethodName(method);
- if (has_error_) {
- return "";
- }
- size_t last_dot = formatted_method_name.find_last_of('.');
- if (last_dot != TString::npos) {
- formatted_method_name[last_dot] = '/';
- }
- formatted_method_name.insert(formatted_method_name.begin(), '/');
- return formatted_method_name;
-}
-
-TString ProtoFileParser::GetMessageTypeFromMethod(const TString& method,
- bool is_request) {
- has_error_ = false;
- TString full_method_name = GetFullMethodName(method);
- if (has_error_) {
- return "";
- }
- const protobuf::MethodDescriptor* method_desc =
- desc_pool_->FindMethodByName(google::protobuf::string(full_method_name));
- if (!method_desc) {
- LogError("Method not found");
- return "";
- }
-
- return is_request ? method_desc->input_type()->full_name()
- : method_desc->output_type()->full_name();
-}
-
-bool ProtoFileParser::IsStreaming(const TString& method, bool is_request) {
- has_error_ = false;
-
- TString full_method_name = GetFullMethodName(method);
- if (has_error_) {
- return false;
- }
-
- const protobuf::MethodDescriptor* method_desc =
- desc_pool_->FindMethodByName(google::protobuf::string(full_method_name));
- if (!method_desc) {
- LogError("Method not found");
- return false;
- }
-
- return is_request ? method_desc->client_streaming()
- : method_desc->server_streaming();
-}
-
-TString ProtoFileParser::GetSerializedProtoFromMethod(
- const TString& method, const TString& formatted_proto,
- bool is_request, bool is_json_format) {
- has_error_ = false;
- TString message_type_name = GetMessageTypeFromMethod(method, is_request);
- if (has_error_) {
- return "";
- }
- return GetSerializedProtoFromMessageType(message_type_name, formatted_proto,
- is_json_format);
-}
-
-TString ProtoFileParser::GetFormattedStringFromMethod(
- const TString& method, const TString& serialized_proto,
- bool is_request, bool is_json_format) {
- has_error_ = false;
- TString message_type_name = GetMessageTypeFromMethod(method, is_request);
- if (has_error_) {
- return "";
- }
- return GetFormattedStringFromMessageType(message_type_name, serialized_proto,
- is_json_format);
-}
-
-TString ProtoFileParser::GetSerializedProtoFromMessageType(
- const TString& message_type_name, const TString& formatted_proto,
- bool is_json_format) {
- has_error_ = false;
- google::protobuf::string serialized;
- const protobuf::Descriptor* desc =
- desc_pool_->FindMessageTypeByName(google::protobuf::string(message_type_name));
- if (!desc) {
- LogError("Message type not found");
- return "";
- }
- std::unique_ptr<grpc::protobuf::Message> msg(
- dynamic_factory_->GetPrototype(desc)->New());
- bool ok;
- if (is_json_format) {
- ok = grpc::protobuf::json::JsonStringToMessage(google::protobuf::string(formatted_proto), msg.get())
- .ok();
- if (!ok) {
- LogError("Failed to convert json format to proto.");
- return "";
- }
- } else {
- ok = protobuf::TextFormat::ParseFromString(google::protobuf::string(formatted_proto), msg.get());
- if (!ok) {
- LogError("Failed to convert text format to proto.");
- return "";
- }
- }
-
- ok = msg->SerializeToString(&serialized);
- if (!ok) {
- LogError("Failed to serialize proto.");
- return "";
- }
- return serialized;
-}
-
-TString ProtoFileParser::GetFormattedStringFromMessageType(
- const TString& message_type_name, const TString& serialized_proto,
- bool is_json_format) {
- has_error_ = false;
- const protobuf::Descriptor* desc =
- desc_pool_->FindMessageTypeByName(google::protobuf::string(message_type_name));
- if (!desc) {
- LogError("Message type not found");
- return "";
- }
- std::unique_ptr<grpc::protobuf::Message> msg(
- dynamic_factory_->GetPrototype(desc)->New());
- if (!msg->ParseFromString(google::protobuf::string(serialized_proto))) {
- LogError("Failed to deserialize proto.");
- return "";
- }
- google::protobuf::string formatted_string;
-
- if (is_json_format) {
- grpc::protobuf::json::JsonPrintOptions jsonPrintOptions;
- jsonPrintOptions.add_whitespace = true;
- if (!grpc::protobuf::json::MessageToJsonString(*msg, &formatted_string,
- jsonPrintOptions)
- .ok()) {
- LogError("Failed to print proto message to json format");
- return "";
- }
- } else {
- if (!protobuf::TextFormat::PrintToString(*msg, &formatted_string)) {
- LogError("Failed to print proto message to text format");
- return "";
- }
- }
- return formatted_string;
-}
-
-void ProtoFileParser::LogError(const TString& error_msg) {
- if (!error_msg.empty()) {
- std::cerr << error_msg << std::endl;
- }
- has_error_ = true;
-}
-
-} // namespace testing
-} // namespace grpc
diff --git a/contrib/libs/grpc/test/cpp/util/proto_file_parser.h b/contrib/libs/grpc/test/cpp/util/proto_file_parser.h
deleted file mode 100644
index 9189b1ce0e8..00000000000
--- a/contrib/libs/grpc/test/cpp/util/proto_file_parser.h
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- *
- * Copyright 2016 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_TEST_CPP_UTIL_PROTO_FILE_PARSER_H
-#define GRPC_TEST_CPP_UTIL_PROTO_FILE_PARSER_H
-
-#include <memory>
-
-#include <grpcpp/channel.h>
-
-#include "test/cpp/util/config_grpc_cli.h"
-#include "test/cpp/util/proto_reflection_descriptor_database.h"
-
-#if defined(_WIN32) && !defined(__CYGWIN__)
-#define GRPC_CLI_PATH_SEPARATOR ";"
-#else
-#define GRPC_CLI_PATH_SEPARATOR ":"
-#endif
-
-namespace grpc {
-namespace testing {
-class ErrorPrinter;
-
-// Find method and associated request/response types.
-class ProtoFileParser {
- public:
- // The parser will search proto files using the server reflection service
- // provided on the given channel. The given protofiles in a source tree rooted
- // from proto_path will also be searched.
- ProtoFileParser(const std::shared_ptr<grpc::Channel>& channel,
- const TString& proto_path, const TString& protofiles);
-
- ~ProtoFileParser();
-
- // The input method name in the following four functions could be a partial
- // string such as Service.Method or even just Method. It will log an error if
- // there is ambiguity.
- // Full method name is in the form of Service.Method, it's good to be used in
- // descriptor database queries.
- TString GetFullMethodName(const TString& method);
-
- // Formatted method name is in the form of /Service/Method, it's good to be
- // used as the argument of Stub::Call()
- TString GetFormattedMethodName(const TString& method);
-
- /// Converts a text or json string to its binary proto representation for the
- /// given method's input or return type.
- /// \param method the name of the method (does not need to be fully qualified
- /// name)
- /// \param formatted_proto the text- or json-formatted proto string
- /// \param is_request if \c true the resolved type is that of the input
- /// parameter of the method, otherwise it is the output type
- /// \param is_json_format if \c true the \c formatted_proto is treated as a
- /// json-formatted proto, otherwise it is treated as a text-formatted
- /// proto
- /// \return the serialised binary proto representation of \c formatted_proto
- TString GetSerializedProtoFromMethod(const TString& method,
- const TString& formatted_proto,
- bool is_request,
- bool is_json_format);
-
- /// Converts a text or json string to its proto representation for the given
- /// message type.
- /// \param formatted_proto the text- or json-formatted proto string
- /// \return the serialised binary proto representation of \c formatted_proto
- TString GetSerializedProtoFromMessageType(
- const TString& message_type_name, const TString& formatted_proto,
- bool is_json_format);
-
- /// Converts a binary proto string to its text or json string representation
- /// for the given method's input or return type.
- /// \param method the name of the method (does not need to be a fully
- /// qualified name)
- /// \param the serialised binary proto representation of type
- /// \c message_type_name
- /// \return the text- or json-formatted proto string of \c serialized_proto
- TString GetFormattedStringFromMethod(const TString& method,
- const TString& serialized_proto,
- bool is_request,
- bool is_json_format);
-
- /// Converts a binary proto string to its text or json string representation
- /// for the given message type.
- /// \param the serialised binary proto representation of type
- /// \c message_type_name
- /// \return the text- or json-formatted proto string of \c serialized_proto
- TString GetFormattedStringFromMessageType(
- const TString& message_type_name, const TString& serialized_proto,
- bool is_json_format);
-
- bool IsStreaming(const TString& method, bool is_request);
-
- bool HasError() const { return has_error_; }
-
- void LogError(const TString& error_msg);
-
- private:
- TString GetMessageTypeFromMethod(const TString& method,
- bool is_request);
-
- bool has_error_;
- TString request_text_;
- protobuf::compiler::DiskSourceTree source_tree_;
- std::unique_ptr<ErrorPrinter> error_printer_;
- std::unique_ptr<protobuf::compiler::Importer> importer_;
- std::unique_ptr<grpc::ProtoReflectionDescriptorDatabase> reflection_db_;
- std::unique_ptr<protobuf::DescriptorPoolDatabase> file_db_;
- std::unique_ptr<protobuf::DescriptorDatabase> desc_db_;
- std::unique_ptr<protobuf::DescriptorPool> desc_pool_;
- std::unique_ptr<protobuf::DynamicMessageFactory> dynamic_factory_;
- std::unique_ptr<grpc::protobuf::Message> request_prototype_;
- std::unique_ptr<grpc::protobuf::Message> response_prototype_;
- std::unordered_map<TString, TString> known_methods_;
- std::vector<const protobuf::ServiceDescriptor*> service_desc_list_;
-};
-
-} // namespace testing
-} // namespace grpc
-
-#endif // GRPC_TEST_CPP_UTIL_PROTO_FILE_PARSER_H
diff --git a/contrib/libs/grpc/test/cpp/util/proto_reflection_descriptor_database.cc b/contrib/libs/grpc/test/cpp/util/proto_reflection_descriptor_database.cc
deleted file mode 100644
index 5def4c1e770..00000000000
--- a/contrib/libs/grpc/test/cpp/util/proto_reflection_descriptor_database.cc
+++ /dev/null
@@ -1,333 +0,0 @@
-/*
- *
- * Copyright 2016 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include "test/cpp/util/proto_reflection_descriptor_database.h"
-
-#include <vector>
-
-#include <grpc/support/log.h>
-
-using grpc::reflection::v1alpha::ErrorResponse;
-using grpc::reflection::v1alpha::ListServiceResponse;
-using grpc::reflection::v1alpha::ServerReflection;
-using grpc::reflection::v1alpha::ServerReflectionRequest;
-using grpc::reflection::v1alpha::ServerReflectionResponse;
-
-namespace grpc {
-
-ProtoReflectionDescriptorDatabase::ProtoReflectionDescriptorDatabase(
- std::unique_ptr<ServerReflection::Stub> stub)
- : stub_(std::move(stub)) {}
-
-ProtoReflectionDescriptorDatabase::ProtoReflectionDescriptorDatabase(
- const std::shared_ptr<grpc::Channel>& channel)
- : stub_(ServerReflection::NewStub(channel)) {}
-
-ProtoReflectionDescriptorDatabase::~ProtoReflectionDescriptorDatabase() {
- if (stream_) {
- stream_->WritesDone();
- Status status = stream_->Finish();
- if (!status.ok()) {
- if (status.error_code() == StatusCode::UNIMPLEMENTED) {
- fprintf(stderr,
- "Reflection request not implemented; "
- "is the ServerReflection service enabled?\n");
- } else {
- fprintf(stderr,
- "ServerReflectionInfo rpc failed. Error code: %d, message: %s, "
- "debug info: %s\n",
- static_cast<int>(status.error_code()),
- status.error_message().c_str(),
- ctx_.debug_error_string().c_str());
- }
- }
- }
-}
-
-bool ProtoReflectionDescriptorDatabase::FindFileByName(
- const google::protobuf::string& filename, protobuf::FileDescriptorProto* output) {
- if (cached_db_.FindFileByName(filename, output)) {
- return true;
- }
-
- if (known_files_.find(filename) != known_files_.end()) {
- return false;
- }
-
- ServerReflectionRequest request;
- request.set_file_by_filename(filename);
- ServerReflectionResponse response;
-
- if (!DoOneRequest(request, response)) {
- return false;
- }
-
- if (response.message_response_case() ==
- ServerReflectionResponse::MessageResponseCase::kFileDescriptorResponse) {
- AddFileFromResponse(response.file_descriptor_response());
- } else if (response.message_response_case() ==
- ServerReflectionResponse::MessageResponseCase::kErrorResponse) {
- const ErrorResponse& error = response.error_response();
- if (error.error_code() == StatusCode::NOT_FOUND) {
- gpr_log(GPR_INFO, "NOT_FOUND from server for FindFileByName(%s)",
- filename.c_str());
- } else {
- gpr_log(GPR_INFO,
- "Error on FindFileByName(%s)\n\tError code: %d\n"
- "\tError Message: %s",
- filename.c_str(), error.error_code(),
- error.error_message().c_str());
- }
- } else {
- gpr_log(
- GPR_INFO,
- "Error on FindFileByName(%s) response type\n"
- "\tExpecting: %d\n\tReceived: %d",
- filename.c_str(),
- ServerReflectionResponse::MessageResponseCase::kFileDescriptorResponse,
- response.message_response_case());
- }
-
- return cached_db_.FindFileByName(filename, output);
-}
-
-bool ProtoReflectionDescriptorDatabase::FindFileContainingSymbol(
- const google::protobuf::string& symbol_name, protobuf::FileDescriptorProto* output) {
- if (cached_db_.FindFileContainingSymbol(symbol_name, output)) {
- return true;
- }
-
- if (missing_symbols_.find(symbol_name) != missing_symbols_.end()) {
- return false;
- }
-
- ServerReflectionRequest request;
- request.set_file_containing_symbol(symbol_name);
- ServerReflectionResponse response;
-
- if (!DoOneRequest(request, response)) {
- return false;
- }
-
- if (response.message_response_case() ==
- ServerReflectionResponse::MessageResponseCase::kFileDescriptorResponse) {
- AddFileFromResponse(response.file_descriptor_response());
- } else if (response.message_response_case() ==
- ServerReflectionResponse::MessageResponseCase::kErrorResponse) {
- const ErrorResponse& error = response.error_response();
- if (error.error_code() == StatusCode::NOT_FOUND) {
- missing_symbols_.insert(symbol_name);
- gpr_log(GPR_INFO,
- "NOT_FOUND from server for FindFileContainingSymbol(%s)",
- symbol_name.c_str());
- } else {
- gpr_log(GPR_INFO,
- "Error on FindFileContainingSymbol(%s)\n"
- "\tError code: %d\n\tError Message: %s",
- symbol_name.c_str(), error.error_code(),
- error.error_message().c_str());
- }
- } else {
- gpr_log(
- GPR_INFO,
- "Error on FindFileContainingSymbol(%s) response type\n"
- "\tExpecting: %d\n\tReceived: %d",
- symbol_name.c_str(),
- ServerReflectionResponse::MessageResponseCase::kFileDescriptorResponse,
- response.message_response_case());
- }
- return cached_db_.FindFileContainingSymbol(symbol_name, output);
-}
-
-bool ProtoReflectionDescriptorDatabase::FindFileContainingExtension(
- const google::protobuf::string& containing_type, int field_number,
- protobuf::FileDescriptorProto* output) {
- if (cached_db_.FindFileContainingExtension(containing_type, field_number,
- output)) {
- return true;
- }
-
- if (missing_extensions_.find(containing_type) != missing_extensions_.end() &&
- missing_extensions_[containing_type].find(field_number) !=
- missing_extensions_[containing_type].end()) {
- gpr_log(GPR_INFO, "nested map.");
- return false;
- }
-
- ServerReflectionRequest request;
- request.mutable_file_containing_extension()->set_containing_type(
- containing_type);
- request.mutable_file_containing_extension()->set_extension_number(
- field_number);
- ServerReflectionResponse response;
-
- if (!DoOneRequest(request, response)) {
- return false;
- }
-
- if (response.message_response_case() ==
- ServerReflectionResponse::MessageResponseCase::kFileDescriptorResponse) {
- AddFileFromResponse(response.file_descriptor_response());
- } else if (response.message_response_case() ==
- ServerReflectionResponse::MessageResponseCase::kErrorResponse) {
- const ErrorResponse& error = response.error_response();
- if (error.error_code() == StatusCode::NOT_FOUND) {
- if (missing_extensions_.find(containing_type) ==
- missing_extensions_.end()) {
- missing_extensions_[containing_type] = {};
- }
- missing_extensions_[containing_type].insert(field_number);
- gpr_log(GPR_INFO,
- "NOT_FOUND from server for FindFileContainingExtension(%s, %d)",
- containing_type.c_str(), field_number);
- } else {
- gpr_log(GPR_INFO,
- "Error on FindFileContainingExtension(%s, %d)\n"
- "\tError code: %d\n\tError Message: %s",
- containing_type.c_str(), field_number, error.error_code(),
- error.error_message().c_str());
- }
- } else {
- gpr_log(
- GPR_INFO,
- "Error on FindFileContainingExtension(%s, %d) response type\n"
- "\tExpecting: %d\n\tReceived: %d",
- containing_type.c_str(), field_number,
- ServerReflectionResponse::MessageResponseCase::kFileDescriptorResponse,
- response.message_response_case());
- }
-
- return cached_db_.FindFileContainingExtension(containing_type, field_number,
- output);
-}
-
-bool ProtoReflectionDescriptorDatabase::FindAllExtensionNumbers(
- const google::protobuf::string& extendee_type, std::vector<int>* output) {
- if (cached_extension_numbers_.find(extendee_type) !=
- cached_extension_numbers_.end()) {
- *output = cached_extension_numbers_[extendee_type];
- return true;
- }
-
- ServerReflectionRequest request;
- request.set_all_extension_numbers_of_type(extendee_type);
- ServerReflectionResponse response;
-
- if (!DoOneRequest(request, response)) {
- return false;
- }
-
- if (response.message_response_case() ==
- ServerReflectionResponse::MessageResponseCase::
- kAllExtensionNumbersResponse) {
- auto number = response.all_extension_numbers_response().extension_number();
- *output = std::vector<int>(number.begin(), number.end());
- cached_extension_numbers_[extendee_type] = *output;
- return true;
- } else if (response.message_response_case() ==
- ServerReflectionResponse::MessageResponseCase::kErrorResponse) {
- const ErrorResponse& error = response.error_response();
- if (error.error_code() == StatusCode::NOT_FOUND) {
- gpr_log(GPR_INFO, "NOT_FOUND from server for FindAllExtensionNumbers(%s)",
- extendee_type.c_str());
- } else {
- gpr_log(GPR_INFO,
- "Error on FindAllExtensionNumbersExtension(%s)\n"
- "\tError code: %d\n\tError Message: %s",
- extendee_type.c_str(), error.error_code(),
- error.error_message().c_str());
- }
- }
- return false;
-}
-
-bool ProtoReflectionDescriptorDatabase::GetServices(
- std::vector<TString>* output) {
- ServerReflectionRequest request;
- request.set_list_services("");
- ServerReflectionResponse response;
-
- if (!DoOneRequest(request, response)) {
- return false;
- }
-
- if (response.message_response_case() ==
- ServerReflectionResponse::MessageResponseCase::kListServicesResponse) {
- const ListServiceResponse& ls_response = response.list_services_response();
- for (int i = 0; i < ls_response.service_size(); ++i) {
- (*output).push_back(ls_response.service(i).name());
- }
- return true;
- } else if (response.message_response_case() ==
- ServerReflectionResponse::MessageResponseCase::kErrorResponse) {
- const ErrorResponse& error = response.error_response();
- gpr_log(GPR_INFO,
- "Error on GetServices()\n\tError code: %d\n"
- "\tError Message: %s",
- error.error_code(), error.error_message().c_str());
- } else {
- gpr_log(
- GPR_INFO,
- "Error on GetServices() response type\n\tExpecting: %d\n\tReceived: %d",
- ServerReflectionResponse::MessageResponseCase::kListServicesResponse,
- response.message_response_case());
- }
- return false;
-}
-
-protobuf::FileDescriptorProto
-ProtoReflectionDescriptorDatabase::ParseFileDescriptorProtoResponse(
- const TString& byte_fd_proto) {
- protobuf::FileDescriptorProto file_desc_proto;
- file_desc_proto.ParseFromString(google::protobuf::string(byte_fd_proto));
- return file_desc_proto;
-}
-
-void ProtoReflectionDescriptorDatabase::AddFileFromResponse(
- const grpc::reflection::v1alpha::FileDescriptorResponse& response) {
- for (int i = 0; i < response.file_descriptor_proto_size(); ++i) {
- const protobuf::FileDescriptorProto file_proto =
- ParseFileDescriptorProtoResponse(response.file_descriptor_proto(i));
- if (known_files_.find(file_proto.name()) == known_files_.end()) {
- known_files_.insert(file_proto.name());
- cached_db_.Add(file_proto);
- }
- }
-}
-
-std::shared_ptr<ProtoReflectionDescriptorDatabase::ClientStream>
-ProtoReflectionDescriptorDatabase::GetStream() {
- if (!stream_) {
- stream_ = stub_->ServerReflectionInfo(&ctx_);
- }
- return stream_;
-}
-
-bool ProtoReflectionDescriptorDatabase::DoOneRequest(
- const ServerReflectionRequest& request,
- ServerReflectionResponse& response) {
- bool success = false;
- stream_mutex_.lock();
- if (GetStream()->Write(request) && GetStream()->Read(&response)) {
- success = true;
- }
- stream_mutex_.unlock();
- return success;
-}
-
-} // namespace grpc
diff --git a/contrib/libs/grpc/test/cpp/util/proto_reflection_descriptor_database.h b/contrib/libs/grpc/test/cpp/util/proto_reflection_descriptor_database.h
deleted file mode 100644
index 6b6f51de8b1..00000000000
--- a/contrib/libs/grpc/test/cpp/util/proto_reflection_descriptor_database.h
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- *
- * Copyright 2016 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-#ifndef GRPC_TEST_CPP_PROTO_SERVER_REFLECTION_DATABSE_H
-#define GRPC_TEST_CPP_PROTO_SERVER_REFLECTION_DATABSE_H
-
-#include <mutex>
-#include <unordered_map>
-#include <unordered_set>
-#include <vector>
-
-#include <grpcpp/grpcpp.h>
-#include <grpcpp/impl/codegen/config_protobuf.h>
-
-#include "src/proto/grpc/reflection/v1alpha/reflection.grpc.pb.h"
-
-namespace grpc {
-
-// ProtoReflectionDescriptorDatabase takes a stub of ServerReflection and
-// provides the methods defined by DescriptorDatabase interfaces. It can be used
-// to feed a DescriptorPool instance.
-class ProtoReflectionDescriptorDatabase : public protobuf::DescriptorDatabase {
- public:
- explicit ProtoReflectionDescriptorDatabase(
- std::unique_ptr<reflection::v1alpha::ServerReflection::Stub> stub);
-
- explicit ProtoReflectionDescriptorDatabase(
- const std::shared_ptr<grpc::Channel>& channel);
-
- ~ProtoReflectionDescriptorDatabase() override;
-
- // The following four methods implement DescriptorDatabase interfaces.
- //
- // Find a file by file name. Fills in *output and returns true if found.
- // Otherwise, returns false, leaving the contents of *output undefined.
- bool FindFileByName(const google::protobuf::string& filename,
- protobuf::FileDescriptorProto* output) override;
-
- // Find the file that declares the given fully-qualified symbol name.
- // If found, fills in *output and returns true, otherwise returns false
- // and leaves *output undefined.
- bool FindFileContainingSymbol(const google::protobuf::string& symbol_name,
- protobuf::FileDescriptorProto* output) override;
-
- // Find the file which defines an extension extending the given message type
- // with the given field number. If found, fills in *output and returns true,
- // otherwise returns false and leaves *output undefined. containing_type
- // must be a fully-qualified type name.
- bool FindFileContainingExtension(
- const google::protobuf::string& containing_type, int field_number,
- protobuf::FileDescriptorProto* output) override;
-
- // Finds the tag numbers used by all known extensions of
- // extendee_type, and appends them to output in an undefined
- // order. This method is best-effort: it's not guaranteed that the
- // database will find all extensions, and it's not guaranteed that
- // FindFileContainingExtension will return true on all of the found
- // numbers. Returns true if the search was successful, otherwise
- // returns false and leaves output unchanged.
- bool FindAllExtensionNumbers(const google::protobuf::string& extendee_type,
- std::vector<int>* output) override;
-
- // Provide a list of full names of registered services
- bool GetServices(std::vector<TString>* output);
-
- private:
- typedef ClientReaderWriter<
- grpc::reflection::v1alpha::ServerReflectionRequest,
- grpc::reflection::v1alpha::ServerReflectionResponse>
- ClientStream;
-
- protobuf::FileDescriptorProto ParseFileDescriptorProtoResponse(
- const TString& byte_fd_proto);
-
- void AddFileFromResponse(
- const grpc::reflection::v1alpha::FileDescriptorResponse& response);
-
- std::shared_ptr<ClientStream> GetStream();
-
- bool DoOneRequest(
- const grpc::reflection::v1alpha::ServerReflectionRequest& request,
- grpc::reflection::v1alpha::ServerReflectionResponse& response);
-
- std::shared_ptr<ClientStream> stream_;
- grpc::ClientContext ctx_;
- std::unique_ptr<grpc::reflection::v1alpha::ServerReflection::Stub> stub_;
- std::unordered_set<string> known_files_;
- std::unordered_set<string> missing_symbols_;
- std::unordered_map<string, std::unordered_set<int>> missing_extensions_;
- std::unordered_map<string, std::vector<int>> cached_extension_numbers_;
- std::mutex stream_mutex_;
-
- protobuf::SimpleDescriptorDatabase cached_db_;
-};
-
-} // namespace grpc
-
-#endif // GRPC_TEST_CPP_METRICS_SERVER_H
diff --git a/contrib/libs/grpc/test/cpp/util/service_describer.cc b/contrib/libs/grpc/test/cpp/util/service_describer.cc
deleted file mode 100644
index 2af1104b979..00000000000
--- a/contrib/libs/grpc/test/cpp/util/service_describer.cc
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- *
- * Copyright 2016 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include "test/cpp/util/service_describer.h"
-
-#include <iostream>
-#include <sstream>
-#include <util/generic/string.h>
-#include <vector>
-
-namespace grpc {
-namespace testing {
-
-TString DescribeServiceList(std::vector<TString> service_list,
- grpc::protobuf::DescriptorPool& desc_pool) {
- std::stringstream result;
- for (auto it = service_list.begin(); it != service_list.end(); it++) {
- auto const& service = *it;
- const grpc::protobuf::ServiceDescriptor* service_desc =
- desc_pool.FindServiceByName(google::protobuf::string(service));
- if (service_desc != nullptr) {
- result << DescribeService(service_desc);
- }
- }
- return result.str();
-}
-
-TString DescribeService(const grpc::protobuf::ServiceDescriptor* service) {
- TString result;
- if (service->options().deprecated()) {
- result.append("DEPRECATED\n");
- }
- result.append("filename: " + service->file()->name() + "\n");
-
- TString package = service->full_name();
- size_t pos = package.rfind("." + service->name());
- if (pos != TString::npos) {
- package.erase(pos);
- result.append("package: " + package + ";\n");
- }
- result.append("service " + service->name() + " {\n");
- for (int i = 0; i < service->method_count(); ++i) {
- result.append(DescribeMethod(service->method(i)));
- }
- result.append("}\n\n");
- return result;
-}
-
-TString DescribeMethod(const grpc::protobuf::MethodDescriptor* method) {
- std::stringstream result;
- result << " rpc " << method->name()
- << (method->client_streaming() ? "(stream " : "(")
- << method->input_type()->full_name() << ") returns "
- << (method->server_streaming() ? "(stream " : "(")
- << method->output_type()->full_name() << ") {}\n";
- if (method->options().deprecated()) {
- result << " DEPRECATED";
- }
- return result.str();
-}
-
-TString SummarizeService(const grpc::protobuf::ServiceDescriptor* service) {
- TString result;
- for (int i = 0; i < service->method_count(); ++i) {
- result.append(SummarizeMethod(service->method(i)));
- }
- return result;
-}
-
-TString SummarizeMethod(const grpc::protobuf::MethodDescriptor* method) {
- TString result = method->name();
- result.append("\n");
- return result;
-}
-
-} // namespace testing
-} // namespace grpc
diff --git a/contrib/libs/grpc/test/cpp/util/service_describer.h b/contrib/libs/grpc/test/cpp/util/service_describer.h
deleted file mode 100644
index a2b2a173203..00000000000
--- a/contrib/libs/grpc/test/cpp/util/service_describer.h
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- *
- * Copyright 2016 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_TEST_CPP_UTIL_SERVICE_DESCRIBER_H
-#define GRPC_TEST_CPP_UTIL_SERVICE_DESCRIBER_H
-
-#include <grpcpp/support/config.h>
-
-#include "test/cpp/util/config_grpc_cli.h"
-
-namespace grpc {
-namespace testing {
-
-TString DescribeServiceList(std::vector<TString> service_list,
- grpc::protobuf::DescriptorPool& desc_pool);
-
-TString DescribeService(const grpc::protobuf::ServiceDescriptor* service);
-
-TString DescribeMethod(const grpc::protobuf::MethodDescriptor* method);
-
-TString SummarizeService(const grpc::protobuf::ServiceDescriptor* service);
-
-TString SummarizeMethod(const grpc::protobuf::MethodDescriptor* method);
-
-} // namespace testing
-} // namespace grpc
-
-#endif // GRPC_TEST_CPP_UTIL_SERVICE_DESCRIBER_H
diff --git a/contrib/libs/grpc/test/cpp/util/string_ref_helper.cc b/contrib/libs/grpc/test/cpp/util/string_ref_helper.cc
deleted file mode 100644
index e573f5d33ad..00000000000
--- a/contrib/libs/grpc/test/cpp/util/string_ref_helper.cc
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- *
- * Copyright 2015 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include "test/cpp/util/string_ref_helper.h"
-
-namespace grpc {
-namespace testing {
-
-TString ToString(const grpc::string_ref& r) {
- return TString(r.data(), r.size());
-}
-
-} // namespace testing
-} // namespace grpc
diff --git a/contrib/libs/grpc/test/cpp/util/string_ref_helper.h b/contrib/libs/grpc/test/cpp/util/string_ref_helper.h
deleted file mode 100644
index e9e941f3192..00000000000
--- a/contrib/libs/grpc/test/cpp/util/string_ref_helper.h
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- *
- * Copyright 2015 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_TEST_CPP_UTIL_STRING_REF_HELPER_H
-#define GRPC_TEST_CPP_UTIL_STRING_REF_HELPER_H
-
-#include <grpcpp/support/string_ref.h>
-
-namespace grpc {
-namespace testing {
-
-TString ToString(const grpc::string_ref& r);
-
-} // namespace testing
-} // namespace grpc
-
-#endif // GRPC_TEST_CPP_UTIL_STRING_REF_HELPER_H
diff --git a/contrib/libs/grpc/test/cpp/util/test_config.h b/contrib/libs/grpc/test/cpp/util/test_config.h
deleted file mode 100644
index fb2b257ddea..00000000000
--- a/contrib/libs/grpc/test/cpp/util/test_config.h
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- *
- * Copyright 2015 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef GRPC_TEST_CPP_UTIL_TEST_CONFIG_H
-#define GRPC_TEST_CPP_UTIL_TEST_CONFIG_H
-
-#ifndef GRPC_GTEST_FLAG_SET_DEATH_TEST_STYLE
-#define GRPC_GTEST_FLAG_SET_DEATH_TEST_STYLE(style) \
- ::testing::FLAGS_gtest_death_test_style = style
-#endif // GRPC_GTEST_FLAG_SET_DEATH_TEST_STYLE
-
-namespace grpc {
-namespace testing {
-
-void InitTest(int* argc, char*** argv, bool remove_flags);
-
-} // namespace testing
-} // namespace grpc
-
-#endif // GRPC_TEST_CPP_UTIL_TEST_CONFIG_H
diff --git a/contrib/libs/grpc/test/cpp/util/test_config_cc.cc b/contrib/libs/grpc/test/cpp/util/test_config_cc.cc
deleted file mode 100644
index 65b925751ec..00000000000
--- a/contrib/libs/grpc/test/cpp/util/test_config_cc.cc
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- *
- * Copyright 2015 gRPC authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#include <vector>
-
-#include "y_absl/flags/parse.h"
-
-#include "test/cpp/util/test_config.h"
-
-namespace grpc {
-namespace testing {
-
-void InitTest(int* argc, char*** argv, bool remove_flags) {
- std::vector<char*> reduced_argv = y_absl::ParseCommandLine(*argc, *argv);
- if (remove_flags) {
- *argc = reduced_argv.size();
- for (int i = 0; i < *argc; i++) {
- (*argv)[i] = reduced_argv.at(i);
- }
- }
-}
-
-} // namespace testing
-} // namespace grpc
diff --git a/contrib/libs/grpc/test/cpp/util/ya.make b/contrib/libs/grpc/test/cpp/util/ya.make
deleted file mode 100644
index f6879835dae..00000000000
--- a/contrib/libs/grpc/test/cpp/util/ya.make
+++ /dev/null
@@ -1,38 +0,0 @@
-LIBRARY()
-
-LICENSE(Apache-2.0)
-
-LICENSE_TEXTS(.yandex_meta/licenses.list.txt)
-
-PEERDIR(
- contrib/libs/gflags
- contrib/libs/protoc
- contrib/libs/grpc/src/proto/grpc/reflection/v1alpha
- contrib/restricted/googletest/googlemock
- contrib/restricted/googletest/googletest
- contrib/restricted/abseil-cpp-tstring/y_absl/flags
-)
-
-ADDINCL(
- ${ARCADIA_BUILD_ROOT}/contrib/libs/grpc
- contrib/libs/grpc
-)
-
-NO_COMPILER_WARNINGS()
-
-SRCS(
- byte_buffer_proto_helper.cc
- # grpc_cli_libs:
- cli_call.cc
- cli_credentials.cc
- grpc_tool.cc
- proto_file_parser.cc
- service_describer.cc
- string_ref_helper.cc
- # grpc++_proto_reflection_desc_db:
- proto_reflection_descriptor_database.cc
- # grpc++_test_config:
- test_config_cc.cc
-)
-
-END()