client_callback_end2end_test.cc 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577
  1. /*
  2. *
  3. * Copyright 2018 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. #include <algorithm>
  19. #include <condition_variable>
  20. #include <functional>
  21. #include <mutex>
  22. #include <sstream>
  23. #include <thread>
  24. #include <gtest/gtest.h>
  25. #include "absl/memory/memory.h"
  26. #include <grpcpp/channel.h>
  27. #include <grpcpp/client_context.h>
  28. #include <grpcpp/create_channel.h>
  29. #include <grpcpp/generic/generic_stub.h>
  30. #include <grpcpp/impl/codegen/proto_utils.h>
  31. #include <grpcpp/server.h>
  32. #include <grpcpp/server_builder.h>
  33. #include <grpcpp/server_context.h>
  34. #include <grpcpp/support/client_callback.h>
  35. #include "src/core/lib/gpr/env.h"
  36. #include "src/core/lib/iomgr/iomgr.h"
  37. #include "src/proto/grpc/testing/echo.grpc.pb.h"
  38. #include "test/core/util/port.h"
  39. #include "test/core/util/test_config.h"
  40. #include "test/cpp/end2end/interceptors_util.h"
  41. #include "test/cpp/end2end/test_service_impl.h"
  42. #include "test/cpp/util/byte_buffer_proto_helper.h"
  43. #include "test/cpp/util/string_ref_helper.h"
  44. #include "test/cpp/util/test_credentials_provider.h"
  45. namespace grpc {
  46. namespace testing {
  47. namespace {
  48. enum class Protocol { INPROC, TCP };
  49. class TestScenario {
  50. public:
  51. TestScenario(bool serve_callback, Protocol protocol, bool intercept,
  52. const std::string& creds_type)
  53. : callback_server(serve_callback),
  54. protocol(protocol),
  55. use_interceptors(intercept),
  56. credentials_type(creds_type) {}
  57. void Log() const;
  58. bool callback_server;
  59. Protocol protocol;
  60. bool use_interceptors;
  61. const std::string credentials_type;
  62. };
  63. std::ostream& operator<<(std::ostream& out, const TestScenario& scenario) {
  64. return out << "TestScenario{callback_server="
  65. << (scenario.callback_server ? "true" : "false") << ",protocol="
  66. << (scenario.protocol == Protocol::INPROC ? "INPROC" : "TCP")
  67. << ",intercept=" << (scenario.use_interceptors ? "true" : "false")
  68. << ",creds=" << scenario.credentials_type << "}";
  69. }
  70. void TestScenario::Log() const {
  71. std::ostringstream out;
  72. out << *this;
  73. gpr_log(GPR_DEBUG, "%s", out.str().c_str());
  74. }
  75. class ClientCallbackEnd2endTest
  76. : public ::testing::TestWithParam<TestScenario> {
  77. protected:
  78. ClientCallbackEnd2endTest() { GetParam().Log(); }
  79. void SetUp() override {
  80. ServerBuilder builder;
  81. auto server_creds = GetCredentialsProvider()->GetServerCredentials(
  82. GetParam().credentials_type);
  83. // TODO(vjpai): Support testing of AuthMetadataProcessor
  84. if (GetParam().protocol == Protocol::TCP) {
  85. picked_port_ = grpc_pick_unused_port_or_die();
  86. server_address_ << "localhost:" << picked_port_;
  87. builder.AddListeningPort(server_address_.str(), server_creds);
  88. }
  89. if (!GetParam().callback_server) {
  90. builder.RegisterService(&service_);
  91. } else {
  92. builder.RegisterService(&callback_service_);
  93. }
  94. if (GetParam().use_interceptors) {
  95. std::vector<
  96. std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
  97. creators;
  98. // Add 20 phony server interceptors
  99. creators.reserve(20);
  100. for (auto i = 0; i < 20; i++) {
  101. creators.push_back(absl::make_unique<PhonyInterceptorFactory>());
  102. }
  103. builder.experimental().SetInterceptorCreators(std::move(creators));
  104. }
  105. server_ = builder.BuildAndStart();
  106. is_server_started_ = true;
  107. }
  108. void ResetStub(
  109. std::unique_ptr<experimental::ClientInterceptorFactoryInterface>
  110. interceptor = nullptr) {
  111. ChannelArguments args;
  112. auto channel_creds = GetCredentialsProvider()->GetChannelCredentials(
  113. GetParam().credentials_type, &args);
  114. auto interceptors = CreatePhonyClientInterceptors();
  115. if (interceptor != nullptr) interceptors.push_back(std::move(interceptor));
  116. switch (GetParam().protocol) {
  117. case Protocol::TCP:
  118. if (!GetParam().use_interceptors) {
  119. channel_ = grpc::CreateCustomChannel(server_address_.str(),
  120. channel_creds, args);
  121. } else {
  122. channel_ = CreateCustomChannelWithInterceptors(
  123. server_address_.str(), channel_creds, args,
  124. std::move(interceptors));
  125. }
  126. break;
  127. case Protocol::INPROC:
  128. if (!GetParam().use_interceptors) {
  129. channel_ = server_->InProcessChannel(args);
  130. } else {
  131. channel_ = server_->experimental().InProcessChannelWithInterceptors(
  132. args, std::move(interceptors));
  133. }
  134. break;
  135. default:
  136. assert(false);
  137. }
  138. stub_ = grpc::testing::EchoTestService::NewStub(channel_);
  139. generic_stub_ = absl::make_unique<GenericStub>(channel_);
  140. PhonyInterceptor::Reset();
  141. }
  142. void TearDown() override {
  143. if (is_server_started_) {
  144. // Although we would normally do an explicit shutdown, the server
  145. // should also work correctly with just a destructor call. The regular
  146. // end2end test uses explicit shutdown, so let this one just do reset.
  147. server_.reset();
  148. }
  149. if (picked_port_ > 0) {
  150. grpc_recycle_unused_port(picked_port_);
  151. }
  152. }
  153. void SendRpcs(int num_rpcs, bool with_binary_metadata) {
  154. std::string test_string("");
  155. for (int i = 0; i < num_rpcs; i++) {
  156. EchoRequest request;
  157. EchoResponse response;
  158. ClientContext cli_ctx;
  159. test_string += "Hello world. ";
  160. request.set_message(test_string);
  161. std::string val;
  162. if (with_binary_metadata) {
  163. request.mutable_param()->set_echo_metadata(true);
  164. char bytes[8] = {'\0', '\1', '\2', '\3',
  165. '\4', '\5', '\6', static_cast<char>(i)};
  166. val = std::string(bytes, 8);
  167. cli_ctx.AddMetadata("custom-bin", val);
  168. }
  169. cli_ctx.set_compression_algorithm(GRPC_COMPRESS_GZIP);
  170. std::mutex mu;
  171. std::condition_variable cv;
  172. bool done = false;
  173. stub_->async()->Echo(
  174. &cli_ctx, &request, &response,
  175. [&cli_ctx, &request, &response, &done, &mu, &cv, val,
  176. with_binary_metadata](Status s) {
  177. GPR_ASSERT(s.ok());
  178. EXPECT_EQ(request.message(), response.message());
  179. if (with_binary_metadata) {
  180. EXPECT_EQ(
  181. 1u, cli_ctx.GetServerTrailingMetadata().count("custom-bin"));
  182. EXPECT_EQ(val, ToString(cli_ctx.GetServerTrailingMetadata()
  183. .find("custom-bin")
  184. ->second));
  185. }
  186. std::lock_guard<std::mutex> l(mu);
  187. done = true;
  188. cv.notify_one();
  189. });
  190. std::unique_lock<std::mutex> l(mu);
  191. while (!done) {
  192. cv.wait(l);
  193. }
  194. }
  195. }
  196. void SendRpcsGeneric(int num_rpcs, bool maybe_except,
  197. const char* suffix_for_stats) {
  198. const std::string kMethodName("/grpc.testing.EchoTestService/Echo");
  199. std::string test_string("");
  200. for (int i = 0; i < num_rpcs; i++) {
  201. EchoRequest request;
  202. std::unique_ptr<ByteBuffer> send_buf;
  203. ByteBuffer recv_buf;
  204. ClientContext cli_ctx;
  205. test_string += "Hello world. ";
  206. request.set_message(test_string);
  207. send_buf = SerializeToByteBuffer(&request);
  208. std::mutex mu;
  209. std::condition_variable cv;
  210. bool done = false;
  211. StubOptions options(suffix_for_stats);
  212. generic_stub_->UnaryCall(
  213. &cli_ctx, kMethodName, options, send_buf.get(), &recv_buf,
  214. [&request, &recv_buf, &done, &mu, &cv, maybe_except](Status s) {
  215. GPR_ASSERT(s.ok());
  216. EchoResponse response;
  217. EXPECT_TRUE(ParseFromByteBuffer(&recv_buf, &response));
  218. EXPECT_EQ(request.message(), response.message());
  219. std::lock_guard<std::mutex> l(mu);
  220. done = true;
  221. cv.notify_one();
  222. #if GRPC_ALLOW_EXCEPTIONS
  223. if (maybe_except) {
  224. throw -1;
  225. }
  226. #else
  227. GPR_ASSERT(!maybe_except);
  228. #endif
  229. });
  230. std::unique_lock<std::mutex> l(mu);
  231. while (!done) {
  232. cv.wait(l);
  233. }
  234. }
  235. }
  236. void SendGenericEchoAsBidi(int num_rpcs, int reuses, bool do_writes_done,
  237. const char* suffix_for_stats) {
  238. const std::string kMethodName("/grpc.testing.EchoTestService/Echo");
  239. std::string test_string("");
  240. for (int i = 0; i < num_rpcs; i++) {
  241. test_string += "Hello world. ";
  242. class Client : public grpc::ClientBidiReactor<ByteBuffer, ByteBuffer> {
  243. public:
  244. Client(ClientCallbackEnd2endTest* test, const std::string& method_name,
  245. const char* suffix_for_stats, const std::string& test_str,
  246. int reuses, bool do_writes_done)
  247. : reuses_remaining_(reuses), do_writes_done_(do_writes_done) {
  248. activate_ = [this, test, method_name, suffix_for_stats, test_str] {
  249. if (reuses_remaining_ > 0) {
  250. cli_ctx_ = absl::make_unique<ClientContext>();
  251. reuses_remaining_--;
  252. StubOptions options(suffix_for_stats);
  253. test->generic_stub_->PrepareBidiStreamingCall(
  254. cli_ctx_.get(), method_name, options, this);
  255. request_.set_message(test_str);
  256. send_buf_ = SerializeToByteBuffer(&request_);
  257. StartWrite(send_buf_.get());
  258. StartRead(&recv_buf_);
  259. StartCall();
  260. } else {
  261. std::unique_lock<std::mutex> l(mu_);
  262. done_ = true;
  263. cv_.notify_one();
  264. }
  265. };
  266. activate_();
  267. }
  268. void OnWriteDone(bool /*ok*/) override {
  269. if (do_writes_done_) {
  270. StartWritesDone();
  271. }
  272. }
  273. void OnReadDone(bool /*ok*/) override {
  274. EchoResponse response;
  275. EXPECT_TRUE(ParseFromByteBuffer(&recv_buf_, &response));
  276. EXPECT_EQ(request_.message(), response.message());
  277. };
  278. void OnDone(const Status& s) override {
  279. EXPECT_TRUE(s.ok());
  280. activate_();
  281. }
  282. void Await() {
  283. std::unique_lock<std::mutex> l(mu_);
  284. while (!done_) {
  285. cv_.wait(l);
  286. }
  287. }
  288. EchoRequest request_;
  289. std::unique_ptr<ByteBuffer> send_buf_;
  290. ByteBuffer recv_buf_;
  291. std::unique_ptr<ClientContext> cli_ctx_;
  292. int reuses_remaining_;
  293. std::function<void()> activate_;
  294. std::mutex mu_;
  295. std::condition_variable cv_;
  296. bool done_ = false;
  297. const bool do_writes_done_;
  298. };
  299. Client rpc(this, kMethodName, suffix_for_stats, test_string, reuses,
  300. do_writes_done);
  301. rpc.Await();
  302. }
  303. }
  304. bool is_server_started_{false};
  305. int picked_port_{0};
  306. std::shared_ptr<Channel> channel_;
  307. std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
  308. std::unique_ptr<grpc::GenericStub> generic_stub_;
  309. TestServiceImpl service_;
  310. CallbackTestServiceImpl callback_service_;
  311. std::unique_ptr<Server> server_;
  312. std::ostringstream server_address_;
  313. };
  314. TEST_P(ClientCallbackEnd2endTest, SimpleRpc) {
  315. ResetStub();
  316. SendRpcs(1, false);
  317. }
  318. TEST_P(ClientCallbackEnd2endTest, SimpleRpcExpectedError) {
  319. ResetStub();
  320. EchoRequest request;
  321. EchoResponse response;
  322. ClientContext cli_ctx;
  323. ErrorStatus error_status;
  324. request.set_message("Hello failure");
  325. error_status.set_code(1); // CANCELLED
  326. error_status.set_error_message("cancel error message");
  327. *request.mutable_param()->mutable_expected_error() = error_status;
  328. std::mutex mu;
  329. std::condition_variable cv;
  330. bool done = false;
  331. stub_->async()->Echo(&cli_ctx, &request, &response,
  332. [&response, &done, &mu, &cv, &error_status](Status s) {
  333. EXPECT_EQ("", response.message());
  334. EXPECT_EQ(error_status.code(), s.error_code());
  335. EXPECT_EQ(error_status.error_message(),
  336. s.error_message());
  337. std::lock_guard<std::mutex> l(mu);
  338. done = true;
  339. cv.notify_one();
  340. });
  341. std::unique_lock<std::mutex> l(mu);
  342. while (!done) {
  343. cv.wait(l);
  344. }
  345. }
  346. TEST_P(ClientCallbackEnd2endTest, SimpleRpcUnderLockNested) {
  347. ResetStub();
  348. // The request/response state associated with an RPC and the synchronization
  349. // variables needed to notify its completion.
  350. struct RpcState {
  351. std::mutex mu;
  352. std::condition_variable cv;
  353. bool done = false;
  354. EchoRequest request;
  355. EchoResponse response;
  356. ClientContext cli_ctx;
  357. RpcState() = default;
  358. ~RpcState() {
  359. // Grab the lock to prevent destruction while another is still holding
  360. // lock
  361. std::lock_guard<std::mutex> lock(mu);
  362. }
  363. };
  364. std::vector<RpcState> rpc_state(3);
  365. for (size_t i = 0; i < rpc_state.size(); i++) {
  366. std::string message = "Hello locked world";
  367. message += std::to_string(i);
  368. rpc_state[i].request.set_message(message);
  369. }
  370. // Grab a lock and then start an RPC whose callback grabs the same lock and
  371. // then calls this function to start the next RPC under lock (up to a limit of
  372. // the size of the rpc_state vector).
  373. std::function<void(int)> nested_call = [this, &nested_call,
  374. &rpc_state](int index) {
  375. std::lock_guard<std::mutex> l(rpc_state[index].mu);
  376. stub_->async()->Echo(&rpc_state[index].cli_ctx, &rpc_state[index].request,
  377. &rpc_state[index].response,
  378. [index, &nested_call, &rpc_state](Status s) {
  379. std::lock_guard<std::mutex> l1(rpc_state[index].mu);
  380. EXPECT_TRUE(s.ok());
  381. rpc_state[index].done = true;
  382. rpc_state[index].cv.notify_all();
  383. // Call the next level of nesting if possible
  384. if (index + 1 < int(rpc_state.size())) {
  385. nested_call(index + 1);
  386. }
  387. });
  388. };
  389. nested_call(0);
  390. // Wait for completion notifications from all RPCs. Order doesn't matter.
  391. for (RpcState& state : rpc_state) {
  392. std::unique_lock<std::mutex> l(state.mu);
  393. while (!state.done) {
  394. state.cv.wait(l);
  395. }
  396. EXPECT_EQ(state.request.message(), state.response.message());
  397. }
  398. }
  399. TEST_P(ClientCallbackEnd2endTest, SimpleRpcUnderLock) {
  400. ResetStub();
  401. std::mutex mu;
  402. std::condition_variable cv;
  403. bool done = false;
  404. EchoRequest request;
  405. request.set_message("Hello locked world.");
  406. EchoResponse response;
  407. ClientContext cli_ctx;
  408. {
  409. std::lock_guard<std::mutex> l(mu);
  410. stub_->async()->Echo(&cli_ctx, &request, &response,
  411. [&mu, &cv, &done, &request, &response](Status s) {
  412. std::lock_guard<std::mutex> l(mu);
  413. EXPECT_TRUE(s.ok());
  414. EXPECT_EQ(request.message(), response.message());
  415. done = true;
  416. cv.notify_one();
  417. });
  418. }
  419. std::unique_lock<std::mutex> l(mu);
  420. while (!done) {
  421. cv.wait(l);
  422. }
  423. }
  424. TEST_P(ClientCallbackEnd2endTest, SequentialRpcs) {
  425. ResetStub();
  426. SendRpcs(10, false);
  427. }
  428. TEST_P(ClientCallbackEnd2endTest, SendClientInitialMetadata) {
  429. ResetStub();
  430. SimpleRequest request;
  431. SimpleResponse response;
  432. ClientContext cli_ctx;
  433. cli_ctx.AddMetadata(kCheckClientInitialMetadataKey,
  434. kCheckClientInitialMetadataVal);
  435. std::mutex mu;
  436. std::condition_variable cv;
  437. bool done = false;
  438. stub_->async()->CheckClientInitialMetadata(
  439. &cli_ctx, &request, &response, [&done, &mu, &cv](Status s) {
  440. GPR_ASSERT(s.ok());
  441. std::lock_guard<std::mutex> l(mu);
  442. done = true;
  443. cv.notify_one();
  444. });
  445. std::unique_lock<std::mutex> l(mu);
  446. while (!done) {
  447. cv.wait(l);
  448. }
  449. }
  450. TEST_P(ClientCallbackEnd2endTest, SimpleRpcWithBinaryMetadata) {
  451. ResetStub();
  452. SendRpcs(1, true);
  453. }
  454. TEST_P(ClientCallbackEnd2endTest, SequentialRpcsWithVariedBinaryMetadataValue) {
  455. ResetStub();
  456. SendRpcs(10, true);
  457. }
  458. TEST_P(ClientCallbackEnd2endTest, SequentialGenericRpcs) {
  459. ResetStub(absl::make_unique<TestInterceptorFactory>(
  460. "/grpc.testing.EchoTestService/Echo", nullptr));
  461. SendRpcsGeneric(10, false, /*suffix_for_stats=*/nullptr);
  462. }
  463. TEST_P(ClientCallbackEnd2endTest, SequentialGenericRpcsWithSuffix) {
  464. ResetStub(absl::make_unique<TestInterceptorFactory>(
  465. "/grpc.testing.EchoTestService/Echo", "TestSuffix"));
  466. SendRpcsGeneric(10, false, "TestSuffix");
  467. }
  468. TEST_P(ClientCallbackEnd2endTest, SequentialGenericRpcsAsBidi) {
  469. ResetStub(absl::make_unique<TestInterceptorFactory>(
  470. "/grpc.testing.EchoTestService/Echo", nullptr));
  471. SendGenericEchoAsBidi(10, 1, /*do_writes_done=*/true,
  472. /*suffix_for_stats=*/nullptr);
  473. }
  474. TEST_P(ClientCallbackEnd2endTest, SequentialGenericRpcsAsBidiWithSuffix) {
  475. ResetStub(absl::make_unique<TestInterceptorFactory>(
  476. "/grpc.testing.EchoTestService/Echo", "TestSuffix"));
  477. SendGenericEchoAsBidi(10, 1, /*do_writes_done=*/true, "TestSuffix");
  478. }
  479. TEST_P(ClientCallbackEnd2endTest, SequentialGenericRpcsAsBidiWithReactorReuse) {
  480. ResetStub();
  481. SendGenericEchoAsBidi(10, 10, /*do_writes_done=*/true,
  482. /*suffix_for_stats=*/nullptr);
  483. }
  484. TEST_P(ClientCallbackEnd2endTest, GenericRpcNoWritesDone) {
  485. ResetStub();
  486. SendGenericEchoAsBidi(1, 1, /*do_writes_done=*/false,
  487. /*suffix_for_stats=*/nullptr);
  488. }
  489. #if GRPC_ALLOW_EXCEPTIONS
  490. TEST_P(ClientCallbackEnd2endTest, ExceptingRpc) {
  491. ResetStub();
  492. SendRpcsGeneric(10, true, nullptr);
  493. }
  494. #endif
  495. TEST_P(ClientCallbackEnd2endTest, MultipleRpcsWithVariedBinaryMetadataValue) {
  496. ResetStub();
  497. std::vector<std::thread> threads;
  498. threads.reserve(10);
  499. for (int i = 0; i < 10; ++i) {
  500. threads.emplace_back([this] { SendRpcs(10, true); });
  501. }
  502. for (int i = 0; i < 10; ++i) {
  503. threads[i].join();
  504. }
  505. }
  506. TEST_P(ClientCallbackEnd2endTest, MultipleRpcs) {
  507. ResetStub();
  508. std::vector<std::thread> threads;
  509. threads.reserve(10);
  510. for (int i = 0; i < 10; ++i) {
  511. threads.emplace_back([this] { SendRpcs(10, false); });
  512. }
  513. for (int i = 0; i < 10; ++i) {
  514. threads[i].join();
  515. }
  516. }
  517. TEST_P(ClientCallbackEnd2endTest, CancelRpcBeforeStart) {
  518. ResetStub();
  519. EchoRequest request;
  520. EchoResponse response;
  521. ClientContext context;
  522. request.set_message("hello");
  523. context.TryCancel();
  524. std::mutex mu;
  525. std::condition_variable cv;
  526. bool done = false;
  527. stub_->async()->Echo(&context, &request, &response,
  528. [&response, &done, &mu, &cv](Status s) {
  529. EXPECT_EQ("", response.message());
  530. EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
  531. std::lock_guard<std::mutex> l(mu);
  532. done = true;
  533. cv.notify_one();
  534. });
  535. std::unique_lock<std::mutex> l(mu);
  536. while (!done) {
  537. cv.wait(l);
  538. }
  539. if (GetParam().use_interceptors) {
  540. EXPECT_EQ(20, PhonyInterceptor::GetNumTimesCancel());
  541. }
  542. }
  543. TEST_P(ClientCallbackEnd2endTest, RequestEchoServerCancel) {
  544. ResetStub();
  545. EchoRequest request;
  546. EchoResponse response;
  547. ClientContext context;
  548. request.set_message("hello");
  549. context.AddMetadata(kServerTryCancelRequest,
  550. std::to_string(CANCEL_BEFORE_PROCESSING));
  551. std::mutex mu;
  552. std::condition_variable cv;
  553. bool done = false;
  554. stub_->async()->Echo(&context, &request, &response,
  555. [&done, &mu, &cv](Status s) {
  556. EXPECT_FALSE(s.ok());
  557. EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
  558. std::lock_guard<std::mutex> l(mu);
  559. done = true;
  560. cv.notify_one();
  561. });
  562. std::unique_lock<std::mutex> l(mu);
  563. while (!done) {
  564. cv.wait(l);
  565. }
  566. }
  567. struct ClientCancelInfo {
  568. bool cancel{false};
  569. int ops_before_cancel;
  570. ClientCancelInfo() : cancel{false} {}
  571. explicit ClientCancelInfo(int ops) : cancel{true}, ops_before_cancel{ops} {}
  572. };
  573. class WriteClient : public grpc::ClientWriteReactor<EchoRequest> {
  574. public:
  575. WriteClient(grpc::testing::EchoTestService::Stub* stub,
  576. ServerTryCancelRequestPhase server_try_cancel,
  577. int num_msgs_to_send, ClientCancelInfo client_cancel = {})
  578. : server_try_cancel_(server_try_cancel),
  579. num_msgs_to_send_(num_msgs_to_send),
  580. client_cancel_{client_cancel} {
  581. std::string msg{"Hello server."};
  582. for (int i = 0; i < num_msgs_to_send; i++) {
  583. desired_ += msg;
  584. }
  585. if (server_try_cancel != DO_NOT_CANCEL) {
  586. // Send server_try_cancel value in the client metadata
  587. context_.AddMetadata(kServerTryCancelRequest,
  588. std::to_string(server_try_cancel));
  589. }
  590. context_.set_initial_metadata_corked(true);
  591. stub->async()->RequestStream(&context_, &response_, this);
  592. StartCall();
  593. request_.set_message(msg);
  594. MaybeWrite();
  595. }
  596. void OnWriteDone(bool ok) override {
  597. if (ok) {
  598. num_msgs_sent_++;
  599. MaybeWrite();
  600. }
  601. }
  602. void OnDone(const Status& s) override {
  603. gpr_log(GPR_INFO, "Sent %d messages", num_msgs_sent_);
  604. int num_to_send =
  605. (client_cancel_.cancel)
  606. ? std::min(num_msgs_to_send_, client_cancel_.ops_before_cancel)
  607. : num_msgs_to_send_;
  608. switch (server_try_cancel_) {
  609. case CANCEL_BEFORE_PROCESSING:
  610. case CANCEL_DURING_PROCESSING:
  611. // If the RPC is canceled by server before / during messages from the
  612. // client, it means that the client most likely did not get a chance to
  613. // send all the messages it wanted to send. i.e num_msgs_sent <=
  614. // num_msgs_to_send
  615. EXPECT_LE(num_msgs_sent_, num_to_send);
  616. break;
  617. case DO_NOT_CANCEL:
  618. case CANCEL_AFTER_PROCESSING:
  619. // If the RPC was not canceled or canceled after all messages were read
  620. // by the server, the client did get a chance to send all its messages
  621. EXPECT_EQ(num_msgs_sent_, num_to_send);
  622. break;
  623. default:
  624. assert(false);
  625. break;
  626. }
  627. if ((server_try_cancel_ == DO_NOT_CANCEL) && !client_cancel_.cancel) {
  628. EXPECT_TRUE(s.ok());
  629. EXPECT_EQ(response_.message(), desired_);
  630. } else {
  631. EXPECT_FALSE(s.ok());
  632. EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
  633. }
  634. std::unique_lock<std::mutex> l(mu_);
  635. done_ = true;
  636. cv_.notify_one();
  637. }
  638. void Await() {
  639. std::unique_lock<std::mutex> l(mu_);
  640. while (!done_) {
  641. cv_.wait(l);
  642. }
  643. }
  644. private:
  645. void MaybeWrite() {
  646. if (client_cancel_.cancel &&
  647. num_msgs_sent_ == client_cancel_.ops_before_cancel) {
  648. context_.TryCancel();
  649. } else if (num_msgs_to_send_ > num_msgs_sent_ + 1) {
  650. StartWrite(&request_);
  651. } else if (num_msgs_to_send_ == num_msgs_sent_ + 1) {
  652. StartWriteLast(&request_, WriteOptions());
  653. }
  654. }
  655. EchoRequest request_;
  656. EchoResponse response_;
  657. ClientContext context_;
  658. const ServerTryCancelRequestPhase server_try_cancel_;
  659. int num_msgs_sent_{0};
  660. const int num_msgs_to_send_;
  661. std::string desired_;
  662. const ClientCancelInfo client_cancel_;
  663. std::mutex mu_;
  664. std::condition_variable cv_;
  665. bool done_ = false;
  666. };
  667. TEST_P(ClientCallbackEnd2endTest, RequestStream) {
  668. ResetStub();
  669. WriteClient test{stub_.get(), DO_NOT_CANCEL, 3};
  670. test.Await();
  671. // Make sure that the server interceptors were not notified to cancel
  672. if (GetParam().use_interceptors) {
  673. EXPECT_EQ(0, PhonyInterceptor::GetNumTimesCancel());
  674. }
  675. }
  676. TEST_P(ClientCallbackEnd2endTest, ClientCancelsRequestStream) {
  677. ResetStub();
  678. WriteClient test{stub_.get(), DO_NOT_CANCEL, 3, ClientCancelInfo{2}};
  679. test.Await();
  680. // Make sure that the server interceptors got the cancel
  681. if (GetParam().use_interceptors) {
  682. EXPECT_EQ(20, PhonyInterceptor::GetNumTimesCancel());
  683. }
  684. }
  685. // Server to cancel before doing reading the request
  686. TEST_P(ClientCallbackEnd2endTest, RequestStreamServerCancelBeforeReads) {
  687. ResetStub();
  688. WriteClient test{stub_.get(), CANCEL_BEFORE_PROCESSING, 1};
  689. test.Await();
  690. // Make sure that the server interceptors were notified
  691. if (GetParam().use_interceptors) {
  692. EXPECT_EQ(20, PhonyInterceptor::GetNumTimesCancel());
  693. }
  694. }
  695. // Server to cancel while reading a request from the stream in parallel
  696. TEST_P(ClientCallbackEnd2endTest, RequestStreamServerCancelDuringRead) {
  697. ResetStub();
  698. WriteClient test{stub_.get(), CANCEL_DURING_PROCESSING, 10};
  699. test.Await();
  700. // Make sure that the server interceptors were notified
  701. if (GetParam().use_interceptors) {
  702. EXPECT_EQ(20, PhonyInterceptor::GetNumTimesCancel());
  703. }
  704. }
  705. // Server to cancel after reading all the requests but before returning to the
  706. // client
  707. TEST_P(ClientCallbackEnd2endTest, RequestStreamServerCancelAfterReads) {
  708. ResetStub();
  709. WriteClient test{stub_.get(), CANCEL_AFTER_PROCESSING, 4};
  710. test.Await();
  711. // Make sure that the server interceptors were notified
  712. if (GetParam().use_interceptors) {
  713. EXPECT_EQ(20, PhonyInterceptor::GetNumTimesCancel());
  714. }
  715. }
  716. TEST_P(ClientCallbackEnd2endTest, UnaryReactor) {
  717. ResetStub();
  718. class UnaryClient : public grpc::ClientUnaryReactor {
  719. public:
  720. explicit UnaryClient(grpc::testing::EchoTestService::Stub* stub) {
  721. cli_ctx_.AddMetadata("key1", "val1");
  722. cli_ctx_.AddMetadata("key2", "val2");
  723. request_.mutable_param()->set_echo_metadata_initially(true);
  724. request_.set_message("Hello metadata");
  725. stub->async()->Echo(&cli_ctx_, &request_, &response_, this);
  726. StartCall();
  727. }
  728. void OnReadInitialMetadataDone(bool ok) override {
  729. EXPECT_TRUE(ok);
  730. EXPECT_EQ(1u, cli_ctx_.GetServerInitialMetadata().count("key1"));
  731. EXPECT_EQ(
  732. "val1",
  733. ToString(cli_ctx_.GetServerInitialMetadata().find("key1")->second));
  734. EXPECT_EQ(1u, cli_ctx_.GetServerInitialMetadata().count("key2"));
  735. EXPECT_EQ(
  736. "val2",
  737. ToString(cli_ctx_.GetServerInitialMetadata().find("key2")->second));
  738. initial_metadata_done_ = true;
  739. }
  740. void OnDone(const Status& s) override {
  741. EXPECT_TRUE(initial_metadata_done_);
  742. EXPECT_EQ(0u, cli_ctx_.GetServerTrailingMetadata().size());
  743. EXPECT_TRUE(s.ok());
  744. EXPECT_EQ(request_.message(), response_.message());
  745. std::unique_lock<std::mutex> l(mu_);
  746. done_ = true;
  747. cv_.notify_one();
  748. }
  749. void Await() {
  750. std::unique_lock<std::mutex> l(mu_);
  751. while (!done_) {
  752. cv_.wait(l);
  753. }
  754. }
  755. private:
  756. EchoRequest request_;
  757. EchoResponse response_;
  758. ClientContext cli_ctx_;
  759. std::mutex mu_;
  760. std::condition_variable cv_;
  761. bool done_{false};
  762. bool initial_metadata_done_{false};
  763. };
  764. UnaryClient test{stub_.get()};
  765. test.Await();
  766. // Make sure that the server interceptors were not notified of a cancel
  767. if (GetParam().use_interceptors) {
  768. EXPECT_EQ(0, PhonyInterceptor::GetNumTimesCancel());
  769. }
  770. }
  771. TEST_P(ClientCallbackEnd2endTest, GenericUnaryReactor) {
  772. const std::string kMethodName("/grpc.testing.EchoTestService/Echo");
  773. constexpr char kSuffixForStats[] = "TestSuffixForStats";
  774. ResetStub(
  775. absl::make_unique<TestInterceptorFactory>(kMethodName, kSuffixForStats));
  776. class UnaryClient : public grpc::ClientUnaryReactor {
  777. public:
  778. UnaryClient(grpc::GenericStub* stub, const std::string& method_name,
  779. const char* suffix_for_stats) {
  780. cli_ctx_.AddMetadata("key1", "val1");
  781. cli_ctx_.AddMetadata("key2", "val2");
  782. request_.mutable_param()->set_echo_metadata_initially(true);
  783. request_.set_message("Hello metadata");
  784. send_buf_ = SerializeToByteBuffer(&request_);
  785. StubOptions options(suffix_for_stats);
  786. stub->PrepareUnaryCall(&cli_ctx_, method_name, options, send_buf_.get(),
  787. &recv_buf_, this);
  788. StartCall();
  789. }
  790. void OnReadInitialMetadataDone(bool ok) override {
  791. EXPECT_TRUE(ok);
  792. EXPECT_EQ(1u, cli_ctx_.GetServerInitialMetadata().count("key1"));
  793. EXPECT_EQ(
  794. "val1",
  795. ToString(cli_ctx_.GetServerInitialMetadata().find("key1")->second));
  796. EXPECT_EQ(1u, cli_ctx_.GetServerInitialMetadata().count("key2"));
  797. EXPECT_EQ(
  798. "val2",
  799. ToString(cli_ctx_.GetServerInitialMetadata().find("key2")->second));
  800. initial_metadata_done_ = true;
  801. }
  802. void OnDone(const Status& s) override {
  803. EXPECT_TRUE(initial_metadata_done_);
  804. EXPECT_EQ(0u, cli_ctx_.GetServerTrailingMetadata().size());
  805. EXPECT_TRUE(s.ok());
  806. EchoResponse response;
  807. EXPECT_TRUE(ParseFromByteBuffer(&recv_buf_, &response));
  808. EXPECT_EQ(request_.message(), response.message());
  809. std::unique_lock<std::mutex> l(mu_);
  810. done_ = true;
  811. cv_.notify_one();
  812. }
  813. void Await() {
  814. std::unique_lock<std::mutex> l(mu_);
  815. while (!done_) {
  816. cv_.wait(l);
  817. }
  818. }
  819. private:
  820. EchoRequest request_;
  821. std::unique_ptr<ByteBuffer> send_buf_;
  822. ByteBuffer recv_buf_;
  823. ClientContext cli_ctx_;
  824. std::mutex mu_;
  825. std::condition_variable cv_;
  826. bool done_{false};
  827. bool initial_metadata_done_{false};
  828. };
  829. UnaryClient test{generic_stub_.get(), kMethodName, kSuffixForStats};
  830. test.Await();
  831. // Make sure that the server interceptors were not notified of a cancel
  832. if (GetParam().use_interceptors) {
  833. EXPECT_EQ(0, PhonyInterceptor::GetNumTimesCancel());
  834. }
  835. }
  836. class ReadClient : public grpc::ClientReadReactor<EchoResponse> {
  837. public:
  838. ReadClient(grpc::testing::EchoTestService::Stub* stub,
  839. ServerTryCancelRequestPhase server_try_cancel,
  840. ClientCancelInfo client_cancel = {})
  841. : server_try_cancel_(server_try_cancel), client_cancel_{client_cancel} {
  842. if (server_try_cancel_ != DO_NOT_CANCEL) {
  843. // Send server_try_cancel value in the client metadata
  844. context_.AddMetadata(kServerTryCancelRequest,
  845. std::to_string(server_try_cancel));
  846. }
  847. request_.set_message("Hello client ");
  848. stub->async()->ResponseStream(&context_, &request_, this);
  849. if (client_cancel_.cancel &&
  850. reads_complete_ == client_cancel_.ops_before_cancel) {
  851. context_.TryCancel();
  852. }
  853. // Even if we cancel, read until failure because there might be responses
  854. // pending
  855. StartRead(&response_);
  856. StartCall();
  857. }
  858. void OnReadDone(bool ok) override {
  859. if (!ok) {
  860. if (server_try_cancel_ == DO_NOT_CANCEL && !client_cancel_.cancel) {
  861. EXPECT_EQ(reads_complete_, kServerDefaultResponseStreamsToSend);
  862. }
  863. } else {
  864. EXPECT_LE(reads_complete_, kServerDefaultResponseStreamsToSend);
  865. EXPECT_EQ(response_.message(),
  866. request_.message() + std::to_string(reads_complete_));
  867. reads_complete_++;
  868. if (client_cancel_.cancel &&
  869. reads_complete_ == client_cancel_.ops_before_cancel) {
  870. context_.TryCancel();
  871. }
  872. // Even if we cancel, read until failure because there might be responses
  873. // pending
  874. StartRead(&response_);
  875. }
  876. }
  877. void OnDone(const Status& s) override {
  878. gpr_log(GPR_INFO, "Read %d messages", reads_complete_);
  879. switch (server_try_cancel_) {
  880. case DO_NOT_CANCEL:
  881. if (!client_cancel_.cancel || client_cancel_.ops_before_cancel >
  882. kServerDefaultResponseStreamsToSend) {
  883. EXPECT_TRUE(s.ok());
  884. EXPECT_EQ(reads_complete_, kServerDefaultResponseStreamsToSend);
  885. } else {
  886. EXPECT_GE(reads_complete_, client_cancel_.ops_before_cancel);
  887. EXPECT_LE(reads_complete_, kServerDefaultResponseStreamsToSend);
  888. // Status might be ok or cancelled depending on whether server
  889. // sent status before client cancel went through
  890. if (!s.ok()) {
  891. EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
  892. }
  893. }
  894. break;
  895. case CANCEL_BEFORE_PROCESSING:
  896. EXPECT_FALSE(s.ok());
  897. EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
  898. EXPECT_EQ(reads_complete_, 0);
  899. break;
  900. case CANCEL_DURING_PROCESSING:
  901. case CANCEL_AFTER_PROCESSING:
  902. // If server canceled while writing messages, client must have read
  903. // less than or equal to the expected number of messages. Even if the
  904. // server canceled after writing all messages, the RPC may be canceled
  905. // before the Client got a chance to read all the messages.
  906. EXPECT_FALSE(s.ok());
  907. EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
  908. EXPECT_LE(reads_complete_, kServerDefaultResponseStreamsToSend);
  909. break;
  910. default:
  911. assert(false);
  912. }
  913. std::unique_lock<std::mutex> l(mu_);
  914. done_ = true;
  915. cv_.notify_one();
  916. }
  917. void Await() {
  918. std::unique_lock<std::mutex> l(mu_);
  919. while (!done_) {
  920. cv_.wait(l);
  921. }
  922. }
  923. private:
  924. EchoRequest request_;
  925. EchoResponse response_;
  926. ClientContext context_;
  927. const ServerTryCancelRequestPhase server_try_cancel_;
  928. int reads_complete_{0};
  929. const ClientCancelInfo client_cancel_;
  930. std::mutex mu_;
  931. std::condition_variable cv_;
  932. bool done_ = false;
  933. };
  934. TEST_P(ClientCallbackEnd2endTest, ResponseStream) {
  935. ResetStub();
  936. ReadClient test{stub_.get(), DO_NOT_CANCEL};
  937. test.Await();
  938. // Make sure that the server interceptors were not notified of a cancel
  939. if (GetParam().use_interceptors) {
  940. EXPECT_EQ(0, PhonyInterceptor::GetNumTimesCancel());
  941. }
  942. }
  943. TEST_P(ClientCallbackEnd2endTest, ClientCancelsResponseStream) {
  944. ResetStub();
  945. ReadClient test{stub_.get(), DO_NOT_CANCEL, ClientCancelInfo{2}};
  946. test.Await();
  947. // Because cancel in this case races with server finish, we can't be sure that
  948. // server interceptors even see cancellation
  949. }
  950. // Server to cancel before sending any response messages
  951. TEST_P(ClientCallbackEnd2endTest, ResponseStreamServerCancelBefore) {
  952. ResetStub();
  953. ReadClient test{stub_.get(), CANCEL_BEFORE_PROCESSING};
  954. test.Await();
  955. // Make sure that the server interceptors were notified
  956. if (GetParam().use_interceptors) {
  957. EXPECT_EQ(20, PhonyInterceptor::GetNumTimesCancel());
  958. }
  959. }
  960. // Server to cancel while writing a response to the stream in parallel
  961. TEST_P(ClientCallbackEnd2endTest, ResponseStreamServerCancelDuring) {
  962. ResetStub();
  963. ReadClient test{stub_.get(), CANCEL_DURING_PROCESSING};
  964. test.Await();
  965. // Make sure that the server interceptors were notified
  966. if (GetParam().use_interceptors) {
  967. EXPECT_EQ(20, PhonyInterceptor::GetNumTimesCancel());
  968. }
  969. }
  970. // Server to cancel after writing all the respones to the stream but before
  971. // returning to the client
  972. TEST_P(ClientCallbackEnd2endTest, ResponseStreamServerCancelAfter) {
  973. ResetStub();
  974. ReadClient test{stub_.get(), CANCEL_AFTER_PROCESSING};
  975. test.Await();
  976. // Make sure that the server interceptors were notified
  977. if (GetParam().use_interceptors) {
  978. EXPECT_EQ(20, PhonyInterceptor::GetNumTimesCancel());
  979. }
  980. }
  981. class BidiClient : public grpc::ClientBidiReactor<EchoRequest, EchoResponse> {
  982. public:
  983. BidiClient(grpc::testing::EchoTestService::Stub* stub,
  984. ServerTryCancelRequestPhase server_try_cancel,
  985. int num_msgs_to_send, bool cork_metadata, bool first_write_async,
  986. ClientCancelInfo client_cancel = {})
  987. : server_try_cancel_(server_try_cancel),
  988. msgs_to_send_{num_msgs_to_send},
  989. client_cancel_{client_cancel} {
  990. if (server_try_cancel_ != DO_NOT_CANCEL) {
  991. // Send server_try_cancel value in the client metadata
  992. context_.AddMetadata(kServerTryCancelRequest,
  993. std::to_string(server_try_cancel));
  994. }
  995. request_.set_message("Hello fren ");
  996. context_.set_initial_metadata_corked(cork_metadata);
  997. stub->async()->BidiStream(&context_, this);
  998. MaybeAsyncWrite(first_write_async);
  999. StartRead(&response_);
  1000. StartCall();
  1001. }
  1002. void OnReadDone(bool ok) override {
  1003. if (!ok) {
  1004. if (server_try_cancel_ == DO_NOT_CANCEL) {
  1005. if (!client_cancel_.cancel) {
  1006. EXPECT_EQ(reads_complete_, msgs_to_send_);
  1007. } else {
  1008. EXPECT_LE(reads_complete_, writes_complete_);
  1009. }
  1010. }
  1011. } else {
  1012. EXPECT_LE(reads_complete_, msgs_to_send_);
  1013. EXPECT_EQ(response_.message(), request_.message());
  1014. reads_complete_++;
  1015. StartRead(&response_);
  1016. }
  1017. }
  1018. void OnWriteDone(bool ok) override {
  1019. if (async_write_thread_.joinable()) {
  1020. async_write_thread_.join();
  1021. RemoveHold();
  1022. }
  1023. if (server_try_cancel_ == DO_NOT_CANCEL) {
  1024. EXPECT_TRUE(ok);
  1025. } else if (!ok) {
  1026. return;
  1027. }
  1028. writes_complete_++;
  1029. MaybeWrite();
  1030. }
  1031. void OnDone(const Status& s) override {
  1032. gpr_log(GPR_INFO, "Sent %d messages", writes_complete_);
  1033. gpr_log(GPR_INFO, "Read %d messages", reads_complete_);
  1034. switch (server_try_cancel_) {
  1035. case DO_NOT_CANCEL:
  1036. if (!client_cancel_.cancel ||
  1037. client_cancel_.ops_before_cancel > msgs_to_send_) {
  1038. EXPECT_TRUE(s.ok());
  1039. EXPECT_EQ(writes_complete_, msgs_to_send_);
  1040. EXPECT_EQ(reads_complete_, writes_complete_);
  1041. } else {
  1042. EXPECT_FALSE(s.ok());
  1043. EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
  1044. EXPECT_EQ(writes_complete_, client_cancel_.ops_before_cancel);
  1045. EXPECT_LE(reads_complete_, writes_complete_);
  1046. }
  1047. break;
  1048. case CANCEL_BEFORE_PROCESSING:
  1049. EXPECT_FALSE(s.ok());
  1050. EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
  1051. // The RPC is canceled before the server did any work or returned any
  1052. // reads, but it's possible that some writes took place first from the
  1053. // client
  1054. EXPECT_LE(writes_complete_, msgs_to_send_);
  1055. EXPECT_EQ(reads_complete_, 0);
  1056. break;
  1057. case CANCEL_DURING_PROCESSING:
  1058. EXPECT_FALSE(s.ok());
  1059. EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
  1060. EXPECT_LE(writes_complete_, msgs_to_send_);
  1061. EXPECT_LE(reads_complete_, writes_complete_);
  1062. break;
  1063. case CANCEL_AFTER_PROCESSING:
  1064. EXPECT_FALSE(s.ok());
  1065. EXPECT_EQ(grpc::StatusCode::CANCELLED, s.error_code());
  1066. EXPECT_EQ(writes_complete_, msgs_to_send_);
  1067. // The Server canceled after reading the last message and after writing
  1068. // the message to the client. However, the RPC cancellation might have
  1069. // taken effect before the client actually read the response.
  1070. EXPECT_LE(reads_complete_, writes_complete_);
  1071. break;
  1072. default:
  1073. assert(false);
  1074. }
  1075. std::unique_lock<std::mutex> l(mu_);
  1076. done_ = true;
  1077. cv_.notify_one();
  1078. }
  1079. void Await() {
  1080. std::unique_lock<std::mutex> l(mu_);
  1081. while (!done_) {
  1082. cv_.wait(l);
  1083. }
  1084. }
  1085. private:
  1086. void MaybeAsyncWrite(bool first_write_async) {
  1087. if (first_write_async) {
  1088. // Make sure that we have a write to issue.
  1089. // TODO(vjpai): Make this work with 0 writes case as well.
  1090. assert(msgs_to_send_ >= 1);
  1091. AddHold();
  1092. async_write_thread_ = std::thread([this] {
  1093. std::unique_lock<std::mutex> lock(async_write_thread_mu_);
  1094. async_write_thread_cv_.wait(
  1095. lock, [this] { return async_write_thread_start_; });
  1096. MaybeWrite();
  1097. });
  1098. std::lock_guard<std::mutex> lock(async_write_thread_mu_);
  1099. async_write_thread_start_ = true;
  1100. async_write_thread_cv_.notify_one();
  1101. return;
  1102. }
  1103. MaybeWrite();
  1104. }
  1105. void MaybeWrite() {
  1106. if (client_cancel_.cancel &&
  1107. writes_complete_ == client_cancel_.ops_before_cancel) {
  1108. context_.TryCancel();
  1109. } else if (writes_complete_ == msgs_to_send_) {
  1110. StartWritesDone();
  1111. } else {
  1112. StartWrite(&request_);
  1113. }
  1114. }
  1115. EchoRequest request_;
  1116. EchoResponse response_;
  1117. ClientContext context_;
  1118. const ServerTryCancelRequestPhase server_try_cancel_;
  1119. int reads_complete_{0};
  1120. int writes_complete_{0};
  1121. const int msgs_to_send_;
  1122. const ClientCancelInfo client_cancel_;
  1123. std::mutex mu_;
  1124. std::condition_variable cv_;
  1125. bool done_ = false;
  1126. std::thread async_write_thread_;
  1127. bool async_write_thread_start_ = false;
  1128. std::mutex async_write_thread_mu_;
  1129. std::condition_variable async_write_thread_cv_;
  1130. };
  1131. TEST_P(ClientCallbackEnd2endTest, BidiStream) {
  1132. ResetStub();
  1133. BidiClient test(stub_.get(), DO_NOT_CANCEL,
  1134. kServerDefaultResponseStreamsToSend,
  1135. /*cork_metadata=*/false, /*first_write_async=*/false);
  1136. test.Await();
  1137. // Make sure that the server interceptors were not notified of a cancel
  1138. if (GetParam().use_interceptors) {
  1139. EXPECT_EQ(0, PhonyInterceptor::GetNumTimesCancel());
  1140. }
  1141. }
  1142. TEST_P(ClientCallbackEnd2endTest, BidiStreamFirstWriteAsync) {
  1143. ResetStub();
  1144. BidiClient test(stub_.get(), DO_NOT_CANCEL,
  1145. kServerDefaultResponseStreamsToSend,
  1146. /*cork_metadata=*/false, /*first_write_async=*/true);
  1147. test.Await();
  1148. // Make sure that the server interceptors were not notified of a cancel
  1149. if (GetParam().use_interceptors) {
  1150. EXPECT_EQ(0, PhonyInterceptor::GetNumTimesCancel());
  1151. }
  1152. }
  1153. TEST_P(ClientCallbackEnd2endTest, BidiStreamCorked) {
  1154. ResetStub();
  1155. BidiClient test(stub_.get(), DO_NOT_CANCEL,
  1156. kServerDefaultResponseStreamsToSend,
  1157. /*cork_metadata=*/true, /*first_write_async=*/false);
  1158. test.Await();
  1159. // Make sure that the server interceptors were not notified of a cancel
  1160. if (GetParam().use_interceptors) {
  1161. EXPECT_EQ(0, PhonyInterceptor::GetNumTimesCancel());
  1162. }
  1163. }
  1164. TEST_P(ClientCallbackEnd2endTest, BidiStreamCorkedFirstWriteAsync) {
  1165. ResetStub();
  1166. BidiClient test(stub_.get(), DO_NOT_CANCEL,
  1167. kServerDefaultResponseStreamsToSend,
  1168. /*cork_metadata=*/true, /*first_write_async=*/true);
  1169. test.Await();
  1170. // Make sure that the server interceptors were not notified of a cancel
  1171. if (GetParam().use_interceptors) {
  1172. EXPECT_EQ(0, PhonyInterceptor::GetNumTimesCancel());
  1173. }
  1174. }
  1175. TEST_P(ClientCallbackEnd2endTest, ClientCancelsBidiStream) {
  1176. ResetStub();
  1177. BidiClient test(stub_.get(), DO_NOT_CANCEL,
  1178. kServerDefaultResponseStreamsToSend,
  1179. /*cork_metadata=*/false, /*first_write_async=*/false,
  1180. ClientCancelInfo(2));
  1181. test.Await();
  1182. // Make sure that the server interceptors were notified of a cancel
  1183. if (GetParam().use_interceptors) {
  1184. EXPECT_EQ(20, PhonyInterceptor::GetNumTimesCancel());
  1185. }
  1186. }
  1187. // Server to cancel before reading/writing any requests/responses on the stream
  1188. TEST_P(ClientCallbackEnd2endTest, BidiStreamServerCancelBefore) {
  1189. ResetStub();
  1190. BidiClient test(stub_.get(), CANCEL_BEFORE_PROCESSING, /*num_msgs_to_send=*/2,
  1191. /*cork_metadata=*/false, /*first_write_async=*/false);
  1192. test.Await();
  1193. // Make sure that the server interceptors were notified
  1194. if (GetParam().use_interceptors) {
  1195. EXPECT_EQ(20, PhonyInterceptor::GetNumTimesCancel());
  1196. }
  1197. }
  1198. // Server to cancel while reading/writing requests/responses on the stream in
  1199. // parallel
  1200. TEST_P(ClientCallbackEnd2endTest, BidiStreamServerCancelDuring) {
  1201. ResetStub();
  1202. BidiClient test(stub_.get(), CANCEL_DURING_PROCESSING,
  1203. /*num_msgs_to_send=*/10, /*cork_metadata=*/false,
  1204. /*first_write_async=*/false);
  1205. test.Await();
  1206. // Make sure that the server interceptors were notified
  1207. if (GetParam().use_interceptors) {
  1208. EXPECT_EQ(20, PhonyInterceptor::GetNumTimesCancel());
  1209. }
  1210. }
  1211. // Server to cancel after reading/writing all requests/responses on the stream
  1212. // but before returning to the client
  1213. TEST_P(ClientCallbackEnd2endTest, BidiStreamServerCancelAfter) {
  1214. ResetStub();
  1215. BidiClient test(stub_.get(), CANCEL_AFTER_PROCESSING, /*num_msgs_to_send=*/5,
  1216. /*cork_metadata=*/false, /*first_write_async=*/false);
  1217. test.Await();
  1218. // Make sure that the server interceptors were notified
  1219. if (GetParam().use_interceptors) {
  1220. EXPECT_EQ(20, PhonyInterceptor::GetNumTimesCancel());
  1221. }
  1222. }
  1223. TEST_P(ClientCallbackEnd2endTest, SimultaneousReadAndWritesDone) {
  1224. ResetStub();
  1225. class Client : public grpc::ClientBidiReactor<EchoRequest, EchoResponse> {
  1226. public:
  1227. explicit Client(grpc::testing::EchoTestService::Stub* stub) {
  1228. request_.set_message("Hello bidi ");
  1229. stub->async()->BidiStream(&context_, this);
  1230. StartWrite(&request_);
  1231. StartCall();
  1232. }
  1233. void OnReadDone(bool ok) override {
  1234. EXPECT_TRUE(ok);
  1235. EXPECT_EQ(response_.message(), request_.message());
  1236. }
  1237. void OnWriteDone(bool ok) override {
  1238. EXPECT_TRUE(ok);
  1239. // Now send out the simultaneous Read and WritesDone
  1240. StartWritesDone();
  1241. StartRead(&response_);
  1242. }
  1243. void OnDone(const Status& s) override {
  1244. EXPECT_TRUE(s.ok());
  1245. EXPECT_EQ(response_.message(), request_.message());
  1246. std::unique_lock<std::mutex> l(mu_);
  1247. done_ = true;
  1248. cv_.notify_one();
  1249. }
  1250. void Await() {
  1251. std::unique_lock<std::mutex> l(mu_);
  1252. while (!done_) {
  1253. cv_.wait(l);
  1254. }
  1255. }
  1256. private:
  1257. EchoRequest request_;
  1258. EchoResponse response_;
  1259. ClientContext context_;
  1260. std::mutex mu_;
  1261. std::condition_variable cv_;
  1262. bool done_ = false;
  1263. } test{stub_.get()};
  1264. test.Await();
  1265. }
  1266. TEST_P(ClientCallbackEnd2endTest, UnimplementedRpc) {
  1267. ChannelArguments args;
  1268. const auto& channel_creds = GetCredentialsProvider()->GetChannelCredentials(
  1269. GetParam().credentials_type, &args);
  1270. std::shared_ptr<Channel> channel =
  1271. (GetParam().protocol == Protocol::TCP)
  1272. ? grpc::CreateCustomChannel(server_address_.str(), channel_creds,
  1273. args)
  1274. : server_->InProcessChannel(args);
  1275. std::unique_ptr<grpc::testing::UnimplementedEchoService::Stub> stub;
  1276. stub = grpc::testing::UnimplementedEchoService::NewStub(channel);
  1277. EchoRequest request;
  1278. EchoResponse response;
  1279. ClientContext cli_ctx;
  1280. request.set_message("Hello world.");
  1281. std::mutex mu;
  1282. std::condition_variable cv;
  1283. bool done = false;
  1284. stub->async()->Unimplemented(
  1285. &cli_ctx, &request, &response, [&done, &mu, &cv](Status s) {
  1286. EXPECT_EQ(StatusCode::UNIMPLEMENTED, s.error_code());
  1287. EXPECT_EQ("", s.error_message());
  1288. std::lock_guard<std::mutex> l(mu);
  1289. done = true;
  1290. cv.notify_one();
  1291. });
  1292. std::unique_lock<std::mutex> l(mu);
  1293. while (!done) {
  1294. cv.wait(l);
  1295. }
  1296. }
  1297. TEST_P(ClientCallbackEnd2endTest, TestTrailersOnlyOnError) {
  1298. // Note that trailers-only is an HTTP/2 concept so we shouldn't do this test
  1299. // for any other transport such as inproc.
  1300. if (GetParam().protocol != Protocol::TCP) {
  1301. return;
  1302. }
  1303. ResetStub();
  1304. class Reactor : public grpc::ClientBidiReactor<EchoRequest, EchoResponse> {
  1305. public:
  1306. explicit Reactor(grpc::testing::EchoTestService::Stub* stub) {
  1307. stub->async()->UnimplementedBidi(&context_, this);
  1308. StartCall();
  1309. }
  1310. void Await() {
  1311. std::unique_lock<std::mutex> l(mu_);
  1312. while (!done_) {
  1313. done_cv_.wait(l);
  1314. }
  1315. }
  1316. private:
  1317. void OnReadInitialMetadataDone(bool ok) override { EXPECT_FALSE(ok); }
  1318. void OnDone(const Status& s) override {
  1319. EXPECT_EQ(s.error_code(), grpc::StatusCode::UNIMPLEMENTED);
  1320. EXPECT_EQ(s.error_message(), "");
  1321. std::unique_lock<std::mutex> l(mu_);
  1322. done_ = true;
  1323. done_cv_.notify_one();
  1324. }
  1325. ClientContext context_;
  1326. std::mutex mu_;
  1327. std::condition_variable done_cv_;
  1328. bool done_ = false;
  1329. } client(stub_.get());
  1330. client.Await();
  1331. }
  1332. TEST_P(ClientCallbackEnd2endTest,
  1333. ResponseStreamExtraReactionFlowReadsUntilDone) {
  1334. ResetStub();
  1335. class ReadAllIncomingDataClient
  1336. : public grpc::ClientReadReactor<EchoResponse> {
  1337. public:
  1338. explicit ReadAllIncomingDataClient(
  1339. grpc::testing::EchoTestService::Stub* stub) {
  1340. request_.set_message("Hello client ");
  1341. stub->async()->ResponseStream(&context_, &request_, this);
  1342. }
  1343. bool WaitForReadDone() {
  1344. std::unique_lock<std::mutex> l(mu_);
  1345. while (!read_done_) {
  1346. read_cv_.wait(l);
  1347. }
  1348. read_done_ = false;
  1349. return read_ok_;
  1350. }
  1351. void Await() {
  1352. std::unique_lock<std::mutex> l(mu_);
  1353. while (!done_) {
  1354. done_cv_.wait(l);
  1355. }
  1356. }
  1357. // RemoveHold under the same lock used for OnDone to make sure that we don't
  1358. // call OnDone directly or indirectly from the RemoveHold function.
  1359. void RemoveHoldUnderLock() {
  1360. std::unique_lock<std::mutex> l(mu_);
  1361. RemoveHold();
  1362. }
  1363. const Status& status() {
  1364. std::unique_lock<std::mutex> l(mu_);
  1365. return status_;
  1366. }
  1367. private:
  1368. void OnReadDone(bool ok) override {
  1369. std::unique_lock<std::mutex> l(mu_);
  1370. read_ok_ = ok;
  1371. read_done_ = true;
  1372. read_cv_.notify_one();
  1373. }
  1374. void OnDone(const Status& s) override {
  1375. std::unique_lock<std::mutex> l(mu_);
  1376. done_ = true;
  1377. status_ = s;
  1378. done_cv_.notify_one();
  1379. }
  1380. EchoRequest request_;
  1381. EchoResponse response_;
  1382. ClientContext context_;
  1383. bool read_ok_ = false;
  1384. bool read_done_ = false;
  1385. std::mutex mu_;
  1386. std::condition_variable read_cv_;
  1387. std::condition_variable done_cv_;
  1388. bool done_ = false;
  1389. Status status_;
  1390. } client{stub_.get()};
  1391. int reads_complete = 0;
  1392. client.AddHold();
  1393. client.StartCall();
  1394. EchoResponse response;
  1395. bool read_ok = true;
  1396. while (read_ok) {
  1397. client.StartRead(&response);
  1398. read_ok = client.WaitForReadDone();
  1399. if (read_ok) {
  1400. ++reads_complete;
  1401. }
  1402. }
  1403. client.RemoveHoldUnderLock();
  1404. client.Await();
  1405. EXPECT_EQ(kServerDefaultResponseStreamsToSend, reads_complete);
  1406. EXPECT_EQ(client.status().error_code(), grpc::StatusCode::OK);
  1407. }
  1408. std::vector<TestScenario> CreateTestScenarios(bool test_insecure) {
  1409. #if TARGET_OS_IPHONE
  1410. // Workaround Apple CFStream bug
  1411. gpr_setenv("grpc_cfstream", "0");
  1412. #endif
  1413. std::vector<TestScenario> scenarios;
  1414. std::vector<std::string> credentials_types{
  1415. GetCredentialsProvider()->GetSecureCredentialsTypeList()};
  1416. auto insec_ok = [] {
  1417. // Only allow insecure credentials type when it is registered with the
  1418. // provider. User may create providers that do not have insecure.
  1419. return GetCredentialsProvider()->GetChannelCredentials(
  1420. kInsecureCredentialsType, nullptr) != nullptr;
  1421. };
  1422. if (test_insecure && insec_ok()) {
  1423. credentials_types.push_back(kInsecureCredentialsType);
  1424. }
  1425. GPR_ASSERT(!credentials_types.empty());
  1426. bool barr[]{false, true};
  1427. Protocol parr[]{Protocol::INPROC, Protocol::TCP};
  1428. for (Protocol p : parr) {
  1429. for (const auto& cred : credentials_types) {
  1430. // TODO(vjpai): Test inproc with secure credentials when feasible
  1431. if (p == Protocol::INPROC &&
  1432. (cred != kInsecureCredentialsType || !insec_ok())) {
  1433. continue;
  1434. }
  1435. for (bool callback_server : barr) {
  1436. for (bool use_interceptors : barr) {
  1437. scenarios.emplace_back(callback_server, p, use_interceptors, cred);
  1438. }
  1439. }
  1440. }
  1441. }
  1442. return scenarios;
  1443. }
  1444. INSTANTIATE_TEST_SUITE_P(ClientCallbackEnd2endTest, ClientCallbackEnd2endTest,
  1445. ::testing::ValuesIn(CreateTestScenarios(true)));
  1446. } // namespace
  1447. } // namespace testing
  1448. } // namespace grpc
  1449. int main(int argc, char** argv) {
  1450. ::testing::InitGoogleTest(&argc, argv);
  1451. grpc::testing::TestEnvironment env(argc, argv);
  1452. grpc_init();
  1453. int ret = RUN_ALL_TESTS();
  1454. grpc_shutdown();
  1455. return ret;
  1456. }