sync_stream.h 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  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_SYNC_STREAM_H
  18. #define GRPCPP_IMPL_CODEGEN_SYNC_STREAM_H
  19. // IWYU pragma: private, include <grpcpp/support/sync_stream.h>
  20. #include <grpcpp/impl/codegen/call.h>
  21. #include <grpcpp/impl/codegen/channel_interface.h>
  22. #include <grpcpp/impl/codegen/client_context.h>
  23. #include <grpcpp/impl/codegen/completion_queue.h>
  24. #include <grpcpp/impl/codegen/core_codegen_interface.h>
  25. #include <grpcpp/impl/codegen/server_context.h>
  26. #include <grpcpp/impl/codegen/service_type.h>
  27. #include <grpcpp/impl/codegen/status.h>
  28. namespace grpc {
  29. namespace internal {
  30. /// Common interface for all synchronous client side streaming.
  31. class ClientStreamingInterface {
  32. public:
  33. virtual ~ClientStreamingInterface() {}
  34. /// Block waiting until the stream finishes and a final status of the call is
  35. /// available.
  36. ///
  37. /// It is appropriate to call this method exactly once when both:
  38. /// * the calling code (client-side) has no more message to send
  39. /// (this can be declared implicitly by calling this method, or
  40. /// explicitly through an earlier call to <i>WritesDone</i> method of the
  41. /// class in use, e.g. \a ClientWriterInterface::WritesDone or
  42. /// \a ClientReaderWriterInterface::WritesDone).
  43. /// * there are no more messages to be received from the server (which can
  44. /// be known implicitly, or explicitly from an earlier call to \a
  45. /// ReaderInterface::Read that returned "false").
  46. ///
  47. /// This function will return either:
  48. /// - when all incoming messages have been read and the server has
  49. /// returned status.
  50. /// - when the server has returned a non-OK status.
  51. /// - OR when the call failed for some reason and the library generated a
  52. /// status.
  53. ///
  54. /// Return values:
  55. /// - \a Status contains the status code, message and details for the call
  56. /// - the \a ClientContext associated with this call is updated with
  57. /// possible trailing metadata sent from the server.
  58. virtual ::grpc::Status Finish() = 0;
  59. };
  60. /// Common interface for all synchronous server side streaming.
  61. class ServerStreamingInterface {
  62. public:
  63. virtual ~ServerStreamingInterface() {}
  64. /// Block to send initial metadata to client.
  65. /// This call is optional, but if it is used, it cannot be used concurrently
  66. /// with or after the \a Finish method.
  67. ///
  68. /// The initial metadata that will be sent to the client will be
  69. /// taken from the \a ServerContext associated with the call.
  70. virtual void SendInitialMetadata() = 0;
  71. };
  72. /// An interface that yields a sequence of messages of type \a R.
  73. template <class R>
  74. class ReaderInterface {
  75. public:
  76. virtual ~ReaderInterface() {}
  77. /// Get an upper bound on the next message size available for reading on this
  78. /// stream.
  79. virtual bool NextMessageSize(uint32_t* sz) = 0;
  80. /// Block to read a message and parse to \a msg. Returns \a true on success.
  81. /// This is thread-safe with respect to \a Write or \WritesDone methods on
  82. /// the same stream. It should not be called concurrently with another \a
  83. /// Read on the same stream as the order of delivery will not be defined.
  84. ///
  85. /// \param[out] msg The read message.
  86. ///
  87. /// \return \a false when there will be no more incoming messages, either
  88. /// because the other side has called \a WritesDone() or the stream has failed
  89. /// (or been cancelled).
  90. virtual bool Read(R* msg) = 0;
  91. };
  92. /// An interface that can be fed a sequence of messages of type \a W.
  93. template <class W>
  94. class WriterInterface {
  95. public:
  96. virtual ~WriterInterface() {}
  97. /// Block to write \a msg to the stream with WriteOptions \a options.
  98. /// This is thread-safe with respect to \a ReaderInterface::Read
  99. ///
  100. /// \param msg The message to be written to the stream.
  101. /// \param options The WriteOptions affecting the write operation.
  102. ///
  103. /// \return \a true on success, \a false when the stream has been closed.
  104. virtual bool Write(const W& msg, ::grpc::WriteOptions options) = 0;
  105. /// Block to write \a msg to the stream with default write options.
  106. /// This is thread-safe with respect to \a ReaderInterface::Read
  107. ///
  108. /// \param msg The message to be written to the stream.
  109. ///
  110. /// \return \a true on success, \a false when the stream has been closed.
  111. inline bool Write(const W& msg) { return Write(msg, ::grpc::WriteOptions()); }
  112. /// Write \a msg and coalesce it with the writing of trailing metadata, using
  113. /// WriteOptions \a options.
  114. ///
  115. /// For client, WriteLast is equivalent of performing Write and WritesDone in
  116. /// a single step. \a msg and trailing metadata are coalesced and sent on wire
  117. /// by calling this function. For server, WriteLast buffers the \a msg.
  118. /// The writing of \a msg is held until the service handler returns,
  119. /// where \a msg and trailing metadata are coalesced and sent on wire.
  120. /// Note that WriteLast can only buffer \a msg up to the flow control window
  121. /// size. If \a msg size is larger than the window size, it will be sent on
  122. /// wire without buffering.
  123. ///
  124. /// \param[in] msg The message to be written to the stream.
  125. /// \param[in] options The WriteOptions to be used to write this message.
  126. void WriteLast(const W& msg, ::grpc::WriteOptions options) {
  127. Write(msg, options.set_last_message());
  128. }
  129. };
  130. } // namespace internal
  131. /// Client-side interface for streaming reads of message of type \a R.
  132. template <class R>
  133. class ClientReaderInterface : public internal::ClientStreamingInterface,
  134. public internal::ReaderInterface<R> {
  135. public:
  136. /// Block to wait for initial metadata from server. The received metadata
  137. /// can only be accessed after this call returns. Should only be called before
  138. /// the first read. Calling this method is optional, and if it is not called
  139. /// the metadata will be available in ClientContext after the first read.
  140. virtual void WaitForInitialMetadata() = 0;
  141. };
  142. namespace internal {
  143. template <class R>
  144. class ClientReaderFactory {
  145. public:
  146. template <class W>
  147. static ClientReader<R>* Create(::grpc::ChannelInterface* channel,
  148. const ::grpc::internal::RpcMethod& method,
  149. ::grpc::ClientContext* context,
  150. const W& request) {
  151. return new ClientReader<R>(channel, method, context, request);
  152. }
  153. };
  154. } // namespace internal
  155. /// Synchronous (blocking) client-side API for doing server-streaming RPCs,
  156. /// where the stream of messages coming from the server has messages
  157. /// of type \a R.
  158. template <class R>
  159. class ClientReader final : public ClientReaderInterface<R> {
  160. public:
  161. /// See the \a ClientStreamingInterface.WaitForInitialMetadata method for
  162. /// semantics.
  163. ///
  164. // Side effect:
  165. /// Once complete, the initial metadata read from
  166. /// the server will be accessible through the \a ClientContext used to
  167. /// construct this object.
  168. void WaitForInitialMetadata() override {
  169. GPR_CODEGEN_ASSERT(!context_->initial_metadata_received_);
  170. ::grpc::internal::CallOpSet<::grpc::internal::CallOpRecvInitialMetadata>
  171. ops;
  172. ops.RecvInitialMetadata(context_);
  173. call_.PerformOps(&ops);
  174. cq_.Pluck(&ops); /// status ignored
  175. }
  176. bool NextMessageSize(uint32_t* sz) override {
  177. int result = call_.max_receive_message_size();
  178. *sz = (result > 0) ? result : UINT32_MAX;
  179. return true;
  180. }
  181. /// See the \a ReaderInterface.Read method for semantics.
  182. /// Side effect:
  183. /// This also receives initial metadata from the server, if not
  184. /// already received (if initial metadata is received, it can be then
  185. /// accessed through the \a ClientContext associated with this call).
  186. bool Read(R* msg) override {
  187. ::grpc::internal::CallOpSet<::grpc::internal::CallOpRecvInitialMetadata,
  188. ::grpc::internal::CallOpRecvMessage<R>>
  189. ops;
  190. if (!context_->initial_metadata_received_) {
  191. ops.RecvInitialMetadata(context_);
  192. }
  193. ops.RecvMessage(msg);
  194. call_.PerformOps(&ops);
  195. return cq_.Pluck(&ops) && ops.got_message;
  196. }
  197. /// See the \a ClientStreamingInterface.Finish method for semantics.
  198. ///
  199. /// Side effect:
  200. /// The \a ClientContext associated with this call is updated with
  201. /// possible metadata received from the server.
  202. ::grpc::Status Finish() override {
  203. ::grpc::internal::CallOpSet<::grpc::internal::CallOpClientRecvStatus> ops;
  204. ::grpc::Status status;
  205. ops.ClientRecvStatus(context_, &status);
  206. call_.PerformOps(&ops);
  207. GPR_CODEGEN_ASSERT(cq_.Pluck(&ops));
  208. return status;
  209. }
  210. private:
  211. friend class internal::ClientReaderFactory<R>;
  212. ::grpc::ClientContext* context_;
  213. ::grpc::CompletionQueue cq_;
  214. ::grpc::internal::Call call_;
  215. /// Block to create a stream and write the initial metadata and \a request
  216. /// out. Note that \a context will be used to fill in custom initial
  217. /// metadata used to send to the server when starting the call.
  218. template <class W>
  219. ClientReader(::grpc::ChannelInterface* channel,
  220. const ::grpc::internal::RpcMethod& method,
  221. ::grpc::ClientContext* context, const W& request)
  222. : context_(context),
  223. cq_(grpc_completion_queue_attributes{
  224. GRPC_CQ_CURRENT_VERSION, GRPC_CQ_PLUCK, GRPC_CQ_DEFAULT_POLLING,
  225. nullptr}), // Pluckable cq
  226. call_(channel->CreateCall(method, context, &cq_)) {
  227. ::grpc::internal::CallOpSet<::grpc::internal::CallOpSendInitialMetadata,
  228. ::grpc::internal::CallOpSendMessage,
  229. ::grpc::internal::CallOpClientSendClose>
  230. ops;
  231. ops.SendInitialMetadata(&context->send_initial_metadata_,
  232. context->initial_metadata_flags());
  233. // TODO(ctiller): don't assert
  234. GPR_CODEGEN_ASSERT(ops.SendMessagePtr(&request).ok());
  235. ops.ClientSendClose();
  236. call_.PerformOps(&ops);
  237. cq_.Pluck(&ops);
  238. }
  239. };
  240. /// Client-side interface for streaming writes of message type \a W.
  241. template <class W>
  242. class ClientWriterInterface : public internal::ClientStreamingInterface,
  243. public internal::WriterInterface<W> {
  244. public:
  245. /// Half close writing from the client. (signal that the stream of messages
  246. /// coming from the client is complete).
  247. /// Blocks until currently-pending writes are completed.
  248. /// Thread safe with respect to \a ReaderInterface::Read operations only
  249. ///
  250. /// \return Whether the writes were successful.
  251. virtual bool WritesDone() = 0;
  252. };
  253. namespace internal {
  254. template <class W>
  255. class ClientWriterFactory {
  256. public:
  257. template <class R>
  258. static ClientWriter<W>* Create(::grpc::ChannelInterface* channel,
  259. const ::grpc::internal::RpcMethod& method,
  260. ::grpc::ClientContext* context, R* response) {
  261. return new ClientWriter<W>(channel, method, context, response);
  262. }
  263. };
  264. } // namespace internal
  265. /// Synchronous (blocking) client-side API for doing client-streaming RPCs,
  266. /// where the outgoing message stream coming from the client has messages of
  267. /// type \a W.
  268. template <class W>
  269. class ClientWriter : public ClientWriterInterface<W> {
  270. public:
  271. /// See the \a ClientStreamingInterface.WaitForInitialMetadata method for
  272. /// semantics.
  273. ///
  274. // Side effect:
  275. /// Once complete, the initial metadata read from the server will be
  276. /// accessible through the \a ClientContext used to construct this object.
  277. void WaitForInitialMetadata() {
  278. GPR_CODEGEN_ASSERT(!context_->initial_metadata_received_);
  279. ::grpc::internal::CallOpSet<::grpc::internal::CallOpRecvInitialMetadata>
  280. ops;
  281. ops.RecvInitialMetadata(context_);
  282. call_.PerformOps(&ops);
  283. cq_.Pluck(&ops); // status ignored
  284. }
  285. /// See the WriterInterface.Write(const W& msg, WriteOptions options) method
  286. /// for semantics.
  287. ///
  288. /// Side effect:
  289. /// Also sends initial metadata if not already sent (using the
  290. /// \a ClientContext associated with this call).
  291. using internal::WriterInterface<W>::Write;
  292. bool Write(const W& msg, ::grpc::WriteOptions options) override {
  293. ::grpc::internal::CallOpSet<::grpc::internal::CallOpSendInitialMetadata,
  294. ::grpc::internal::CallOpSendMessage,
  295. ::grpc::internal::CallOpClientSendClose>
  296. ops;
  297. if (options.is_last_message()) {
  298. options.set_buffer_hint();
  299. ops.ClientSendClose();
  300. }
  301. if (context_->initial_metadata_corked_) {
  302. ops.SendInitialMetadata(&context_->send_initial_metadata_,
  303. context_->initial_metadata_flags());
  304. context_->set_initial_metadata_corked(false);
  305. }
  306. if (!ops.SendMessagePtr(&msg, options).ok()) {
  307. return false;
  308. }
  309. call_.PerformOps(&ops);
  310. return cq_.Pluck(&ops);
  311. }
  312. bool WritesDone() override {
  313. ::grpc::internal::CallOpSet<::grpc::internal::CallOpClientSendClose> ops;
  314. ops.ClientSendClose();
  315. call_.PerformOps(&ops);
  316. return cq_.Pluck(&ops);
  317. }
  318. /// See the ClientStreamingInterface.Finish method for semantics.
  319. /// Side effects:
  320. /// - Also receives initial metadata if not already received.
  321. /// - Attempts to fill in the \a response parameter passed
  322. /// to the constructor of this instance with the response
  323. /// message from the server.
  324. ::grpc::Status Finish() override {
  325. ::grpc::Status status;
  326. if (!context_->initial_metadata_received_) {
  327. finish_ops_.RecvInitialMetadata(context_);
  328. }
  329. finish_ops_.ClientRecvStatus(context_, &status);
  330. call_.PerformOps(&finish_ops_);
  331. GPR_CODEGEN_ASSERT(cq_.Pluck(&finish_ops_));
  332. return status;
  333. }
  334. private:
  335. friend class internal::ClientWriterFactory<W>;
  336. /// Block to create a stream (i.e. send request headers and other initial
  337. /// metadata to the server). Note that \a context will be used to fill
  338. /// in custom initial metadata. \a response will be filled in with the
  339. /// single expected response message from the server upon a successful
  340. /// call to the \a Finish method of this instance.
  341. template <class R>
  342. ClientWriter(::grpc::ChannelInterface* channel,
  343. const ::grpc::internal::RpcMethod& method,
  344. ::grpc::ClientContext* context, R* response)
  345. : context_(context),
  346. cq_(grpc_completion_queue_attributes{
  347. GRPC_CQ_CURRENT_VERSION, GRPC_CQ_PLUCK, GRPC_CQ_DEFAULT_POLLING,
  348. nullptr}), // Pluckable cq
  349. call_(channel->CreateCall(method, context, &cq_)) {
  350. finish_ops_.RecvMessage(response);
  351. finish_ops_.AllowNoMessage();
  352. if (!context_->initial_metadata_corked_) {
  353. ::grpc::internal::CallOpSet<::grpc::internal::CallOpSendInitialMetadata>
  354. ops;
  355. ops.SendInitialMetadata(&context->send_initial_metadata_,
  356. context->initial_metadata_flags());
  357. call_.PerformOps(&ops);
  358. cq_.Pluck(&ops);
  359. }
  360. }
  361. ::grpc::ClientContext* context_;
  362. ::grpc::internal::CallOpSet<::grpc::internal::CallOpRecvInitialMetadata,
  363. ::grpc::internal::CallOpGenericRecvMessage,
  364. ::grpc::internal::CallOpClientRecvStatus>
  365. finish_ops_;
  366. ::grpc::CompletionQueue cq_;
  367. ::grpc::internal::Call call_;
  368. };
  369. /// Client-side interface for bi-directional streaming with
  370. /// client-to-server stream messages of type \a W and
  371. /// server-to-client stream messages of type \a R.
  372. template <class W, class R>
  373. class ClientReaderWriterInterface : public internal::ClientStreamingInterface,
  374. public internal::WriterInterface<W>,
  375. public internal::ReaderInterface<R> {
  376. public:
  377. /// Block to wait for initial metadata from server. The received metadata
  378. /// can only be accessed after this call returns. Should only be called before
  379. /// the first read. Calling this method is optional, and if it is not called
  380. /// the metadata will be available in ClientContext after the first read.
  381. virtual void WaitForInitialMetadata() = 0;
  382. /// Half close writing from the client. (signal that the stream of messages
  383. /// coming from the client is complete).
  384. /// Blocks until currently-pending writes are completed.
  385. /// Thread-safe with respect to \a ReaderInterface::Read
  386. ///
  387. /// \return Whether the writes were successful.
  388. virtual bool WritesDone() = 0;
  389. };
  390. namespace internal {
  391. template <class W, class R>
  392. class ClientReaderWriterFactory {
  393. public:
  394. static ClientReaderWriter<W, R>* Create(
  395. ::grpc::ChannelInterface* channel,
  396. const ::grpc::internal::RpcMethod& method,
  397. ::grpc::ClientContext* context) {
  398. return new ClientReaderWriter<W, R>(channel, method, context);
  399. }
  400. };
  401. } // namespace internal
  402. /// Synchronous (blocking) client-side API for bi-directional streaming RPCs,
  403. /// where the outgoing message stream coming from the client has messages of
  404. /// type \a W, and the incoming messages stream coming from the server has
  405. /// messages of type \a R.
  406. template <class W, class R>
  407. class ClientReaderWriter final : public ClientReaderWriterInterface<W, R> {
  408. public:
  409. /// Block waiting to read initial metadata from the server.
  410. /// This call is optional, but if it is used, it cannot be used concurrently
  411. /// with or after the \a Finish method.
  412. ///
  413. /// Once complete, the initial metadata read from the server will be
  414. /// accessible through the \a ClientContext used to construct this object.
  415. void WaitForInitialMetadata() override {
  416. GPR_CODEGEN_ASSERT(!context_->initial_metadata_received_);
  417. ::grpc::internal::CallOpSet<::grpc::internal::CallOpRecvInitialMetadata>
  418. ops;
  419. ops.RecvInitialMetadata(context_);
  420. call_.PerformOps(&ops);
  421. cq_.Pluck(&ops); // status ignored
  422. }
  423. bool NextMessageSize(uint32_t* sz) override {
  424. int result = call_.max_receive_message_size();
  425. *sz = (result > 0) ? result : UINT32_MAX;
  426. return true;
  427. }
  428. /// See the \a ReaderInterface.Read method for semantics.
  429. /// Side effect:
  430. /// Also receives initial metadata if not already received (updates the \a
  431. /// ClientContext associated with this call in that case).
  432. bool Read(R* msg) override {
  433. ::grpc::internal::CallOpSet<::grpc::internal::CallOpRecvInitialMetadata,
  434. ::grpc::internal::CallOpRecvMessage<R>>
  435. ops;
  436. if (!context_->initial_metadata_received_) {
  437. ops.RecvInitialMetadata(context_);
  438. }
  439. ops.RecvMessage(msg);
  440. call_.PerformOps(&ops);
  441. return cq_.Pluck(&ops) && ops.got_message;
  442. }
  443. /// See the \a WriterInterface.Write method for semantics.
  444. ///
  445. /// Side effect:
  446. /// Also sends initial metadata if not already sent (using the
  447. /// \a ClientContext associated with this call to fill in values).
  448. using internal::WriterInterface<W>::Write;
  449. bool Write(const W& msg, ::grpc::WriteOptions options) override {
  450. ::grpc::internal::CallOpSet<::grpc::internal::CallOpSendInitialMetadata,
  451. ::grpc::internal::CallOpSendMessage,
  452. ::grpc::internal::CallOpClientSendClose>
  453. ops;
  454. if (options.is_last_message()) {
  455. options.set_buffer_hint();
  456. ops.ClientSendClose();
  457. }
  458. if (context_->initial_metadata_corked_) {
  459. ops.SendInitialMetadata(&context_->send_initial_metadata_,
  460. context_->initial_metadata_flags());
  461. context_->set_initial_metadata_corked(false);
  462. }
  463. if (!ops.SendMessagePtr(&msg, options).ok()) {
  464. return false;
  465. }
  466. call_.PerformOps(&ops);
  467. return cq_.Pluck(&ops);
  468. }
  469. bool WritesDone() override {
  470. ::grpc::internal::CallOpSet<::grpc::internal::CallOpClientSendClose> ops;
  471. ops.ClientSendClose();
  472. call_.PerformOps(&ops);
  473. return cq_.Pluck(&ops);
  474. }
  475. /// See the ClientStreamingInterface.Finish method for semantics.
  476. ///
  477. /// Side effect:
  478. /// - the \a ClientContext associated with this call is updated with
  479. /// possible trailing metadata sent from the server.
  480. ::grpc::Status Finish() override {
  481. ::grpc::internal::CallOpSet<::grpc::internal::CallOpRecvInitialMetadata,
  482. ::grpc::internal::CallOpClientRecvStatus>
  483. ops;
  484. if (!context_->initial_metadata_received_) {
  485. ops.RecvInitialMetadata(context_);
  486. }
  487. ::grpc::Status status;
  488. ops.ClientRecvStatus(context_, &status);
  489. call_.PerformOps(&ops);
  490. GPR_CODEGEN_ASSERT(cq_.Pluck(&ops));
  491. return status;
  492. }
  493. private:
  494. friend class internal::ClientReaderWriterFactory<W, R>;
  495. ::grpc::ClientContext* context_;
  496. ::grpc::CompletionQueue cq_;
  497. ::grpc::internal::Call call_;
  498. /// Block to create a stream and write the initial metadata and \a request
  499. /// out. Note that \a context will be used to fill in custom initial metadata
  500. /// used to send to the server when starting the call.
  501. ClientReaderWriter(::grpc::ChannelInterface* channel,
  502. const ::grpc::internal::RpcMethod& method,
  503. ::grpc::ClientContext* context)
  504. : context_(context),
  505. cq_(grpc_completion_queue_attributes{
  506. GRPC_CQ_CURRENT_VERSION, GRPC_CQ_PLUCK, GRPC_CQ_DEFAULT_POLLING,
  507. nullptr}), // Pluckable cq
  508. call_(channel->CreateCall(method, context, &cq_)) {
  509. if (!context_->initial_metadata_corked_) {
  510. ::grpc::internal::CallOpSet<::grpc::internal::CallOpSendInitialMetadata>
  511. ops;
  512. ops.SendInitialMetadata(&context->send_initial_metadata_,
  513. context->initial_metadata_flags());
  514. call_.PerformOps(&ops);
  515. cq_.Pluck(&ops);
  516. }
  517. }
  518. };
  519. /// Server-side interface for streaming reads of message of type \a R.
  520. template <class R>
  521. class ServerReaderInterface : public internal::ServerStreamingInterface,
  522. public internal::ReaderInterface<R> {};
  523. /// Synchronous (blocking) server-side API for doing client-streaming RPCs,
  524. /// where the incoming message stream coming from the client has messages of
  525. /// type \a R.
  526. template <class R>
  527. class ServerReader final : public ServerReaderInterface<R> {
  528. public:
  529. /// See the \a ServerStreamingInterface.SendInitialMetadata method
  530. /// for semantics. Note that initial metadata will be affected by the
  531. /// \a ServerContext associated with this call.
  532. void SendInitialMetadata() override {
  533. GPR_CODEGEN_ASSERT(!ctx_->sent_initial_metadata_);
  534. ::grpc::internal::CallOpSet<::grpc::internal::CallOpSendInitialMetadata>
  535. ops;
  536. ops.SendInitialMetadata(&ctx_->initial_metadata_,
  537. ctx_->initial_metadata_flags());
  538. if (ctx_->compression_level_set()) {
  539. ops.set_compression_level(ctx_->compression_level());
  540. }
  541. ctx_->sent_initial_metadata_ = true;
  542. call_->PerformOps(&ops);
  543. call_->cq()->Pluck(&ops);
  544. }
  545. bool NextMessageSize(uint32_t* sz) override {
  546. int result = call_->max_receive_message_size();
  547. *sz = (result > 0) ? result : UINT32_MAX;
  548. return true;
  549. }
  550. bool Read(R* msg) override {
  551. ::grpc::internal::CallOpSet<::grpc::internal::CallOpRecvMessage<R>> ops;
  552. ops.RecvMessage(msg);
  553. call_->PerformOps(&ops);
  554. bool ok = call_->cq()->Pluck(&ops) && ops.got_message;
  555. if (!ok) {
  556. ctx_->MaybeMarkCancelledOnRead();
  557. }
  558. return ok;
  559. }
  560. private:
  561. ::grpc::internal::Call* const call_;
  562. ServerContext* const ctx_;
  563. template <class ServiceType, class RequestType, class ResponseType>
  564. friend class internal::ClientStreamingHandler;
  565. ServerReader(::grpc::internal::Call* call, ::grpc::ServerContext* ctx)
  566. : call_(call), ctx_(ctx) {}
  567. };
  568. /// Server-side interface for streaming writes of message of type \a W.
  569. template <class W>
  570. class ServerWriterInterface : public internal::ServerStreamingInterface,
  571. public internal::WriterInterface<W> {};
  572. /// Synchronous (blocking) server-side API for doing for doing a
  573. /// server-streaming RPCs, where the outgoing message stream coming from the
  574. /// server has messages of type \a W.
  575. template <class W>
  576. class ServerWriter final : public ServerWriterInterface<W> {
  577. public:
  578. /// See the \a ServerStreamingInterface.SendInitialMetadata method
  579. /// for semantics.
  580. /// Note that initial metadata will be affected by the
  581. /// \a ServerContext associated with this call.
  582. void SendInitialMetadata() override {
  583. GPR_CODEGEN_ASSERT(!ctx_->sent_initial_metadata_);
  584. ::grpc::internal::CallOpSet<::grpc::internal::CallOpSendInitialMetadata>
  585. ops;
  586. ops.SendInitialMetadata(&ctx_->initial_metadata_,
  587. ctx_->initial_metadata_flags());
  588. if (ctx_->compression_level_set()) {
  589. ops.set_compression_level(ctx_->compression_level());
  590. }
  591. ctx_->sent_initial_metadata_ = true;
  592. call_->PerformOps(&ops);
  593. call_->cq()->Pluck(&ops);
  594. }
  595. /// See the \a WriterInterface.Write method for semantics.
  596. ///
  597. /// Side effect:
  598. /// Also sends initial metadata if not already sent (using the
  599. /// \a ClientContext associated with this call to fill in values).
  600. using internal::WriterInterface<W>::Write;
  601. bool Write(const W& msg, ::grpc::WriteOptions options) override {
  602. if (options.is_last_message()) {
  603. options.set_buffer_hint();
  604. }
  605. if (!ctx_->pending_ops_.SendMessagePtr(&msg, options).ok()) {
  606. return false;
  607. }
  608. if (!ctx_->sent_initial_metadata_) {
  609. ctx_->pending_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
  610. ctx_->initial_metadata_flags());
  611. if (ctx_->compression_level_set()) {
  612. ctx_->pending_ops_.set_compression_level(ctx_->compression_level());
  613. }
  614. ctx_->sent_initial_metadata_ = true;
  615. }
  616. call_->PerformOps(&ctx_->pending_ops_);
  617. // if this is the last message we defer the pluck until AFTER we start
  618. // the trailing md op. This prevents hangs. See
  619. // https://github.com/grpc/grpc/issues/11546
  620. if (options.is_last_message()) {
  621. ctx_->has_pending_ops_ = true;
  622. return true;
  623. }
  624. ctx_->has_pending_ops_ = false;
  625. return call_->cq()->Pluck(&ctx_->pending_ops_);
  626. }
  627. private:
  628. ::grpc::internal::Call* const call_;
  629. ::grpc::ServerContext* const ctx_;
  630. template <class ServiceType, class RequestType, class ResponseType>
  631. friend class internal::ServerStreamingHandler;
  632. ServerWriter(::grpc::internal::Call* call, ::grpc::ServerContext* ctx)
  633. : call_(call), ctx_(ctx) {}
  634. };
  635. /// Server-side interface for bi-directional streaming.
  636. template <class W, class R>
  637. class ServerReaderWriterInterface : public internal::ServerStreamingInterface,
  638. public internal::WriterInterface<W>,
  639. public internal::ReaderInterface<R> {};
  640. /// Actual implementation of bi-directional streaming
  641. namespace internal {
  642. template <class W, class R>
  643. class ServerReaderWriterBody final {
  644. public:
  645. ServerReaderWriterBody(grpc::internal::Call* call, ::grpc::ServerContext* ctx)
  646. : call_(call), ctx_(ctx) {}
  647. void SendInitialMetadata() {
  648. GPR_CODEGEN_ASSERT(!ctx_->sent_initial_metadata_);
  649. grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata> ops;
  650. ops.SendInitialMetadata(&ctx_->initial_metadata_,
  651. ctx_->initial_metadata_flags());
  652. if (ctx_->compression_level_set()) {
  653. ops.set_compression_level(ctx_->compression_level());
  654. }
  655. ctx_->sent_initial_metadata_ = true;
  656. call_->PerformOps(&ops);
  657. call_->cq()->Pluck(&ops);
  658. }
  659. bool NextMessageSize(uint32_t* sz) {
  660. int result = call_->max_receive_message_size();
  661. *sz = (result > 0) ? result : UINT32_MAX;
  662. return true;
  663. }
  664. bool Read(R* msg) {
  665. ::grpc::internal::CallOpSet<::grpc::internal::CallOpRecvMessage<R>> ops;
  666. ops.RecvMessage(msg);
  667. call_->PerformOps(&ops);
  668. bool ok = call_->cq()->Pluck(&ops) && ops.got_message;
  669. if (!ok) {
  670. ctx_->MaybeMarkCancelledOnRead();
  671. }
  672. return ok;
  673. }
  674. bool Write(const W& msg, ::grpc::WriteOptions options) {
  675. if (options.is_last_message()) {
  676. options.set_buffer_hint();
  677. }
  678. if (!ctx_->pending_ops_.SendMessagePtr(&msg, options).ok()) {
  679. return false;
  680. }
  681. if (!ctx_->sent_initial_metadata_) {
  682. ctx_->pending_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
  683. ctx_->initial_metadata_flags());
  684. if (ctx_->compression_level_set()) {
  685. ctx_->pending_ops_.set_compression_level(ctx_->compression_level());
  686. }
  687. ctx_->sent_initial_metadata_ = true;
  688. }
  689. call_->PerformOps(&ctx_->pending_ops_);
  690. // if this is the last message we defer the pluck until AFTER we start
  691. // the trailing md op. This prevents hangs. See
  692. // https://github.com/grpc/grpc/issues/11546
  693. if (options.is_last_message()) {
  694. ctx_->has_pending_ops_ = true;
  695. return true;
  696. }
  697. ctx_->has_pending_ops_ = false;
  698. return call_->cq()->Pluck(&ctx_->pending_ops_);
  699. }
  700. private:
  701. grpc::internal::Call* const call_;
  702. ::grpc::ServerContext* const ctx_;
  703. };
  704. } // namespace internal
  705. /// Synchronous (blocking) server-side API for a bidirectional
  706. /// streaming call, where the incoming message stream coming from the client has
  707. /// messages of type \a R, and the outgoing message streaming coming from
  708. /// the server has messages of type \a W.
  709. template <class W, class R>
  710. class ServerReaderWriter final : public ServerReaderWriterInterface<W, R> {
  711. public:
  712. /// See the \a ServerStreamingInterface.SendInitialMetadata method
  713. /// for semantics. Note that initial metadata will be affected by the
  714. /// \a ServerContext associated with this call.
  715. void SendInitialMetadata() override { body_.SendInitialMetadata(); }
  716. bool NextMessageSize(uint32_t* sz) override {
  717. return body_.NextMessageSize(sz);
  718. }
  719. bool Read(R* msg) override { return body_.Read(msg); }
  720. /// See the \a WriterInterface.Write(const W& msg, WriteOptions options)
  721. /// method for semantics.
  722. /// Side effect:
  723. /// Also sends initial metadata if not already sent (using the \a
  724. /// ServerContext associated with this call).
  725. using internal::WriterInterface<W>::Write;
  726. bool Write(const W& msg, ::grpc::WriteOptions options) override {
  727. return body_.Write(msg, options);
  728. }
  729. private:
  730. internal::ServerReaderWriterBody<W, R> body_;
  731. friend class internal::TemplatedBidiStreamingHandler<ServerReaderWriter<W, R>,
  732. false>;
  733. ServerReaderWriter(::grpc::internal::Call* call, ::grpc::ServerContext* ctx)
  734. : body_(call, ctx) {}
  735. };
  736. /// A class to represent a flow-controlled unary call. This is something
  737. /// of a hybrid between conventional unary and streaming. This is invoked
  738. /// through a unary call on the client side, but the server responds to it
  739. /// as though it were a single-ping-pong streaming call. The server can use
  740. /// the \a NextMessageSize method to determine an upper-bound on the size of
  741. /// the message. A key difference relative to streaming: ServerUnaryStreamer
  742. /// must have exactly 1 Read and exactly 1 Write, in that order, to function
  743. /// correctly. Otherwise, the RPC is in error.
  744. template <class RequestType, class ResponseType>
  745. class ServerUnaryStreamer final
  746. : public ServerReaderWriterInterface<ResponseType, RequestType> {
  747. public:
  748. /// Block to send initial metadata to client.
  749. /// Implicit input parameter:
  750. /// - the \a ServerContext associated with this call will be used for
  751. /// sending initial metadata.
  752. void SendInitialMetadata() override { body_.SendInitialMetadata(); }
  753. /// Get an upper bound on the request message size from the client.
  754. bool NextMessageSize(uint32_t* sz) override {
  755. return body_.NextMessageSize(sz);
  756. }
  757. /// Read a message of type \a R into \a msg. Completion will be notified by \a
  758. /// tag on the associated completion queue.
  759. /// This is thread-safe with respect to \a Write or \a WritesDone methods. It
  760. /// should not be called concurrently with other streaming APIs
  761. /// on the same stream. It is not meaningful to call it concurrently
  762. /// with another \a ReaderInterface::Read on the same stream since reads on
  763. /// the same stream are delivered in order.
  764. ///
  765. /// \param[out] msg Where to eventually store the read message.
  766. /// \param[in] tag The tag identifying the operation.
  767. bool Read(RequestType* request) override {
  768. if (read_done_) {
  769. return false;
  770. }
  771. read_done_ = true;
  772. return body_.Read(request);
  773. }
  774. /// Block to write \a msg to the stream with WriteOptions \a options.
  775. /// This is thread-safe with respect to \a ReaderInterface::Read
  776. ///
  777. /// \param msg The message to be written to the stream.
  778. /// \param options The WriteOptions affecting the write operation.
  779. ///
  780. /// \return \a true on success, \a false when the stream has been closed.
  781. using internal::WriterInterface<ResponseType>::Write;
  782. bool Write(const ResponseType& response,
  783. ::grpc::WriteOptions options) override {
  784. if (write_done_ || !read_done_) {
  785. return false;
  786. }
  787. write_done_ = true;
  788. return body_.Write(response, options);
  789. }
  790. private:
  791. internal::ServerReaderWriterBody<ResponseType, RequestType> body_;
  792. bool read_done_;
  793. bool write_done_;
  794. friend class internal::TemplatedBidiStreamingHandler<
  795. ServerUnaryStreamer<RequestType, ResponseType>, true>;
  796. ServerUnaryStreamer(::grpc::internal::Call* call, ::grpc::ServerContext* ctx)
  797. : body_(call, ctx), read_done_(false), write_done_(false) {}
  798. };
  799. /// A class to represent a flow-controlled server-side streaming call.
  800. /// This is something of a hybrid between server-side and bidi streaming.
  801. /// This is invoked through a server-side streaming call on the client side,
  802. /// but the server responds to it as though it were a bidi streaming call that
  803. /// must first have exactly 1 Read and then any number of Writes.
  804. template <class RequestType, class ResponseType>
  805. class ServerSplitStreamer final
  806. : public ServerReaderWriterInterface<ResponseType, RequestType> {
  807. public:
  808. /// Block to send initial metadata to client.
  809. /// Implicit input parameter:
  810. /// - the \a ServerContext associated with this call will be used for
  811. /// sending initial metadata.
  812. void SendInitialMetadata() override { body_.SendInitialMetadata(); }
  813. /// Get an upper bound on the request message size from the client.
  814. bool NextMessageSize(uint32_t* sz) override {
  815. return body_.NextMessageSize(sz);
  816. }
  817. /// Read a message of type \a R into \a msg. Completion will be notified by \a
  818. /// tag on the associated completion queue.
  819. /// This is thread-safe with respect to \a Write or \a WritesDone methods. It
  820. /// should not be called concurrently with other streaming APIs
  821. /// on the same stream. It is not meaningful to call it concurrently
  822. /// with another \a ReaderInterface::Read on the same stream since reads on
  823. /// the same stream are delivered in order.
  824. ///
  825. /// \param[out] msg Where to eventually store the read message.
  826. /// \param[in] tag The tag identifying the operation.
  827. bool Read(RequestType* request) override {
  828. if (read_done_) {
  829. return false;
  830. }
  831. read_done_ = true;
  832. return body_.Read(request);
  833. }
  834. /// Block to write \a msg to the stream with WriteOptions \a options.
  835. /// This is thread-safe with respect to \a ReaderInterface::Read
  836. ///
  837. /// \param msg The message to be written to the stream.
  838. /// \param options The WriteOptions affecting the write operation.
  839. ///
  840. /// \return \a true on success, \a false when the stream has been closed.
  841. using internal::WriterInterface<ResponseType>::Write;
  842. bool Write(const ResponseType& response,
  843. ::grpc::WriteOptions options) override {
  844. return read_done_ && body_.Write(response, options);
  845. }
  846. private:
  847. internal::ServerReaderWriterBody<ResponseType, RequestType> body_;
  848. bool read_done_;
  849. friend class internal::TemplatedBidiStreamingHandler<
  850. ServerSplitStreamer<RequestType, ResponseType>, false>;
  851. ServerSplitStreamer(::grpc::internal::Call* call, ::grpc::ServerContext* ctx)
  852. : body_(call, ctx), read_done_(false) {}
  853. };
  854. } // namespace grpc
  855. #endif // GRPCPP_IMPL_CODEGEN_SYNC_STREAM_H