test_service_impl.cc 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. /*
  2. *
  3. * Copyright 2016 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 "test/cpp/end2end/test_service_impl.h"
  19. #include <string>
  20. #include <thread>
  21. #include <gtest/gtest.h>
  22. #include <grpc/support/log.h>
  23. #include <grpcpp/alarm.h>
  24. #include <grpcpp/security/credentials.h>
  25. #include <grpcpp/server_context.h>
  26. #include "src/proto/grpc/testing/echo.grpc.pb.h"
  27. #include "test/cpp/util/string_ref_helper.h"
  28. using std::chrono::system_clock;
  29. namespace grpc {
  30. namespace testing {
  31. namespace internal {
  32. // When echo_deadline is requested, deadline seen in the ServerContext is set in
  33. // the response in seconds.
  34. void MaybeEchoDeadline(ServerContextBase* context, const EchoRequest* request,
  35. EchoResponse* response) {
  36. if (request->has_param() && request->param().echo_deadline()) {
  37. gpr_timespec deadline = gpr_inf_future(GPR_CLOCK_REALTIME);
  38. if (context->deadline() != system_clock::time_point::max()) {
  39. Timepoint2Timespec(context->deadline(), &deadline);
  40. }
  41. response->mutable_param()->set_request_deadline(deadline.tv_sec);
  42. }
  43. }
  44. void CheckServerAuthContext(const ServerContextBase* context,
  45. const std::string& expected_transport_security_type,
  46. const std::string& expected_client_identity) {
  47. std::shared_ptr<const AuthContext> auth_ctx = context->auth_context();
  48. std::vector<grpc::string_ref> tst =
  49. auth_ctx->FindPropertyValues("transport_security_type");
  50. EXPECT_EQ(1u, tst.size());
  51. EXPECT_EQ(expected_transport_security_type, ToString(tst[0]));
  52. if (expected_client_identity.empty()) {
  53. EXPECT_TRUE(auth_ctx->GetPeerIdentityPropertyName().empty());
  54. EXPECT_TRUE(auth_ctx->GetPeerIdentity().empty());
  55. EXPECT_FALSE(auth_ctx->IsPeerAuthenticated());
  56. } else {
  57. auto identity = auth_ctx->GetPeerIdentity();
  58. EXPECT_TRUE(auth_ctx->IsPeerAuthenticated());
  59. EXPECT_EQ(1u, identity.size());
  60. EXPECT_EQ(expected_client_identity, identity[0]);
  61. }
  62. }
  63. // Returns the number of pairs in metadata that exactly match the given
  64. // key-value pair. Returns -1 if the pair wasn't found.
  65. int MetadataMatchCount(
  66. const std::multimap<grpc::string_ref, grpc::string_ref>& metadata,
  67. const std::string& key, const std::string& value) {
  68. int count = 0;
  69. for (const auto& metadatum : metadata) {
  70. if (ToString(metadatum.first) == key &&
  71. ToString(metadatum.second) == value) {
  72. count++;
  73. }
  74. }
  75. return count;
  76. }
  77. int GetIntValueFromMetadataHelper(
  78. const char* key,
  79. const std::multimap<grpc::string_ref, grpc::string_ref>& metadata,
  80. int default_value) {
  81. if (metadata.find(key) != metadata.end()) {
  82. std::istringstream iss(ToString(metadata.find(key)->second));
  83. iss >> default_value;
  84. gpr_log(GPR_INFO, "%s : %d", key, default_value);
  85. }
  86. return default_value;
  87. }
  88. int GetIntValueFromMetadata(
  89. const char* key,
  90. const std::multimap<grpc::string_ref, grpc::string_ref>& metadata,
  91. int default_value) {
  92. return GetIntValueFromMetadataHelper(key, metadata, default_value);
  93. }
  94. void ServerTryCancel(ServerContext* context) {
  95. EXPECT_FALSE(context->IsCancelled());
  96. context->TryCancel();
  97. gpr_log(GPR_INFO, "Server called TryCancel() to cancel the request");
  98. // Now wait until it's really canceled
  99. while (!context->IsCancelled()) {
  100. gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
  101. gpr_time_from_micros(1000, GPR_TIMESPAN)));
  102. }
  103. }
  104. void ServerTryCancelNonblocking(CallbackServerContext* context) {
  105. EXPECT_FALSE(context->IsCancelled());
  106. context->TryCancel();
  107. gpr_log(GPR_INFO,
  108. "Server called TryCancelNonblocking() to cancel the request");
  109. }
  110. } // namespace internal
  111. ServerUnaryReactor* CallbackTestServiceImpl::Echo(
  112. CallbackServerContext* context, const EchoRequest* request,
  113. EchoResponse* response) {
  114. class Reactor : public grpc::ServerUnaryReactor {
  115. public:
  116. Reactor(CallbackTestServiceImpl* service, CallbackServerContext* ctx,
  117. const EchoRequest* request, EchoResponse* response)
  118. : service_(service), ctx_(ctx), req_(request), resp_(response) {
  119. // It should be safe to call IsCancelled here, even though we don't know
  120. // the result. Call it asynchronously to see if we trigger any data races.
  121. // Join it in OnDone (technically that could be blocking but shouldn't be
  122. // for very long).
  123. async_cancel_check_ = std::thread([this] { (void)ctx_->IsCancelled(); });
  124. started_ = true;
  125. if (request->has_param() &&
  126. request->param().server_notify_client_when_started()) {
  127. service->signaller_.SignalClientThatRpcStarted();
  128. // Block on the "wait to continue" decision in a different thread since
  129. // we can't tie up an EM thread with blocking events. We can join it in
  130. // OnDone since it would definitely be done by then.
  131. rpc_wait_thread_ = std::thread([this] {
  132. service_->signaller_.ServerWaitToContinue();
  133. StartRpc();
  134. });
  135. } else {
  136. StartRpc();
  137. }
  138. }
  139. void StartRpc() {
  140. if (req_->has_param() && req_->param().server_sleep_us() > 0) {
  141. // Set an alarm for that much time
  142. alarm_.Set(
  143. gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC),
  144. gpr_time_from_micros(req_->param().server_sleep_us(),
  145. GPR_TIMESPAN)),
  146. [this](bool ok) { NonDelayed(ok); });
  147. return;
  148. }
  149. NonDelayed(true);
  150. }
  151. void OnSendInitialMetadataDone(bool ok) override {
  152. EXPECT_TRUE(ok);
  153. initial_metadata_sent_ = true;
  154. }
  155. void OnCancel() override {
  156. EXPECT_TRUE(started_);
  157. EXPECT_TRUE(ctx_->IsCancelled());
  158. on_cancel_invoked_ = true;
  159. std::lock_guard<std::mutex> l(cancel_mu_);
  160. cancel_cv_.notify_one();
  161. }
  162. void OnDone() override {
  163. if (req_->has_param() && req_->param().echo_metadata_initially()) {
  164. EXPECT_TRUE(initial_metadata_sent_);
  165. }
  166. EXPECT_EQ(ctx_->IsCancelled(), on_cancel_invoked_);
  167. // Validate that finishing with a non-OK status doesn't cause cancellation
  168. if (req_->has_param() && req_->param().has_expected_error()) {
  169. EXPECT_FALSE(on_cancel_invoked_);
  170. }
  171. async_cancel_check_.join();
  172. if (rpc_wait_thread_.joinable()) {
  173. rpc_wait_thread_.join();
  174. }
  175. if (finish_when_cancelled_.joinable()) {
  176. finish_when_cancelled_.join();
  177. }
  178. delete this;
  179. }
  180. private:
  181. void NonDelayed(bool ok) {
  182. if (!ok) {
  183. EXPECT_TRUE(ctx_->IsCancelled());
  184. Finish(Status::CANCELLED);
  185. return;
  186. }
  187. if (req_->has_param() && req_->param().server_die()) {
  188. gpr_log(GPR_ERROR, "The request should not reach application handler.");
  189. GPR_ASSERT(0);
  190. }
  191. if (req_->has_param() && req_->param().has_expected_error()) {
  192. const auto& error = req_->param().expected_error();
  193. Finish(Status(static_cast<StatusCode>(error.code()),
  194. error.error_message(), error.binary_error_details()));
  195. return;
  196. }
  197. int server_try_cancel = internal::GetIntValueFromMetadata(
  198. kServerTryCancelRequest, ctx_->client_metadata(), DO_NOT_CANCEL);
  199. if (server_try_cancel != DO_NOT_CANCEL) {
  200. // Since this is a unary RPC, by the time this server handler is called,
  201. // the 'request' message is already read from the client. So the
  202. // scenarios in server_try_cancel don't make much sense. Just cancel the
  203. // RPC as long as server_try_cancel is not DO_NOT_CANCEL
  204. EXPECT_FALSE(ctx_->IsCancelled());
  205. ctx_->TryCancel();
  206. gpr_log(GPR_INFO, "Server called TryCancel() to cancel the request");
  207. FinishWhenCancelledAsync();
  208. return;
  209. }
  210. resp_->set_message(req_->message());
  211. internal::MaybeEchoDeadline(ctx_, req_, resp_);
  212. if (service_->host_) {
  213. resp_->mutable_param()->set_host(*service_->host_);
  214. }
  215. if (req_->has_param() && req_->param().client_cancel_after_us()) {
  216. {
  217. std::unique_lock<std::mutex> lock(service_->mu_);
  218. service_->signal_client_ = true;
  219. }
  220. FinishWhenCancelledAsync();
  221. return;
  222. } else if (req_->has_param() && req_->param().server_cancel_after_us()) {
  223. alarm_.Set(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
  224. gpr_time_from_micros(
  225. req_->param().server_cancel_after_us(),
  226. GPR_TIMESPAN)),
  227. [this](bool) { Finish(Status::CANCELLED); });
  228. return;
  229. } else if (!req_->has_param() || !req_->param().skip_cancelled_check()) {
  230. EXPECT_FALSE(ctx_->IsCancelled());
  231. }
  232. if (req_->has_param() && req_->param().echo_metadata_initially()) {
  233. const std::multimap<grpc::string_ref, grpc::string_ref>&
  234. client_metadata = ctx_->client_metadata();
  235. for (const auto& metadatum : client_metadata) {
  236. ctx_->AddInitialMetadata(ToString(metadatum.first),
  237. ToString(metadatum.second));
  238. }
  239. StartSendInitialMetadata();
  240. }
  241. if (req_->has_param() && req_->param().echo_metadata()) {
  242. const std::multimap<grpc::string_ref, grpc::string_ref>&
  243. client_metadata = ctx_->client_metadata();
  244. for (const auto& metadatum : client_metadata) {
  245. ctx_->AddTrailingMetadata(ToString(metadatum.first),
  246. ToString(metadatum.second));
  247. }
  248. // Terminate rpc with error and debug info in trailer.
  249. if (req_->param().debug_info().stack_entries_size() ||
  250. !req_->param().debug_info().detail().empty()) {
  251. std::string serialized_debug_info =
  252. req_->param().debug_info().SerializeAsString();
  253. ctx_->AddTrailingMetadata(kDebugInfoTrailerKey,
  254. serialized_debug_info);
  255. Finish(Status::CANCELLED);
  256. return;
  257. }
  258. }
  259. if (req_->has_param() &&
  260. (req_->param().expected_client_identity().length() > 0 ||
  261. req_->param().check_auth_context())) {
  262. internal::CheckServerAuthContext(
  263. ctx_, req_->param().expected_transport_security_type(),
  264. req_->param().expected_client_identity());
  265. }
  266. if (req_->has_param() && req_->param().response_message_length() > 0) {
  267. resp_->set_message(
  268. std::string(req_->param().response_message_length(), '\0'));
  269. }
  270. if (req_->has_param() && req_->param().echo_peer()) {
  271. resp_->mutable_param()->set_peer(ctx_->peer());
  272. }
  273. Finish(Status::OK);
  274. }
  275. void FinishWhenCancelledAsync() {
  276. finish_when_cancelled_ = std::thread([this] {
  277. std::unique_lock<std::mutex> l(cancel_mu_);
  278. cancel_cv_.wait(l, [this] { return ctx_->IsCancelled(); });
  279. Finish(Status::CANCELLED);
  280. });
  281. }
  282. CallbackTestServiceImpl* const service_;
  283. CallbackServerContext* const ctx_;
  284. const EchoRequest* const req_;
  285. EchoResponse* const resp_;
  286. Alarm alarm_;
  287. std::mutex cancel_mu_;
  288. std::condition_variable cancel_cv_;
  289. bool initial_metadata_sent_ = false;
  290. bool started_ = false;
  291. bool on_cancel_invoked_ = false;
  292. std::thread async_cancel_check_;
  293. std::thread rpc_wait_thread_;
  294. std::thread finish_when_cancelled_;
  295. };
  296. return new Reactor(this, context, request, response);
  297. }
  298. ServerUnaryReactor* CallbackTestServiceImpl::CheckClientInitialMetadata(
  299. CallbackServerContext* context, const SimpleRequest*, SimpleResponse*) {
  300. class Reactor : public grpc::ServerUnaryReactor {
  301. public:
  302. explicit Reactor(CallbackServerContext* ctx) {
  303. EXPECT_EQ(internal::MetadataMatchCount(ctx->client_metadata(),
  304. kCheckClientInitialMetadataKey,
  305. kCheckClientInitialMetadataVal),
  306. 1);
  307. EXPECT_EQ(ctx->client_metadata().count(kCheckClientInitialMetadataKey),
  308. 1u);
  309. Finish(Status::OK);
  310. }
  311. void OnDone() override { delete this; }
  312. };
  313. return new Reactor(context);
  314. }
  315. ServerReadReactor<EchoRequest>* CallbackTestServiceImpl::RequestStream(
  316. CallbackServerContext* context, EchoResponse* response) {
  317. // If 'server_try_cancel' is set in the metadata, the RPC is cancelled by
  318. // the server by calling ServerContext::TryCancel() depending on the
  319. // value:
  320. // CANCEL_BEFORE_PROCESSING: The RPC is cancelled before the server
  321. // reads any message from the client CANCEL_DURING_PROCESSING: The RPC
  322. // is cancelled while the server is reading messages from the client
  323. // CANCEL_AFTER_PROCESSING: The RPC is cancelled after the server reads
  324. // all the messages from the client
  325. int server_try_cancel = internal::GetIntValueFromMetadata(
  326. kServerTryCancelRequest, context->client_metadata(), DO_NOT_CANCEL);
  327. if (server_try_cancel == CANCEL_BEFORE_PROCESSING) {
  328. internal::ServerTryCancelNonblocking(context);
  329. // Don't need to provide a reactor since the RPC is canceled
  330. return nullptr;
  331. }
  332. class Reactor : public grpc::ServerReadReactor<EchoRequest> {
  333. public:
  334. Reactor(CallbackServerContext* ctx, EchoResponse* response,
  335. int server_try_cancel)
  336. : ctx_(ctx),
  337. response_(response),
  338. server_try_cancel_(server_try_cancel) {
  339. EXPECT_NE(server_try_cancel, CANCEL_BEFORE_PROCESSING);
  340. response->set_message("");
  341. if (server_try_cancel_ == CANCEL_DURING_PROCESSING) {
  342. ctx->TryCancel();
  343. // Don't wait for it here
  344. }
  345. StartRead(&request_);
  346. setup_done_ = true;
  347. }
  348. void OnDone() override { delete this; }
  349. void OnCancel() override {
  350. EXPECT_TRUE(setup_done_);
  351. EXPECT_TRUE(ctx_->IsCancelled());
  352. FinishOnce(Status::CANCELLED);
  353. }
  354. void OnReadDone(bool ok) override {
  355. if (ok) {
  356. response_->mutable_message()->append(request_.message());
  357. num_msgs_read_++;
  358. StartRead(&request_);
  359. } else {
  360. gpr_log(GPR_INFO, "Read: %d messages", num_msgs_read_);
  361. if (server_try_cancel_ == CANCEL_DURING_PROCESSING) {
  362. // Let OnCancel recover this
  363. return;
  364. }
  365. if (server_try_cancel_ == CANCEL_AFTER_PROCESSING) {
  366. internal::ServerTryCancelNonblocking(ctx_);
  367. return;
  368. }
  369. FinishOnce(Status::OK);
  370. }
  371. }
  372. private:
  373. void FinishOnce(const Status& s) {
  374. std::lock_guard<std::mutex> l(finish_mu_);
  375. if (!finished_) {
  376. Finish(s);
  377. finished_ = true;
  378. }
  379. }
  380. CallbackServerContext* const ctx_;
  381. EchoResponse* const response_;
  382. EchoRequest request_;
  383. int num_msgs_read_{0};
  384. int server_try_cancel_;
  385. std::mutex finish_mu_;
  386. bool finished_{false};
  387. bool setup_done_{false};
  388. };
  389. return new Reactor(context, response, server_try_cancel);
  390. }
  391. // Return 'kNumResponseStreamMsgs' messages.
  392. // TODO(yangg) make it generic by adding a parameter into EchoRequest
  393. ServerWriteReactor<EchoResponse>* CallbackTestServiceImpl::ResponseStream(
  394. CallbackServerContext* context, const EchoRequest* request) {
  395. // If 'server_try_cancel' is set in the metadata, the RPC is cancelled by
  396. // the server by calling ServerContext::TryCancel() depending on the
  397. // value:
  398. // CANCEL_BEFORE_PROCESSING: The RPC is cancelled before the server
  399. // reads any message from the client CANCEL_DURING_PROCESSING: The RPC
  400. // is cancelled while the server is reading messages from the client
  401. // CANCEL_AFTER_PROCESSING: The RPC is cancelled after the server reads
  402. // all the messages from the client
  403. int server_try_cancel = internal::GetIntValueFromMetadata(
  404. kServerTryCancelRequest, context->client_metadata(), DO_NOT_CANCEL);
  405. if (server_try_cancel == CANCEL_BEFORE_PROCESSING) {
  406. internal::ServerTryCancelNonblocking(context);
  407. }
  408. class Reactor : public grpc::ServerWriteReactor<EchoResponse> {
  409. public:
  410. Reactor(CallbackServerContext* ctx, const EchoRequest* request,
  411. int server_try_cancel)
  412. : ctx_(ctx), request_(request), server_try_cancel_(server_try_cancel) {
  413. server_coalescing_api_ = internal::GetIntValueFromMetadata(
  414. kServerUseCoalescingApi, ctx->client_metadata(), 0);
  415. server_responses_to_send_ = internal::GetIntValueFromMetadata(
  416. kServerResponseStreamsToSend, ctx->client_metadata(),
  417. kServerDefaultResponseStreamsToSend);
  418. if (server_try_cancel_ == CANCEL_DURING_PROCESSING) {
  419. ctx->TryCancel();
  420. }
  421. if (server_try_cancel_ != CANCEL_BEFORE_PROCESSING) {
  422. if (num_msgs_sent_ < server_responses_to_send_) {
  423. NextWrite();
  424. }
  425. }
  426. setup_done_ = true;
  427. }
  428. void OnDone() override { delete this; }
  429. void OnCancel() override {
  430. EXPECT_TRUE(setup_done_);
  431. EXPECT_TRUE(ctx_->IsCancelled());
  432. FinishOnce(Status::CANCELLED);
  433. }
  434. void OnWriteDone(bool /*ok*/) override {
  435. if (num_msgs_sent_ < server_responses_to_send_) {
  436. NextWrite();
  437. } else if (server_coalescing_api_ != 0) {
  438. // We would have already done Finish just after the WriteLast
  439. } else if (server_try_cancel_ == CANCEL_DURING_PROCESSING) {
  440. // Let OnCancel recover this
  441. } else if (server_try_cancel_ == CANCEL_AFTER_PROCESSING) {
  442. internal::ServerTryCancelNonblocking(ctx_);
  443. } else {
  444. FinishOnce(Status::OK);
  445. }
  446. }
  447. private:
  448. void FinishOnce(const Status& s) {
  449. std::lock_guard<std::mutex> l(finish_mu_);
  450. if (!finished_) {
  451. Finish(s);
  452. finished_ = true;
  453. }
  454. }
  455. void NextWrite() {
  456. response_.set_message(request_->message() +
  457. std::to_string(num_msgs_sent_));
  458. if (num_msgs_sent_ == server_responses_to_send_ - 1 &&
  459. server_coalescing_api_ != 0) {
  460. {
  461. std::lock_guard<std::mutex> l(finish_mu_);
  462. if (!finished_) {
  463. num_msgs_sent_++;
  464. StartWriteLast(&response_, WriteOptions());
  465. }
  466. }
  467. // If we use WriteLast, we shouldn't wait before attempting Finish
  468. FinishOnce(Status::OK);
  469. } else {
  470. std::lock_guard<std::mutex> l(finish_mu_);
  471. if (!finished_) {
  472. num_msgs_sent_++;
  473. StartWrite(&response_);
  474. }
  475. }
  476. }
  477. CallbackServerContext* const ctx_;
  478. const EchoRequest* const request_;
  479. EchoResponse response_;
  480. int num_msgs_sent_{0};
  481. int server_try_cancel_;
  482. int server_coalescing_api_;
  483. int server_responses_to_send_;
  484. std::mutex finish_mu_;
  485. bool finished_{false};
  486. bool setup_done_{false};
  487. };
  488. return new Reactor(context, request, server_try_cancel);
  489. }
  490. ServerBidiReactor<EchoRequest, EchoResponse>*
  491. CallbackTestServiceImpl::BidiStream(CallbackServerContext* context) {
  492. class Reactor : public grpc::ServerBidiReactor<EchoRequest, EchoResponse> {
  493. public:
  494. explicit Reactor(CallbackServerContext* ctx) : ctx_(ctx) {
  495. // If 'server_try_cancel' is set in the metadata, the RPC is cancelled by
  496. // the server by calling ServerContext::TryCancel() depending on the
  497. // value:
  498. // CANCEL_BEFORE_PROCESSING: The RPC is cancelled before the server
  499. // reads any message from the client CANCEL_DURING_PROCESSING: The RPC
  500. // is cancelled while the server is reading messages from the client
  501. // CANCEL_AFTER_PROCESSING: The RPC is cancelled after the server reads
  502. // all the messages from the client
  503. server_try_cancel_ = internal::GetIntValueFromMetadata(
  504. kServerTryCancelRequest, ctx->client_metadata(), DO_NOT_CANCEL);
  505. server_write_last_ = internal::GetIntValueFromMetadata(
  506. kServerFinishAfterNReads, ctx->client_metadata(), 0);
  507. client_try_cancel_ = static_cast<bool>(internal::GetIntValueFromMetadata(
  508. kClientTryCancelRequest, ctx->client_metadata(), 0));
  509. if (server_try_cancel_ == CANCEL_BEFORE_PROCESSING) {
  510. internal::ServerTryCancelNonblocking(ctx);
  511. } else {
  512. if (server_try_cancel_ == CANCEL_DURING_PROCESSING) {
  513. ctx->TryCancel();
  514. }
  515. StartRead(&request_);
  516. }
  517. setup_done_ = true;
  518. }
  519. void OnDone() override {
  520. {
  521. // Use the same lock as finish to make sure that OnDone isn't inlined.
  522. std::lock_guard<std::mutex> l(finish_mu_);
  523. EXPECT_TRUE(finished_);
  524. finish_thread_.join();
  525. }
  526. delete this;
  527. }
  528. void OnCancel() override {
  529. EXPECT_TRUE(setup_done_);
  530. EXPECT_TRUE(ctx_->IsCancelled());
  531. FinishOnce(Status::CANCELLED);
  532. }
  533. void OnReadDone(bool ok) override {
  534. if (ok) {
  535. num_msgs_read_++;
  536. response_.set_message(request_.message());
  537. std::lock_guard<std::mutex> l(finish_mu_);
  538. if (!finished_) {
  539. if (num_msgs_read_ == server_write_last_) {
  540. StartWriteLast(&response_, WriteOptions());
  541. // If we use WriteLast, we shouldn't wait before attempting Finish
  542. } else {
  543. StartWrite(&response_);
  544. return;
  545. }
  546. }
  547. } else if (client_try_cancel_) {
  548. EXPECT_TRUE(ctx_->IsCancelled());
  549. }
  550. if (server_try_cancel_ == CANCEL_DURING_PROCESSING) {
  551. // Let OnCancel handle this
  552. } else if (server_try_cancel_ == CANCEL_AFTER_PROCESSING) {
  553. internal::ServerTryCancelNonblocking(ctx_);
  554. } else {
  555. FinishOnce(Status::OK);
  556. }
  557. }
  558. void OnWriteDone(bool /*ok*/) override {
  559. std::lock_guard<std::mutex> l(finish_mu_);
  560. if (!finished_) {
  561. StartRead(&request_);
  562. }
  563. }
  564. private:
  565. void FinishOnce(const Status& s) {
  566. std::lock_guard<std::mutex> l(finish_mu_);
  567. if (!finished_) {
  568. finished_ = true;
  569. // Finish asynchronously to make sure that there are no deadlocks.
  570. finish_thread_ = std::thread([this, s] {
  571. std::lock_guard<std::mutex> l(finish_mu_);
  572. Finish(s);
  573. });
  574. }
  575. }
  576. CallbackServerContext* const ctx_;
  577. EchoRequest request_;
  578. EchoResponse response_;
  579. int num_msgs_read_{0};
  580. int server_try_cancel_;
  581. int server_write_last_;
  582. std::mutex finish_mu_;
  583. bool finished_{false};
  584. bool setup_done_{false};
  585. std::thread finish_thread_;
  586. bool client_try_cancel_ = false;
  587. };
  588. return new Reactor(context);
  589. }
  590. } // namespace testing
  591. } // namespace grpc