You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

client_callback.h 60 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442
  1. /*
  2. *
  3. * Copyright 2019 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. #ifndef GRPCPP_IMPL_CODEGEN_CLIENT_CALLBACK_H
  18. #define GRPCPP_IMPL_CODEGEN_CLIENT_CALLBACK_H
  19. // IWYU pragma: private, include <grpcpp/support/client_callback.h>
  20. #include <atomic>
  21. #include <functional>
  22. #include <grpcpp/impl/codegen/call.h>
  23. #include <grpcpp/impl/codegen/call_op_set.h>
  24. #include <grpcpp/impl/codegen/callback_common.h>
  25. #include <grpcpp/impl/codegen/channel_interface.h>
  26. #include <grpcpp/impl/codegen/config.h>
  27. #include <grpcpp/impl/codegen/core_codegen_interface.h>
  28. #include <grpcpp/impl/codegen/status.h>
  29. #include <grpcpp/impl/codegen/sync.h>
  30. namespace grpc
  31. {
  32. class Channel;
  33. class ClientContext;
  34. namespace internal
  35. {
  36. class RpcMethod;
  37. /// Perform a callback-based unary call. May optionally specify the base
  38. /// class of the Request and Response so that the internal calls and structures
  39. /// below this may be based on those base classes and thus achieve code reuse
  40. /// across different RPCs (e.g., for protobuf, MessageLite would be a base
  41. /// class).
  42. /// TODO(vjpai): Combine as much as possible with the blocking unary call code
  43. template<class InputMessage, class OutputMessage, class BaseInputMessage = InputMessage, class BaseOutputMessage = OutputMessage>
  44. void CallbackUnaryCall(grpc::ChannelInterface* channel, const grpc::internal::RpcMethod& method, grpc::ClientContext* context, const InputMessage* request, OutputMessage* result, std::function<void(grpc::Status)> on_completion)
  45. {
  46. static_assert(std::is_base_of<BaseInputMessage, InputMessage>::value, "Invalid input message specification");
  47. static_assert(std::is_base_of<BaseOutputMessage, OutputMessage>::value, "Invalid output message specification");
  48. CallbackUnaryCallImpl<BaseInputMessage, BaseOutputMessage> x(
  49. channel, method, context, request, result, on_completion
  50. );
  51. }
  52. template<class InputMessage, class OutputMessage>
  53. class CallbackUnaryCallImpl
  54. {
  55. public:
  56. CallbackUnaryCallImpl(grpc::ChannelInterface* channel, const grpc::internal::RpcMethod& method, grpc::ClientContext* context, const InputMessage* request, OutputMessage* result, std::function<void(grpc::Status)> on_completion)
  57. {
  58. grpc::CompletionQueue* cq = channel->CallbackCQ();
  59. GPR_CODEGEN_ASSERT(cq != nullptr);
  60. grpc::internal::Call call(channel->CreateCall(method, context, cq));
  61. using FullCallOpSet = grpc::internal::CallOpSet<
  62. grpc::internal::CallOpSendInitialMetadata,
  63. grpc::internal::CallOpSendMessage,
  64. grpc::internal::CallOpRecvInitialMetadata,
  65. grpc::internal::CallOpRecvMessage<OutputMessage>,
  66. grpc::internal::CallOpClientSendClose,
  67. grpc::internal::CallOpClientRecvStatus>;
  68. struct OpSetAndTag
  69. {
  70. FullCallOpSet opset;
  71. grpc::internal::CallbackWithStatusTag tag;
  72. };
  73. const size_t alloc_sz = sizeof(OpSetAndTag);
  74. auto* const alloced = static_cast<OpSetAndTag*>(
  75. grpc::g_core_codegen_interface->grpc_call_arena_alloc(call.call(), alloc_sz)
  76. );
  77. auto* ops = new (&alloced->opset) FullCallOpSet;
  78. auto* tag = new (&alloced->tag)
  79. grpc::internal::CallbackWithStatusTag(call.call(), on_completion, ops);
  80. // TODO(vjpai): Unify code with sync API as much as possible
  81. grpc::Status s = ops->SendMessagePtr(request);
  82. if (!s.ok())
  83. {
  84. tag->force_run(s);
  85. return;
  86. }
  87. ops->SendInitialMetadata(&context->send_initial_metadata_, context->initial_metadata_flags());
  88. ops->RecvInitialMetadata(context);
  89. ops->RecvMessage(result);
  90. ops->AllowNoMessage();
  91. ops->ClientSendClose();
  92. ops->ClientRecvStatus(context, tag->status_ptr());
  93. ops->set_core_cq_tag(tag);
  94. call.PerformOps(ops);
  95. }
  96. };
  97. // Base class for public API classes.
  98. class ClientReactor
  99. {
  100. public:
  101. virtual ~ClientReactor() = default;
  102. /// Called by the library when all operations associated with this RPC have
  103. /// completed and all Holds have been removed. OnDone provides the RPC status
  104. /// outcome for both successful and failed RPCs. If it is never called on an
  105. /// RPC, it indicates an application-level problem (like failure to remove a
  106. /// hold).
  107. ///
  108. /// \param[in] s The status outcome of this RPC
  109. virtual void OnDone(const grpc::Status& /*s*/) = 0;
  110. /// InternalScheduleOnDone is not part of the API and is not meant to be
  111. /// overridden. It is virtual to allow successful builds for certain bazel
  112. /// build users that only want to depend on gRPC codegen headers and not the
  113. /// full library (although this is not a generally-supported option). Although
  114. /// the virtual call is slower than a direct call, this function is
  115. /// heavyweight and the cost of the virtual call is not much in comparison.
  116. /// This function may be removed or devirtualized in the future.
  117. virtual void InternalScheduleOnDone(grpc::Status s);
  118. /// InternalTrailersOnly is not part of the API and is not meant to be
  119. /// overridden. It is virtual to allow successful builds for certain bazel
  120. /// build users that only want to depend on gRPC codegen headers and not the
  121. /// full library (although this is not a generally-supported option). Although
  122. /// the virtual call is slower than a direct call, this function is
  123. /// heavyweight and the cost of the virtual call is not much in comparison.
  124. /// This function may be removed or devirtualized in the future.
  125. virtual bool InternalTrailersOnly(const grpc_call* call) const;
  126. };
  127. } // namespace internal
  128. // Forward declarations
  129. template<class Request, class Response>
  130. class ClientBidiReactor;
  131. template<class Response>
  132. class ClientReadReactor;
  133. template<class Request>
  134. class ClientWriteReactor;
  135. class ClientUnaryReactor;
  136. // NOTE: The streaming objects are not actually implemented in the public API.
  137. // These interfaces are provided for mocking only. Typical applications
  138. // will interact exclusively with the reactors that they define.
  139. template<class Request, class Response>
  140. class ClientCallbackReaderWriter
  141. {
  142. public:
  143. virtual ~ClientCallbackReaderWriter()
  144. {
  145. }
  146. virtual void StartCall() = 0;
  147. virtual void Write(const Request* req, grpc::WriteOptions options) = 0;
  148. virtual void WritesDone() = 0;
  149. virtual void Read(Response* resp) = 0;
  150. virtual void AddHold(int holds) = 0;
  151. virtual void RemoveHold() = 0;
  152. protected:
  153. void BindReactor(ClientBidiReactor<Request, Response>* reactor)
  154. {
  155. reactor->BindStream(this);
  156. }
  157. };
  158. template<class Response>
  159. class ClientCallbackReader
  160. {
  161. public:
  162. virtual ~ClientCallbackReader()
  163. {
  164. }
  165. virtual void StartCall() = 0;
  166. virtual void Read(Response* resp) = 0;
  167. virtual void AddHold(int holds) = 0;
  168. virtual void RemoveHold() = 0;
  169. protected:
  170. void BindReactor(ClientReadReactor<Response>* reactor)
  171. {
  172. reactor->BindReader(this);
  173. }
  174. };
  175. template<class Request>
  176. class ClientCallbackWriter
  177. {
  178. public:
  179. virtual ~ClientCallbackWriter()
  180. {
  181. }
  182. virtual void StartCall() = 0;
  183. void Write(const Request* req)
  184. {
  185. Write(req, grpc::WriteOptions());
  186. }
  187. virtual void Write(const Request* req, grpc::WriteOptions options) = 0;
  188. void WriteLast(const Request* req, grpc::WriteOptions options)
  189. {
  190. Write(req, options.set_last_message());
  191. }
  192. virtual void WritesDone() = 0;
  193. virtual void AddHold(int holds) = 0;
  194. virtual void RemoveHold() = 0;
  195. protected:
  196. void BindReactor(ClientWriteReactor<Request>* reactor)
  197. {
  198. reactor->BindWriter(this);
  199. }
  200. };
  201. class ClientCallbackUnary
  202. {
  203. public:
  204. virtual ~ClientCallbackUnary()
  205. {
  206. }
  207. virtual void StartCall() = 0;
  208. protected:
  209. void BindReactor(ClientUnaryReactor* reactor);
  210. };
  211. // The following classes are the reactor interfaces that are to be implemented
  212. // by the user. They are passed in to the library as an argument to a call on a
  213. // stub (either a codegen-ed call or a generic call). The streaming RPC is
  214. // activated by calling StartCall, possibly after initiating StartRead,
  215. // StartWrite, or AddHold operations on the streaming object. Note that none of
  216. // the classes are pure; all reactions have a default empty reaction so that the
  217. // user class only needs to override those reactions that it cares about.
  218. // The reactor must be passed to the stub invocation before any of the below
  219. // operations can be called and its reactions will be invoked by the library in
  220. // response to the completion of various operations. Reactions must not include
  221. // blocking operations (such as blocking I/O, starting synchronous RPCs, or
  222. // waiting on condition variables). Reactions may be invoked concurrently,
  223. // except that OnDone is called after all others (assuming proper API usage).
  224. // The reactor may not be deleted until OnDone is called.
  225. /// \a ClientBidiReactor is the interface for a bidirectional streaming RPC.
  226. template<class Request, class Response>
  227. class ClientBidiReactor : public internal::ClientReactor
  228. {
  229. public:
  230. /// Activate the RPC and initiate any reads or writes that have been Start'ed
  231. /// before this call. All streaming RPCs issued by the client MUST have
  232. /// StartCall invoked on them (even if they are canceled) as this call is the
  233. /// activation of their lifecycle.
  234. void StartCall()
  235. {
  236. stream_->StartCall();
  237. }
  238. /// Initiate a read operation (or post it for later initiation if StartCall
  239. /// has not yet been invoked).
  240. ///
  241. /// \param[out] resp Where to eventually store the read message. Valid when
  242. /// the library calls OnReadDone
  243. void StartRead(Response* resp)
  244. {
  245. stream_->Read(resp);
  246. }
  247. /// Initiate a write operation (or post it for later initiation if StartCall
  248. /// has not yet been invoked).
  249. ///
  250. /// \param[in] req The message to be written. The library does not take
  251. /// ownership but the caller must ensure that the message is
  252. /// not deleted or modified until OnWriteDone is called.
  253. void StartWrite(const Request* req)
  254. {
  255. StartWrite(req, grpc::WriteOptions());
  256. }
  257. /// Initiate/post a write operation with specified options.
  258. ///
  259. /// \param[in] req The message to be written. The library does not take
  260. /// ownership but the caller must ensure that the message is
  261. /// not deleted or modified until OnWriteDone is called.
  262. /// \param[in] options The WriteOptions to use for writing this message
  263. void StartWrite(const Request* req, grpc::WriteOptions options)
  264. {
  265. stream_->Write(req, options);
  266. }
  267. /// Initiate/post a write operation with specified options and an indication
  268. /// that this is the last write (like StartWrite and StartWritesDone, merged).
  269. /// Note that calling this means that no more calls to StartWrite,
  270. /// StartWriteLast, or StartWritesDone are allowed.
  271. ///
  272. /// \param[in] req The message to be written. The library does not take
  273. /// ownership but the caller must ensure that the message is
  274. /// not deleted or modified until OnWriteDone is called.
  275. /// \param[in] options The WriteOptions to use for writing this message
  276. void StartWriteLast(const Request* req, grpc::WriteOptions options)
  277. {
  278. StartWrite(req, options.set_last_message());
  279. }
  280. /// Indicate that the RPC will have no more write operations. This can only be
  281. /// issued once for a given RPC. This is not required or allowed if
  282. /// StartWriteLast is used since that already has the same implication.
  283. /// Note that calling this means that no more calls to StartWrite,
  284. /// StartWriteLast, or StartWritesDone are allowed.
  285. void StartWritesDone()
  286. {
  287. stream_->WritesDone();
  288. }
  289. /// Holds are needed if (and only if) this stream has operations that take
  290. /// place on it after StartCall but from outside one of the reactions
  291. /// (OnReadDone, etc). This is _not_ a common use of the streaming API.
  292. ///
  293. /// Holds must be added before calling StartCall. If a stream still has a hold
  294. /// in place, its resources will not be destroyed even if the status has
  295. /// already come in from the wire and there are currently no active callbacks
  296. /// outstanding. Similarly, the stream will not call OnDone if there are still
  297. /// holds on it.
  298. ///
  299. /// For example, if a StartRead or StartWrite operation is going to be
  300. /// initiated from elsewhere in the application, the application should call
  301. /// AddHold or AddMultipleHolds before StartCall. If there is going to be,
  302. /// for example, a read-flow and a write-flow taking place outside the
  303. /// reactions, then call AddMultipleHolds(2) before StartCall. When the
  304. /// application knows that it won't issue any more read operations (such as
  305. /// when a read comes back as not ok), it should issue a RemoveHold(). It
  306. /// should also call RemoveHold() again after it does StartWriteLast or
  307. /// StartWritesDone that indicates that there will be no more write ops.
  308. /// The number of RemoveHold calls must match the total number of AddHold
  309. /// calls plus the number of holds added by AddMultipleHolds.
  310. /// The argument to AddMultipleHolds must be positive.
  311. void AddHold()
  312. {
  313. AddMultipleHolds(1);
  314. }
  315. void AddMultipleHolds(int holds)
  316. {
  317. GPR_CODEGEN_DEBUG_ASSERT(holds > 0);
  318. stream_->AddHold(holds);
  319. }
  320. void RemoveHold()
  321. {
  322. stream_->RemoveHold();
  323. }
  324. /// Notifies the application that all operations associated with this RPC
  325. /// have completed and all Holds have been removed. OnDone provides the RPC
  326. /// status outcome for both successful and failed RPCs and will be called in
  327. /// all cases. If it is not called, it indicates an application-level problem
  328. /// (like failure to remove a hold).
  329. ///
  330. /// \param[in] s The status outcome of this RPC
  331. void OnDone(const grpc::Status& /*s*/) override
  332. {
  333. }
  334. /// Notifies the application that a read of initial metadata from the
  335. /// server is done. If the application chooses not to implement this method,
  336. /// it can assume that the initial metadata has been read before the first
  337. /// call of OnReadDone or OnDone.
  338. ///
  339. /// \param[in] ok Was the initial metadata read successfully? If false, no
  340. /// new read/write operation will succeed, and any further
  341. /// Start* operations should not be called.
  342. virtual void OnReadInitialMetadataDone(bool /*ok*/)
  343. {
  344. }
  345. /// Notifies the application that a StartRead operation completed.
  346. ///
  347. /// \param[in] ok Was it successful? If false, no new read/write operation
  348. /// will succeed, and any further Start* should not be called.
  349. virtual void OnReadDone(bool /*ok*/)
  350. {
  351. }
  352. /// Notifies the application that a StartWrite or StartWriteLast operation
  353. /// completed.
  354. ///
  355. /// \param[in] ok Was it successful? If false, no new read/write operation
  356. /// will succeed, and any further Start* should not be called.
  357. virtual void OnWriteDone(bool /*ok*/)
  358. {
  359. }
  360. /// Notifies the application that a StartWritesDone operation completed. Note
  361. /// that this is only used on explicit StartWritesDone operations and not for
  362. /// those that are implicitly invoked as part of a StartWriteLast.
  363. ///
  364. /// \param[in] ok Was it successful? If false, the application will later see
  365. /// the failure reflected as a bad status in OnDone and no
  366. /// further Start* should be called.
  367. virtual void OnWritesDoneDone(bool /*ok*/)
  368. {
  369. }
  370. private:
  371. friend class ClientCallbackReaderWriter<Request, Response>;
  372. void BindStream(ClientCallbackReaderWriter<Request, Response>* stream)
  373. {
  374. stream_ = stream;
  375. }
  376. ClientCallbackReaderWriter<Request, Response>* stream_;
  377. };
  378. /// \a ClientReadReactor is the interface for a server-streaming RPC.
  379. /// All public methods behave as in ClientBidiReactor.
  380. template<class Response>
  381. class ClientReadReactor : public internal::ClientReactor
  382. {
  383. public:
  384. void StartCall()
  385. {
  386. reader_->StartCall();
  387. }
  388. void StartRead(Response* resp)
  389. {
  390. reader_->Read(resp);
  391. }
  392. void AddHold()
  393. {
  394. AddMultipleHolds(1);
  395. }
  396. void AddMultipleHolds(int holds)
  397. {
  398. GPR_CODEGEN_DEBUG_ASSERT(holds > 0);
  399. reader_->AddHold(holds);
  400. }
  401. void RemoveHold()
  402. {
  403. reader_->RemoveHold();
  404. }
  405. void OnDone(const grpc::Status& /*s*/) override
  406. {
  407. }
  408. virtual void OnReadInitialMetadataDone(bool /*ok*/)
  409. {
  410. }
  411. virtual void OnReadDone(bool /*ok*/)
  412. {
  413. }
  414. private:
  415. friend class ClientCallbackReader<Response>;
  416. void BindReader(ClientCallbackReader<Response>* reader)
  417. {
  418. reader_ = reader;
  419. }
  420. ClientCallbackReader<Response>* reader_;
  421. };
  422. /// \a ClientWriteReactor is the interface for a client-streaming RPC.
  423. /// All public methods behave as in ClientBidiReactor.
  424. template<class Request>
  425. class ClientWriteReactor : public internal::ClientReactor
  426. {
  427. public:
  428. void StartCall()
  429. {
  430. writer_->StartCall();
  431. }
  432. void StartWrite(const Request* req)
  433. {
  434. StartWrite(req, grpc::WriteOptions());
  435. }
  436. void StartWrite(const Request* req, grpc::WriteOptions options)
  437. {
  438. writer_->Write(req, options);
  439. }
  440. void StartWriteLast(const Request* req, grpc::WriteOptions options)
  441. {
  442. StartWrite(req, options.set_last_message());
  443. }
  444. void StartWritesDone()
  445. {
  446. writer_->WritesDone();
  447. }
  448. void AddHold()
  449. {
  450. AddMultipleHolds(1);
  451. }
  452. void AddMultipleHolds(int holds)
  453. {
  454. GPR_CODEGEN_DEBUG_ASSERT(holds > 0);
  455. writer_->AddHold(holds);
  456. }
  457. void RemoveHold()
  458. {
  459. writer_->RemoveHold();
  460. }
  461. void OnDone(const grpc::Status& /*s*/) override
  462. {
  463. }
  464. virtual void OnReadInitialMetadataDone(bool /*ok*/)
  465. {
  466. }
  467. virtual void OnWriteDone(bool /*ok*/)
  468. {
  469. }
  470. virtual void OnWritesDoneDone(bool /*ok*/)
  471. {
  472. }
  473. private:
  474. friend class ClientCallbackWriter<Request>;
  475. void BindWriter(ClientCallbackWriter<Request>* writer)
  476. {
  477. writer_ = writer;
  478. }
  479. ClientCallbackWriter<Request>* writer_;
  480. };
  481. /// \a ClientUnaryReactor is a reactor-style interface for a unary RPC.
  482. /// This is _not_ a common way of invoking a unary RPC. In practice, this
  483. /// option should be used only if the unary RPC wants to receive initial
  484. /// metadata without waiting for the response to complete. Most deployments of
  485. /// RPC systems do not use this option, but it is needed for generality.
  486. /// All public methods behave as in ClientBidiReactor.
  487. /// StartCall is included for consistency with the other reactor flavors: even
  488. /// though there are no StartRead or StartWrite operations to queue before the
  489. /// call (that is part of the unary call itself) and there is no reactor object
  490. /// being created as a result of this call, we keep a consistent 2-phase
  491. /// initiation API among all the reactor flavors.
  492. class ClientUnaryReactor : public internal::ClientReactor
  493. {
  494. public:
  495. void StartCall()
  496. {
  497. call_->StartCall();
  498. }
  499. void OnDone(const grpc::Status& /*s*/) override
  500. {
  501. }
  502. virtual void OnReadInitialMetadataDone(bool /*ok*/)
  503. {
  504. }
  505. private:
  506. friend class ClientCallbackUnary;
  507. void BindCall(ClientCallbackUnary* call)
  508. {
  509. call_ = call;
  510. }
  511. ClientCallbackUnary* call_;
  512. };
  513. // Define function out-of-line from class to avoid forward declaration issue
  514. inline void ClientCallbackUnary::BindReactor(ClientUnaryReactor* reactor)
  515. {
  516. reactor->BindCall(this);
  517. }
  518. namespace internal
  519. {
  520. // Forward declare factory classes for friendship
  521. template<class Request, class Response>
  522. class ClientCallbackReaderWriterFactory;
  523. template<class Response>
  524. class ClientCallbackReaderFactory;
  525. template<class Request>
  526. class ClientCallbackWriterFactory;
  527. template<class Request, class Response>
  528. class ClientCallbackReaderWriterImpl : public ClientCallbackReaderWriter<Request, Response>
  529. {
  530. public:
  531. // always allocated against a call arena, no memory free required
  532. static void operator delete(void* /*ptr*/, std::size_t size)
  533. {
  534. GPR_CODEGEN_ASSERT(size == sizeof(ClientCallbackReaderWriterImpl));
  535. }
  536. // This operator should never be called as the memory should be freed as part
  537. // of the arena destruction. It only exists to provide a matching operator
  538. // delete to the operator new so that some compilers will not complain (see
  539. // https://github.com/grpc/grpc/issues/11301) Note at the time of adding this
  540. // there are no tests catching the compiler warning.
  541. static void operator delete(void*, void*)
  542. {
  543. GPR_CODEGEN_ASSERT(false);
  544. }
  545. void StartCall() ABSL_LOCKS_EXCLUDED(start_mu_) override
  546. {
  547. // This call initiates two batches, plus any backlog, each with a callback
  548. // 1. Send initial metadata (unless corked) + recv initial metadata
  549. // 2. Any read backlog
  550. // 3. Any write backlog
  551. // 4. Recv trailing metadata (unless corked)
  552. if (!start_corked_)
  553. {
  554. start_ops_.SendInitialMetadata(&context_->send_initial_metadata_, context_->initial_metadata_flags());
  555. }
  556. call_.PerformOps(&start_ops_);
  557. {
  558. grpc::internal::MutexLock lock(&start_mu_);
  559. if (backlog_.read_ops)
  560. {
  561. call_.PerformOps(&read_ops_);
  562. }
  563. if (backlog_.write_ops)
  564. {
  565. call_.PerformOps(&write_ops_);
  566. }
  567. if (backlog_.writes_done_ops)
  568. {
  569. call_.PerformOps(&writes_done_ops_);
  570. }
  571. call_.PerformOps(&finish_ops_);
  572. // The last thing in this critical section is to set started_ so that it
  573. // can be used lock-free as well.
  574. started_.store(true, std::memory_order_release);
  575. }
  576. // MaybeFinish outside the lock to make sure that destruction of this object
  577. // doesn't take place while holding the lock (which would cause the lock to
  578. // be released after destruction)
  579. this->MaybeFinish(/*from_reaction=*/false);
  580. }
  581. void Read(Response* msg) override
  582. {
  583. read_ops_.RecvMessage(msg);
  584. callbacks_outstanding_.fetch_add(1, std::memory_order_relaxed);
  585. if (GPR_UNLIKELY(!started_.load(std::memory_order_acquire)))
  586. {
  587. grpc::internal::MutexLock lock(&start_mu_);
  588. if (GPR_LIKELY(!started_.load(std::memory_order_relaxed)))
  589. {
  590. backlog_.read_ops = true;
  591. return;
  592. }
  593. }
  594. call_.PerformOps(&read_ops_);
  595. }
  596. void Write(const Request* msg, grpc::WriteOptions options)
  597. ABSL_LOCKS_EXCLUDED(start_mu_) override
  598. {
  599. if (options.is_last_message())
  600. {
  601. options.set_buffer_hint();
  602. write_ops_.ClientSendClose();
  603. }
  604. // TODO(vjpai): don't assert
  605. GPR_CODEGEN_ASSERT(write_ops_.SendMessagePtr(msg, options).ok());
  606. callbacks_outstanding_.fetch_add(1, std::memory_order_relaxed);
  607. if (GPR_UNLIKELY(corked_write_needed_))
  608. {
  609. write_ops_.SendInitialMetadata(&context_->send_initial_metadata_, context_->initial_metadata_flags());
  610. corked_write_needed_ = false;
  611. }
  612. if (GPR_UNLIKELY(!started_.load(std::memory_order_acquire)))
  613. {
  614. grpc::internal::MutexLock lock(&start_mu_);
  615. if (GPR_LIKELY(!started_.load(std::memory_order_relaxed)))
  616. {
  617. backlog_.write_ops = true;
  618. return;
  619. }
  620. }
  621. call_.PerformOps(&write_ops_);
  622. }
  623. void WritesDone() ABSL_LOCKS_EXCLUDED(start_mu_) override
  624. {
  625. writes_done_ops_.ClientSendClose();
  626. writes_done_tag_.Set(
  627. call_.call(),
  628. [this](bool ok)
  629. {
  630. reactor_->OnWritesDoneDone(ok);
  631. MaybeFinish(/*from_reaction=*/true);
  632. },
  633. &writes_done_ops_,
  634. /*can_inline=*/false
  635. );
  636. writes_done_ops_.set_core_cq_tag(&writes_done_tag_);
  637. callbacks_outstanding_.fetch_add(1, std::memory_order_relaxed);
  638. if (GPR_UNLIKELY(corked_write_needed_))
  639. {
  640. writes_done_ops_.SendInitialMetadata(&context_->send_initial_metadata_, context_->initial_metadata_flags());
  641. corked_write_needed_ = false;
  642. }
  643. if (GPR_UNLIKELY(!started_.load(std::memory_order_acquire)))
  644. {
  645. grpc::internal::MutexLock lock(&start_mu_);
  646. if (GPR_LIKELY(!started_.load(std::memory_order_relaxed)))
  647. {
  648. backlog_.writes_done_ops = true;
  649. return;
  650. }
  651. }
  652. call_.PerformOps(&writes_done_ops_);
  653. }
  654. void AddHold(int holds) override
  655. {
  656. callbacks_outstanding_.fetch_add(holds, std::memory_order_relaxed);
  657. }
  658. void RemoveHold() override
  659. {
  660. MaybeFinish(/*from_reaction=*/false);
  661. }
  662. private:
  663. friend class ClientCallbackReaderWriterFactory<Request, Response>;
  664. ClientCallbackReaderWriterImpl(grpc::internal::Call call, grpc::ClientContext* context, ClientBidiReactor<Request, Response>* reactor) :
  665. context_(context),
  666. call_(call),
  667. reactor_(reactor),
  668. start_corked_(context_->initial_metadata_corked_),
  669. corked_write_needed_(start_corked_)
  670. {
  671. this->BindReactor(reactor);
  672. // Set up the unchanging parts of the start, read, and write tags and ops.
  673. start_tag_.Set(
  674. call_.call(),
  675. [this](bool ok)
  676. {
  677. reactor_->OnReadInitialMetadataDone(
  678. ok && !reactor_->InternalTrailersOnly(call_.call())
  679. );
  680. MaybeFinish(/*from_reaction=*/true);
  681. },
  682. &start_ops_,
  683. /*can_inline=*/false
  684. );
  685. start_ops_.RecvInitialMetadata(context_);
  686. start_ops_.set_core_cq_tag(&start_tag_);
  687. write_tag_.Set(
  688. call_.call(),
  689. [this](bool ok)
  690. {
  691. reactor_->OnWriteDone(ok);
  692. MaybeFinish(/*from_reaction=*/true);
  693. },
  694. &write_ops_,
  695. /*can_inline=*/false
  696. );
  697. write_ops_.set_core_cq_tag(&write_tag_);
  698. read_tag_.Set(
  699. call_.call(),
  700. [this](bool ok)
  701. {
  702. reactor_->OnReadDone(ok);
  703. MaybeFinish(/*from_reaction=*/true);
  704. },
  705. &read_ops_,
  706. /*can_inline=*/false
  707. );
  708. read_ops_.set_core_cq_tag(&read_tag_);
  709. // Also set up the Finish tag and op set.
  710. finish_tag_.Set(
  711. call_.call(),
  712. [this](bool /*ok*/)
  713. { MaybeFinish(/*from_reaction=*/true); },
  714. &finish_ops_,
  715. /*can_inline=*/false
  716. );
  717. finish_ops_.ClientRecvStatus(context_, &finish_status_);
  718. finish_ops_.set_core_cq_tag(&finish_tag_);
  719. }
  720. // MaybeFinish can be called from reactions or from user-initiated operations
  721. // like StartCall or RemoveHold. If this is the last operation or hold on this
  722. // object, it will invoke the OnDone reaction. If MaybeFinish was called from
  723. // a reaction, it can call OnDone directly. If not, it would need to schedule
  724. // OnDone onto an executor thread to avoid the possibility of deadlocking with
  725. // any locks in the user code that invoked it.
  726. void MaybeFinish(bool from_reaction)
  727. {
  728. if (GPR_UNLIKELY(callbacks_outstanding_.fetch_sub(1, std::memory_order_acq_rel) == 1))
  729. {
  730. grpc::Status s = std::move(finish_status_);
  731. auto* reactor = reactor_;
  732. auto* call = call_.call();
  733. this->~ClientCallbackReaderWriterImpl();
  734. grpc::g_core_codegen_interface->grpc_call_unref(call);
  735. if (GPR_LIKELY(from_reaction))
  736. {
  737. reactor->OnDone(s);
  738. }
  739. else
  740. {
  741. reactor->InternalScheduleOnDone(std::move(s));
  742. }
  743. }
  744. }
  745. grpc::ClientContext* const context_;
  746. grpc::internal::Call call_;
  747. ClientBidiReactor<Request, Response>* const reactor_;
  748. grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata, grpc::internal::CallOpRecvInitialMetadata>
  749. start_ops_;
  750. grpc::internal::CallbackWithSuccessTag start_tag_;
  751. const bool start_corked_;
  752. bool corked_write_needed_; // no lock needed since only accessed in
  753. // Write/WritesDone which cannot be concurrent
  754. grpc::internal::CallOpSet<grpc::internal::CallOpClientRecvStatus> finish_ops_;
  755. grpc::internal::CallbackWithSuccessTag finish_tag_;
  756. grpc::Status finish_status_;
  757. grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata, grpc::internal::CallOpSendMessage, grpc::internal::CallOpClientSendClose>
  758. write_ops_;
  759. grpc::internal::CallbackWithSuccessTag write_tag_;
  760. grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata, grpc::internal::CallOpClientSendClose>
  761. writes_done_ops_;
  762. grpc::internal::CallbackWithSuccessTag writes_done_tag_;
  763. grpc::internal::CallOpSet<grpc::internal::CallOpRecvMessage<Response>>
  764. read_ops_;
  765. grpc::internal::CallbackWithSuccessTag read_tag_;
  766. struct StartCallBacklog
  767. {
  768. bool write_ops = false;
  769. bool writes_done_ops = false;
  770. bool read_ops = false;
  771. };
  772. StartCallBacklog backlog_ ABSL_GUARDED_BY(start_mu_);
  773. // Minimum of 3 callbacks to pre-register for start ops, StartCall, and finish
  774. std::atomic<intptr_t> callbacks_outstanding_{3};
  775. std::atomic_bool started_{false};
  776. grpc::internal::Mutex start_mu_;
  777. };
  778. template<class Request, class Response>
  779. class ClientCallbackReaderWriterFactory
  780. {
  781. public:
  782. static void Create(grpc::ChannelInterface* channel, const grpc::internal::RpcMethod& method, grpc::ClientContext* context, ClientBidiReactor<Request, Response>* reactor)
  783. {
  784. grpc::internal::Call call =
  785. channel->CreateCall(method, context, channel->CallbackCQ());
  786. grpc::g_core_codegen_interface->grpc_call_ref(call.call());
  787. new (grpc::g_core_codegen_interface->grpc_call_arena_alloc(
  788. call.call(), sizeof(ClientCallbackReaderWriterImpl<Request, Response>)
  789. ))
  790. ClientCallbackReaderWriterImpl<Request, Response>(call, context, reactor);
  791. }
  792. };
  793. template<class Response>
  794. class ClientCallbackReaderImpl : public ClientCallbackReader<Response>
  795. {
  796. public:
  797. // always allocated against a call arena, no memory free required
  798. static void operator delete(void* /*ptr*/, std::size_t size)
  799. {
  800. GPR_CODEGEN_ASSERT(size == sizeof(ClientCallbackReaderImpl));
  801. }
  802. // This operator should never be called as the memory should be freed as part
  803. // of the arena destruction. It only exists to provide a matching operator
  804. // delete to the operator new so that some compilers will not complain (see
  805. // https://github.com/grpc/grpc/issues/11301) Note at the time of adding this
  806. // there are no tests catching the compiler warning.
  807. static void operator delete(void*, void*)
  808. {
  809. GPR_CODEGEN_ASSERT(false);
  810. }
  811. void StartCall() override
  812. {
  813. // This call initiates two batches, plus any backlog, each with a callback
  814. // 1. Send initial metadata (unless corked) + recv initial metadata
  815. // 2. Any backlog
  816. // 3. Recv trailing metadata
  817. start_tag_.Set(
  818. call_.call(),
  819. [this](bool ok)
  820. {
  821. reactor_->OnReadInitialMetadataDone(
  822. ok && !reactor_->InternalTrailersOnly(call_.call())
  823. );
  824. MaybeFinish(/*from_reaction=*/true);
  825. },
  826. &start_ops_,
  827. /*can_inline=*/false
  828. );
  829. start_ops_.SendInitialMetadata(&context_->send_initial_metadata_, context_->initial_metadata_flags());
  830. start_ops_.RecvInitialMetadata(context_);
  831. start_ops_.set_core_cq_tag(&start_tag_);
  832. call_.PerformOps(&start_ops_);
  833. // Also set up the read tag so it doesn't have to be set up each time
  834. read_tag_.Set(
  835. call_.call(),
  836. [this](bool ok)
  837. {
  838. reactor_->OnReadDone(ok);
  839. MaybeFinish(/*from_reaction=*/true);
  840. },
  841. &read_ops_,
  842. /*can_inline=*/false
  843. );
  844. read_ops_.set_core_cq_tag(&read_tag_);
  845. {
  846. grpc::internal::MutexLock lock(&start_mu_);
  847. if (backlog_.read_ops)
  848. {
  849. call_.PerformOps(&read_ops_);
  850. }
  851. started_.store(true, std::memory_order_release);
  852. }
  853. finish_tag_.Set(
  854. call_.call(),
  855. [this](bool /*ok*/)
  856. { MaybeFinish(/*from_reaction=*/true); },
  857. &finish_ops_,
  858. /*can_inline=*/false
  859. );
  860. finish_ops_.ClientRecvStatus(context_, &finish_status_);
  861. finish_ops_.set_core_cq_tag(&finish_tag_);
  862. call_.PerformOps(&finish_ops_);
  863. }
  864. void Read(Response* msg) override
  865. {
  866. read_ops_.RecvMessage(msg);
  867. callbacks_outstanding_.fetch_add(1, std::memory_order_relaxed);
  868. if (GPR_UNLIKELY(!started_.load(std::memory_order_acquire)))
  869. {
  870. grpc::internal::MutexLock lock(&start_mu_);
  871. if (GPR_LIKELY(!started_.load(std::memory_order_relaxed)))
  872. {
  873. backlog_.read_ops = true;
  874. return;
  875. }
  876. }
  877. call_.PerformOps(&read_ops_);
  878. }
  879. void AddHold(int holds) override
  880. {
  881. callbacks_outstanding_.fetch_add(holds, std::memory_order_relaxed);
  882. }
  883. void RemoveHold() override
  884. {
  885. MaybeFinish(/*from_reaction=*/false);
  886. }
  887. private:
  888. friend class ClientCallbackReaderFactory<Response>;
  889. template<class Request>
  890. ClientCallbackReaderImpl(grpc::internal::Call call, grpc::ClientContext* context, Request* request, ClientReadReactor<Response>* reactor) :
  891. context_(context),
  892. call_(call),
  893. reactor_(reactor)
  894. {
  895. this->BindReactor(reactor);
  896. // TODO(vjpai): don't assert
  897. GPR_CODEGEN_ASSERT(start_ops_.SendMessagePtr(request).ok());
  898. start_ops_.ClientSendClose();
  899. }
  900. // MaybeFinish behaves as in ClientCallbackReaderWriterImpl.
  901. void MaybeFinish(bool from_reaction)
  902. {
  903. if (GPR_UNLIKELY(callbacks_outstanding_.fetch_sub(1, std::memory_order_acq_rel) == 1))
  904. {
  905. grpc::Status s = std::move(finish_status_);
  906. auto* reactor = reactor_;
  907. auto* call = call_.call();
  908. this->~ClientCallbackReaderImpl();
  909. grpc::g_core_codegen_interface->grpc_call_unref(call);
  910. if (GPR_LIKELY(from_reaction))
  911. {
  912. reactor->OnDone(s);
  913. }
  914. else
  915. {
  916. reactor->InternalScheduleOnDone(std::move(s));
  917. }
  918. }
  919. }
  920. grpc::ClientContext* const context_;
  921. grpc::internal::Call call_;
  922. ClientReadReactor<Response>* const reactor_;
  923. grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata, grpc::internal::CallOpSendMessage, grpc::internal::CallOpClientSendClose, grpc::internal::CallOpRecvInitialMetadata>
  924. start_ops_;
  925. grpc::internal::CallbackWithSuccessTag start_tag_;
  926. grpc::internal::CallOpSet<grpc::internal::CallOpClientRecvStatus> finish_ops_;
  927. grpc::internal::CallbackWithSuccessTag finish_tag_;
  928. grpc::Status finish_status_;
  929. grpc::internal::CallOpSet<grpc::internal::CallOpRecvMessage<Response>>
  930. read_ops_;
  931. grpc::internal::CallbackWithSuccessTag read_tag_;
  932. struct StartCallBacklog
  933. {
  934. bool read_ops = false;
  935. };
  936. StartCallBacklog backlog_ ABSL_GUARDED_BY(start_mu_);
  937. // Minimum of 2 callbacks to pre-register for start and finish
  938. std::atomic<intptr_t> callbacks_outstanding_{2};
  939. std::atomic_bool started_{false};
  940. grpc::internal::Mutex start_mu_;
  941. };
  942. template<class Response>
  943. class ClientCallbackReaderFactory
  944. {
  945. public:
  946. template<class Request>
  947. static void Create(grpc::ChannelInterface* channel, const grpc::internal::RpcMethod& method, grpc::ClientContext* context, const Request* request, ClientReadReactor<Response>* reactor)
  948. {
  949. grpc::internal::Call call =
  950. channel->CreateCall(method, context, channel->CallbackCQ());
  951. grpc::g_core_codegen_interface->grpc_call_ref(call.call());
  952. new (grpc::g_core_codegen_interface->grpc_call_arena_alloc(
  953. call.call(), sizeof(ClientCallbackReaderImpl<Response>)
  954. ))
  955. ClientCallbackReaderImpl<Response>(call, context, request, reactor);
  956. }
  957. };
  958. template<class Request>
  959. class ClientCallbackWriterImpl : public ClientCallbackWriter<Request>
  960. {
  961. public:
  962. // always allocated against a call arena, no memory free required
  963. static void operator delete(void* /*ptr*/, std::size_t size)
  964. {
  965. GPR_CODEGEN_ASSERT(size == sizeof(ClientCallbackWriterImpl));
  966. }
  967. // This operator should never be called as the memory should be freed as part
  968. // of the arena destruction. It only exists to provide a matching operator
  969. // delete to the operator new so that some compilers will not complain (see
  970. // https://github.com/grpc/grpc/issues/11301) Note at the time of adding this
  971. // there are no tests catching the compiler warning.
  972. static void operator delete(void*, void*)
  973. {
  974. GPR_CODEGEN_ASSERT(false);
  975. }
  976. void StartCall() ABSL_LOCKS_EXCLUDED(start_mu_) override
  977. {
  978. // This call initiates two batches, plus any backlog, each with a callback
  979. // 1. Send initial metadata (unless corked) + recv initial metadata
  980. // 2. Any backlog
  981. // 3. Recv trailing metadata
  982. if (!start_corked_)
  983. {
  984. start_ops_.SendInitialMetadata(&context_->send_initial_metadata_, context_->initial_metadata_flags());
  985. }
  986. call_.PerformOps(&start_ops_);
  987. {
  988. grpc::internal::MutexLock lock(&start_mu_);
  989. if (backlog_.write_ops)
  990. {
  991. call_.PerformOps(&write_ops_);
  992. }
  993. if (backlog_.writes_done_ops)
  994. {
  995. call_.PerformOps(&writes_done_ops_);
  996. }
  997. call_.PerformOps(&finish_ops_);
  998. // The last thing in this critical section is to set started_ so that it
  999. // can be used lock-free as well.
  1000. started_.store(true, std::memory_order_release);
  1001. }
  1002. // MaybeFinish outside the lock to make sure that destruction of this object
  1003. // doesn't take place while holding the lock (which would cause the lock to
  1004. // be released after destruction)
  1005. this->MaybeFinish(/*from_reaction=*/false);
  1006. }
  1007. void Write(const Request* msg, grpc::WriteOptions options)
  1008. ABSL_LOCKS_EXCLUDED(start_mu_) override
  1009. {
  1010. if (GPR_UNLIKELY(options.is_last_message()))
  1011. {
  1012. options.set_buffer_hint();
  1013. write_ops_.ClientSendClose();
  1014. }
  1015. // TODO(vjpai): don't assert
  1016. GPR_CODEGEN_ASSERT(write_ops_.SendMessagePtr(msg, options).ok());
  1017. callbacks_outstanding_.fetch_add(1, std::memory_order_relaxed);
  1018. if (GPR_UNLIKELY(corked_write_needed_))
  1019. {
  1020. write_ops_.SendInitialMetadata(&context_->send_initial_metadata_, context_->initial_metadata_flags());
  1021. corked_write_needed_ = false;
  1022. }
  1023. if (GPR_UNLIKELY(!started_.load(std::memory_order_acquire)))
  1024. {
  1025. grpc::internal::MutexLock lock(&start_mu_);
  1026. if (GPR_LIKELY(!started_.load(std::memory_order_relaxed)))
  1027. {
  1028. backlog_.write_ops = true;
  1029. return;
  1030. }
  1031. }
  1032. call_.PerformOps(&write_ops_);
  1033. }
  1034. void WritesDone() ABSL_LOCKS_EXCLUDED(start_mu_) override
  1035. {
  1036. writes_done_ops_.ClientSendClose();
  1037. writes_done_tag_.Set(
  1038. call_.call(),
  1039. [this](bool ok)
  1040. {
  1041. reactor_->OnWritesDoneDone(ok);
  1042. MaybeFinish(/*from_reaction=*/true);
  1043. },
  1044. &writes_done_ops_,
  1045. /*can_inline=*/false
  1046. );
  1047. writes_done_ops_.set_core_cq_tag(&writes_done_tag_);
  1048. callbacks_outstanding_.fetch_add(1, std::memory_order_relaxed);
  1049. if (GPR_UNLIKELY(corked_write_needed_))
  1050. {
  1051. writes_done_ops_.SendInitialMetadata(&context_->send_initial_metadata_, context_->initial_metadata_flags());
  1052. corked_write_needed_ = false;
  1053. }
  1054. if (GPR_UNLIKELY(!started_.load(std::memory_order_acquire)))
  1055. {
  1056. grpc::internal::MutexLock lock(&start_mu_);
  1057. if (GPR_LIKELY(!started_.load(std::memory_order_relaxed)))
  1058. {
  1059. backlog_.writes_done_ops = true;
  1060. return;
  1061. }
  1062. }
  1063. call_.PerformOps(&writes_done_ops_);
  1064. }
  1065. void AddHold(int holds) override
  1066. {
  1067. callbacks_outstanding_.fetch_add(holds, std::memory_order_relaxed);
  1068. }
  1069. void RemoveHold() override
  1070. {
  1071. MaybeFinish(/*from_reaction=*/false);
  1072. }
  1073. private:
  1074. friend class ClientCallbackWriterFactory<Request>;
  1075. template<class Response>
  1076. ClientCallbackWriterImpl(grpc::internal::Call call, grpc::ClientContext* context, Response* response, ClientWriteReactor<Request>* reactor) :
  1077. context_(context),
  1078. call_(call),
  1079. reactor_(reactor),
  1080. start_corked_(context_->initial_metadata_corked_),
  1081. corked_write_needed_(start_corked_)
  1082. {
  1083. this->BindReactor(reactor);
  1084. // Set up the unchanging parts of the start and write tags and ops.
  1085. start_tag_.Set(
  1086. call_.call(),
  1087. [this](bool ok)
  1088. {
  1089. reactor_->OnReadInitialMetadataDone(
  1090. ok && !reactor_->InternalTrailersOnly(call_.call())
  1091. );
  1092. MaybeFinish(/*from_reaction=*/true);
  1093. },
  1094. &start_ops_,
  1095. /*can_inline=*/false
  1096. );
  1097. start_ops_.RecvInitialMetadata(context_);
  1098. start_ops_.set_core_cq_tag(&start_tag_);
  1099. write_tag_.Set(
  1100. call_.call(),
  1101. [this](bool ok)
  1102. {
  1103. reactor_->OnWriteDone(ok);
  1104. MaybeFinish(/*from_reaction=*/true);
  1105. },
  1106. &write_ops_,
  1107. /*can_inline=*/false
  1108. );
  1109. write_ops_.set_core_cq_tag(&write_tag_);
  1110. // Also set up the Finish tag and op set.
  1111. finish_ops_.RecvMessage(response);
  1112. finish_ops_.AllowNoMessage();
  1113. finish_tag_.Set(
  1114. call_.call(),
  1115. [this](bool /*ok*/)
  1116. { MaybeFinish(/*from_reaction=*/true); },
  1117. &finish_ops_,
  1118. /*can_inline=*/false
  1119. );
  1120. finish_ops_.ClientRecvStatus(context_, &finish_status_);
  1121. finish_ops_.set_core_cq_tag(&finish_tag_);
  1122. }
  1123. // MaybeFinish behaves as in ClientCallbackReaderWriterImpl.
  1124. void MaybeFinish(bool from_reaction)
  1125. {
  1126. if (GPR_UNLIKELY(callbacks_outstanding_.fetch_sub(1, std::memory_order_acq_rel) == 1))
  1127. {
  1128. grpc::Status s = std::move(finish_status_);
  1129. auto* reactor = reactor_;
  1130. auto* call = call_.call();
  1131. this->~ClientCallbackWriterImpl();
  1132. grpc::g_core_codegen_interface->grpc_call_unref(call);
  1133. if (GPR_LIKELY(from_reaction))
  1134. {
  1135. reactor->OnDone(s);
  1136. }
  1137. else
  1138. {
  1139. reactor->InternalScheduleOnDone(std::move(s));
  1140. }
  1141. }
  1142. }
  1143. grpc::ClientContext* const context_;
  1144. grpc::internal::Call call_;
  1145. ClientWriteReactor<Request>* const reactor_;
  1146. grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata, grpc::internal::CallOpRecvInitialMetadata>
  1147. start_ops_;
  1148. grpc::internal::CallbackWithSuccessTag start_tag_;
  1149. const bool start_corked_;
  1150. bool corked_write_needed_; // no lock needed since only accessed in
  1151. // Write/WritesDone which cannot be concurrent
  1152. grpc::internal::CallOpSet<grpc::internal::CallOpGenericRecvMessage, grpc::internal::CallOpClientRecvStatus>
  1153. finish_ops_;
  1154. grpc::internal::CallbackWithSuccessTag finish_tag_;
  1155. grpc::Status finish_status_;
  1156. grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata, grpc::internal::CallOpSendMessage, grpc::internal::CallOpClientSendClose>
  1157. write_ops_;
  1158. grpc::internal::CallbackWithSuccessTag write_tag_;
  1159. grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata, grpc::internal::CallOpClientSendClose>
  1160. writes_done_ops_;
  1161. grpc::internal::CallbackWithSuccessTag writes_done_tag_;
  1162. struct StartCallBacklog
  1163. {
  1164. bool write_ops = false;
  1165. bool writes_done_ops = false;
  1166. };
  1167. StartCallBacklog backlog_ ABSL_GUARDED_BY(start_mu_);
  1168. // Minimum of 3 callbacks to pre-register for start ops, StartCall, and finish
  1169. std::atomic<intptr_t> callbacks_outstanding_{3};
  1170. std::atomic_bool started_{false};
  1171. grpc::internal::Mutex start_mu_;
  1172. };
  1173. template<class Request>
  1174. class ClientCallbackWriterFactory
  1175. {
  1176. public:
  1177. template<class Response>
  1178. static void Create(grpc::ChannelInterface* channel, const grpc::internal::RpcMethod& method, grpc::ClientContext* context, Response* response, ClientWriteReactor<Request>* reactor)
  1179. {
  1180. grpc::internal::Call call =
  1181. channel->CreateCall(method, context, channel->CallbackCQ());
  1182. grpc::g_core_codegen_interface->grpc_call_ref(call.call());
  1183. new (grpc::g_core_codegen_interface->grpc_call_arena_alloc(
  1184. call.call(), sizeof(ClientCallbackWriterImpl<Request>)
  1185. ))
  1186. ClientCallbackWriterImpl<Request>(call, context, response, reactor);
  1187. }
  1188. };
  1189. class ClientCallbackUnaryImpl final : public ClientCallbackUnary
  1190. {
  1191. public:
  1192. // always allocated against a call arena, no memory free required
  1193. static void operator delete(void* /*ptr*/, std::size_t size)
  1194. {
  1195. GPR_CODEGEN_ASSERT(size == sizeof(ClientCallbackUnaryImpl));
  1196. }
  1197. // This operator should never be called as the memory should be freed as part
  1198. // of the arena destruction. It only exists to provide a matching operator
  1199. // delete to the operator new so that some compilers will not complain (see
  1200. // https://github.com/grpc/grpc/issues/11301) Note at the time of adding this
  1201. // there are no tests catching the compiler warning.
  1202. static void operator delete(void*, void*)
  1203. {
  1204. GPR_CODEGEN_ASSERT(false);
  1205. }
  1206. void StartCall() override
  1207. {
  1208. // This call initiates two batches, each with a callback
  1209. // 1. Send initial metadata + write + writes done + recv initial metadata
  1210. // 2. Read message, recv trailing metadata
  1211. start_tag_.Set(
  1212. call_.call(),
  1213. [this](bool ok)
  1214. {
  1215. reactor_->OnReadInitialMetadataDone(
  1216. ok && !reactor_->InternalTrailersOnly(call_.call())
  1217. );
  1218. MaybeFinish();
  1219. },
  1220. &start_ops_,
  1221. /*can_inline=*/false
  1222. );
  1223. start_ops_.SendInitialMetadata(&context_->send_initial_metadata_, context_->initial_metadata_flags());
  1224. start_ops_.RecvInitialMetadata(context_);
  1225. start_ops_.set_core_cq_tag(&start_tag_);
  1226. call_.PerformOps(&start_ops_);
  1227. finish_tag_.Set(
  1228. call_.call(), [this](bool /*ok*/)
  1229. { MaybeFinish(); },
  1230. &finish_ops_,
  1231. /*can_inline=*/false
  1232. );
  1233. finish_ops_.ClientRecvStatus(context_, &finish_status_);
  1234. finish_ops_.set_core_cq_tag(&finish_tag_);
  1235. call_.PerformOps(&finish_ops_);
  1236. }
  1237. private:
  1238. friend class ClientCallbackUnaryFactory;
  1239. template<class Request, class Response>
  1240. ClientCallbackUnaryImpl(grpc::internal::Call call, grpc::ClientContext* context, Request* request, Response* response, ClientUnaryReactor* reactor) :
  1241. context_(context),
  1242. call_(call),
  1243. reactor_(reactor)
  1244. {
  1245. this->BindReactor(reactor);
  1246. // TODO(vjpai): don't assert
  1247. GPR_CODEGEN_ASSERT(start_ops_.SendMessagePtr(request).ok());
  1248. start_ops_.ClientSendClose();
  1249. finish_ops_.RecvMessage(response);
  1250. finish_ops_.AllowNoMessage();
  1251. }
  1252. // In the unary case, MaybeFinish is only ever invoked from a
  1253. // library-initiated reaction, so it will just directly call OnDone if this is
  1254. // the last reaction for this RPC.
  1255. void MaybeFinish()
  1256. {
  1257. if (GPR_UNLIKELY(callbacks_outstanding_.fetch_sub(1, std::memory_order_acq_rel) == 1))
  1258. {
  1259. grpc::Status s = std::move(finish_status_);
  1260. auto* reactor = reactor_;
  1261. auto* call = call_.call();
  1262. this->~ClientCallbackUnaryImpl();
  1263. grpc::g_core_codegen_interface->grpc_call_unref(call);
  1264. reactor->OnDone(s);
  1265. }
  1266. }
  1267. grpc::ClientContext* const context_;
  1268. grpc::internal::Call call_;
  1269. ClientUnaryReactor* const reactor_;
  1270. grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata, grpc::internal::CallOpSendMessage, grpc::internal::CallOpClientSendClose, grpc::internal::CallOpRecvInitialMetadata>
  1271. start_ops_;
  1272. grpc::internal::CallbackWithSuccessTag start_tag_;
  1273. grpc::internal::CallOpSet<grpc::internal::CallOpGenericRecvMessage, grpc::internal::CallOpClientRecvStatus>
  1274. finish_ops_;
  1275. grpc::internal::CallbackWithSuccessTag finish_tag_;
  1276. grpc::Status finish_status_;
  1277. // This call will have 2 callbacks: start and finish
  1278. std::atomic<intptr_t> callbacks_outstanding_{2};
  1279. };
  1280. class ClientCallbackUnaryFactory
  1281. {
  1282. public:
  1283. template<class Request, class Response, class BaseRequest = Request, class BaseResponse = Response>
  1284. static void Create(grpc::ChannelInterface* channel, const grpc::internal::RpcMethod& method, grpc::ClientContext* context, const Request* request, Response* response, ClientUnaryReactor* reactor)
  1285. {
  1286. grpc::internal::Call call =
  1287. channel->CreateCall(method, context, channel->CallbackCQ());
  1288. grpc::g_core_codegen_interface->grpc_call_ref(call.call());
  1289. new (grpc::g_core_codegen_interface->grpc_call_arena_alloc(
  1290. call.call(), sizeof(ClientCallbackUnaryImpl)
  1291. ))
  1292. ClientCallbackUnaryImpl(call, context, static_cast<const BaseRequest*>(request), static_cast<BaseResponse*>(response), reactor);
  1293. }
  1294. };
  1295. } // namespace internal
  1296. } // namespace grpc
  1297. #endif // GRPCPP_IMPL_CODEGEN_CLIENT_CALLBACK_H