sync_stream.h 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949
  1. //
  2. //
  3. // Copyright 2015 gRPC authors.
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License");
  6. // you may not use this file except in compliance with the License.
  7. // You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. //
  17. //
  18. #ifndef GRPCPP_SUPPORT_SYNC_STREAM_H
  19. #define GRPCPP_SUPPORT_SYNC_STREAM_H
  20. #include <grpc/support/log.h>
  21. #include <grpcpp/client_context.h>
  22. #include <grpcpp/completion_queue.h>
  23. #include <grpcpp/impl/call.h>
  24. #include <grpcpp/impl/codegen/channel_interface.h>
  25. #include <grpcpp/impl/service_type.h>
  26. #include <grpcpp/server_context.h>
  27. #include <grpcpp/support/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_ASSERT(!context_->initial_metadata_received_);
  170. grpc::internal::CallOpSet<grpc::internal::CallOpRecvInitialMetadata> ops;
  171. ops.RecvInitialMetadata(context_);
  172. call_.PerformOps(&ops);
  173. cq_.Pluck(&ops); /// status ignored
  174. }
  175. bool NextMessageSize(uint32_t* sz) override {
  176. int result = call_.max_receive_message_size();
  177. *sz = (result > 0) ? result : UINT32_MAX;
  178. return true;
  179. }
  180. /// See the \a ReaderInterface.Read method for semantics.
  181. /// Side effect:
  182. /// This also receives initial metadata from the server, if not
  183. /// already received (if initial metadata is received, it can be then
  184. /// accessed through the \a ClientContext associated with this call).
  185. bool Read(R* msg) override {
  186. grpc::internal::CallOpSet<grpc::internal::CallOpRecvInitialMetadata,
  187. grpc::internal::CallOpRecvMessage<R>>
  188. ops;
  189. if (!context_->initial_metadata_received_) {
  190. ops.RecvInitialMetadata(context_);
  191. }
  192. ops.RecvMessage(msg);
  193. call_.PerformOps(&ops);
  194. return cq_.Pluck(&ops) && ops.got_message;
  195. }
  196. /// See the \a ClientStreamingInterface.Finish method for semantics.
  197. ///
  198. /// Side effect:
  199. /// The \a ClientContext associated with this call is updated with
  200. /// possible metadata received from the server.
  201. grpc::Status Finish() override {
  202. grpc::internal::CallOpSet<grpc::internal::CallOpRecvInitialMetadata,
  203. grpc::internal::CallOpClientRecvStatus>
  204. ops;
  205. if (!context_->initial_metadata_received_) {
  206. ops.RecvInitialMetadata(context_);
  207. }
  208. grpc::Status status;
  209. ops.ClientRecvStatus(context_, &status);
  210. call_.PerformOps(&ops);
  211. GPR_ASSERT(cq_.Pluck(&ops));
  212. return status;
  213. }
  214. private:
  215. friend class internal::ClientReaderFactory<R>;
  216. grpc::ClientContext* context_;
  217. grpc::CompletionQueue cq_;
  218. grpc::internal::Call call_;
  219. /// Block to create a stream and write the initial metadata and \a request
  220. /// out. Note that \a context will be used to fill in custom initial
  221. /// metadata used to send to the server when starting the call.
  222. template <class W>
  223. ClientReader(grpc::ChannelInterface* channel,
  224. const grpc::internal::RpcMethod& method,
  225. grpc::ClientContext* context, const W& request)
  226. : context_(context),
  227. cq_(grpc_completion_queue_attributes{
  228. GRPC_CQ_CURRENT_VERSION, GRPC_CQ_PLUCK, GRPC_CQ_DEFAULT_POLLING,
  229. nullptr}), // Pluckable cq
  230. call_(channel->CreateCall(method, context, &cq_)) {
  231. grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata,
  232. grpc::internal::CallOpSendMessage,
  233. grpc::internal::CallOpClientSendClose>
  234. ops;
  235. ops.SendInitialMetadata(&context->send_initial_metadata_,
  236. context->initial_metadata_flags());
  237. // TODO(ctiller): don't assert
  238. GPR_ASSERT(ops.SendMessagePtr(&request).ok());
  239. ops.ClientSendClose();
  240. call_.PerformOps(&ops);
  241. cq_.Pluck(&ops);
  242. }
  243. };
  244. /// Client-side interface for streaming writes of message type \a W.
  245. template <class W>
  246. class ClientWriterInterface : public internal::ClientStreamingInterface,
  247. public internal::WriterInterface<W> {
  248. public:
  249. /// Half close writing from the client. (signal that the stream of messages
  250. /// coming from the client is complete).
  251. /// Blocks until currently-pending writes are completed.
  252. /// Thread safe with respect to \a ReaderInterface::Read operations only
  253. ///
  254. /// \return Whether the writes were successful.
  255. virtual bool WritesDone() = 0;
  256. };
  257. namespace internal {
  258. template <class W>
  259. class ClientWriterFactory {
  260. public:
  261. template <class R>
  262. static ClientWriter<W>* Create(grpc::ChannelInterface* channel,
  263. const grpc::internal::RpcMethod& method,
  264. grpc::ClientContext* context, R* response) {
  265. return new ClientWriter<W>(channel, method, context, response);
  266. }
  267. };
  268. } // namespace internal
  269. /// Synchronous (blocking) client-side API for doing client-streaming RPCs,
  270. /// where the outgoing message stream coming from the client has messages of
  271. /// type \a W.
  272. template <class W>
  273. class ClientWriter : public ClientWriterInterface<W> {
  274. public:
  275. /// See the \a ClientStreamingInterface.WaitForInitialMetadata method for
  276. /// semantics.
  277. ///
  278. // Side effect:
  279. /// Once complete, the initial metadata read from the server will be
  280. /// accessible through the \a ClientContext used to construct this object.
  281. void WaitForInitialMetadata() {
  282. GPR_ASSERT(!context_->initial_metadata_received_);
  283. grpc::internal::CallOpSet<grpc::internal::CallOpRecvInitialMetadata> ops;
  284. ops.RecvInitialMetadata(context_);
  285. call_.PerformOps(&ops);
  286. cq_.Pluck(&ops); // status ignored
  287. }
  288. /// See the WriterInterface.Write(const W& msg, WriteOptions options) method
  289. /// for semantics.
  290. ///
  291. /// Side effect:
  292. /// Also sends initial metadata if not already sent (using the
  293. /// \a ClientContext associated with this call).
  294. using internal::WriterInterface<W>::Write;
  295. bool Write(const W& msg, grpc::WriteOptions options) override {
  296. grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata,
  297. grpc::internal::CallOpSendMessage,
  298. grpc::internal::CallOpClientSendClose>
  299. ops;
  300. if (options.is_last_message()) {
  301. options.set_buffer_hint();
  302. ops.ClientSendClose();
  303. }
  304. if (context_->initial_metadata_corked_) {
  305. ops.SendInitialMetadata(&context_->send_initial_metadata_,
  306. context_->initial_metadata_flags());
  307. context_->set_initial_metadata_corked(false);
  308. }
  309. if (!ops.SendMessagePtr(&msg, options).ok()) {
  310. return false;
  311. }
  312. call_.PerformOps(&ops);
  313. return cq_.Pluck(&ops);
  314. }
  315. bool WritesDone() override {
  316. grpc::internal::CallOpSet<grpc::internal::CallOpClientSendClose> ops;
  317. ops.ClientSendClose();
  318. call_.PerformOps(&ops);
  319. return cq_.Pluck(&ops);
  320. }
  321. /// See the ClientStreamingInterface.Finish method for semantics.
  322. /// Side effects:
  323. /// - Also receives initial metadata if not already received.
  324. /// - Attempts to fill in the \a response parameter passed
  325. /// to the constructor of this instance with the response
  326. /// message from the server.
  327. grpc::Status Finish() override {
  328. grpc::Status status;
  329. if (!context_->initial_metadata_received_) {
  330. finish_ops_.RecvInitialMetadata(context_);
  331. }
  332. finish_ops_.ClientRecvStatus(context_, &status);
  333. call_.PerformOps(&finish_ops_);
  334. GPR_ASSERT(cq_.Pluck(&finish_ops_));
  335. return status;
  336. }
  337. private:
  338. friend class internal::ClientWriterFactory<W>;
  339. /// Block to create a stream (i.e. send request headers and other initial
  340. /// metadata to the server). Note that \a context will be used to fill
  341. /// in custom initial metadata. \a response will be filled in with the
  342. /// single expected response message from the server upon a successful
  343. /// call to the \a Finish method of this instance.
  344. template <class R>
  345. ClientWriter(grpc::ChannelInterface* channel,
  346. const grpc::internal::RpcMethod& method,
  347. grpc::ClientContext* context, R* response)
  348. : context_(context),
  349. cq_(grpc_completion_queue_attributes{
  350. GRPC_CQ_CURRENT_VERSION, GRPC_CQ_PLUCK, GRPC_CQ_DEFAULT_POLLING,
  351. nullptr}), // Pluckable cq
  352. call_(channel->CreateCall(method, context, &cq_)) {
  353. finish_ops_.RecvMessage(response);
  354. finish_ops_.AllowNoMessage();
  355. if (!context_->initial_metadata_corked_) {
  356. grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata> ops;
  357. ops.SendInitialMetadata(&context->send_initial_metadata_,
  358. context->initial_metadata_flags());
  359. call_.PerformOps(&ops);
  360. cq_.Pluck(&ops);
  361. }
  362. }
  363. grpc::ClientContext* context_;
  364. grpc::internal::CallOpSet<grpc::internal::CallOpRecvInitialMetadata,
  365. grpc::internal::CallOpGenericRecvMessage,
  366. grpc::internal::CallOpClientRecvStatus>
  367. finish_ops_;
  368. grpc::CompletionQueue cq_;
  369. grpc::internal::Call call_;
  370. };
  371. /// Client-side interface for bi-directional streaming with
  372. /// client-to-server stream messages of type \a W and
  373. /// server-to-client stream messages of type \a R.
  374. template <class W, class R>
  375. class ClientReaderWriterInterface : public internal::ClientStreamingInterface,
  376. public internal::WriterInterface<W>,
  377. public internal::ReaderInterface<R> {
  378. public:
  379. /// Block to wait for initial metadata from server. The received metadata
  380. /// can only be accessed after this call returns. Should only be called before
  381. /// the first read. Calling this method is optional, and if it is not called
  382. /// the metadata will be available in ClientContext after the first read.
  383. virtual void WaitForInitialMetadata() = 0;
  384. /// Half close writing from the client. (signal that the stream of messages
  385. /// coming from the client is complete).
  386. /// Blocks until currently-pending writes are completed.
  387. /// Thread-safe with respect to \a ReaderInterface::Read
  388. ///
  389. /// \return Whether the writes were successful.
  390. virtual bool WritesDone() = 0;
  391. };
  392. namespace internal {
  393. template <class W, class R>
  394. class ClientReaderWriterFactory {
  395. public:
  396. static ClientReaderWriter<W, R>* Create(
  397. grpc::ChannelInterface* channel, const grpc::internal::RpcMethod& method,
  398. grpc::ClientContext* context) {
  399. return new ClientReaderWriter<W, R>(channel, method, context);
  400. }
  401. };
  402. } // namespace internal
  403. /// Synchronous (blocking) client-side API for bi-directional streaming RPCs,
  404. /// where the outgoing message stream coming from the client has messages of
  405. /// type \a W, and the incoming messages stream coming from the server has
  406. /// messages of type \a R.
  407. template <class W, class R>
  408. class ClientReaderWriter final : public ClientReaderWriterInterface<W, R> {
  409. public:
  410. /// Block waiting to read initial metadata from the server.
  411. /// This call is optional, but if it is used, it cannot be used concurrently
  412. /// with or after the \a Finish method.
  413. ///
  414. /// Once complete, the initial metadata read from the server will be
  415. /// accessible through the \a ClientContext used to construct this object.
  416. void WaitForInitialMetadata() override {
  417. GPR_ASSERT(!context_->initial_metadata_received_);
  418. grpc::internal::CallOpSet<grpc::internal::CallOpRecvInitialMetadata> 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_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> ops;
  511. ops.SendInitialMetadata(&context->send_initial_metadata_,
  512. context->initial_metadata_flags());
  513. call_.PerformOps(&ops);
  514. cq_.Pluck(&ops);
  515. }
  516. }
  517. };
  518. /// Server-side interface for streaming reads of message of type \a R.
  519. template <class R>
  520. class ServerReaderInterface : public internal::ServerStreamingInterface,
  521. public internal::ReaderInterface<R> {};
  522. /// Synchronous (blocking) server-side API for doing client-streaming RPCs,
  523. /// where the incoming message stream coming from the client has messages of
  524. /// type \a R.
  525. template <class R>
  526. class ServerReader final : public ServerReaderInterface<R> {
  527. public:
  528. /// See the \a ServerStreamingInterface.SendInitialMetadata method
  529. /// for semantics. Note that initial metadata will be affected by the
  530. /// \a ServerContext associated with this call.
  531. void SendInitialMetadata() override {
  532. GPR_ASSERT(!ctx_->sent_initial_metadata_);
  533. grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata> ops;
  534. ops.SendInitialMetadata(&ctx_->initial_metadata_,
  535. ctx_->initial_metadata_flags());
  536. if (ctx_->compression_level_set()) {
  537. ops.set_compression_level(ctx_->compression_level());
  538. }
  539. ctx_->sent_initial_metadata_ = true;
  540. call_->PerformOps(&ops);
  541. call_->cq()->Pluck(&ops);
  542. }
  543. bool NextMessageSize(uint32_t* sz) override {
  544. int result = call_->max_receive_message_size();
  545. *sz = (result > 0) ? result : UINT32_MAX;
  546. return true;
  547. }
  548. bool Read(R* msg) override {
  549. grpc::internal::CallOpSet<grpc::internal::CallOpRecvMessage<R>> ops;
  550. ops.RecvMessage(msg);
  551. call_->PerformOps(&ops);
  552. bool ok = call_->cq()->Pluck(&ops) && ops.got_message;
  553. if (!ok) {
  554. ctx_->MaybeMarkCancelledOnRead();
  555. }
  556. return ok;
  557. }
  558. private:
  559. grpc::internal::Call* const call_;
  560. ServerContext* const ctx_;
  561. template <class ServiceType, class RequestType, class ResponseType>
  562. friend class internal::ClientStreamingHandler;
  563. ServerReader(grpc::internal::Call* call, grpc::ServerContext* ctx)
  564. : call_(call), ctx_(ctx) {}
  565. };
  566. /// Server-side interface for streaming writes of message of type \a W.
  567. template <class W>
  568. class ServerWriterInterface : public internal::ServerStreamingInterface,
  569. public internal::WriterInterface<W> {};
  570. /// Synchronous (blocking) server-side API for doing for doing a
  571. /// server-streaming RPCs, where the outgoing message stream coming from the
  572. /// server has messages of type \a W.
  573. template <class W>
  574. class ServerWriter final : public ServerWriterInterface<W> {
  575. public:
  576. /// See the \a ServerStreamingInterface.SendInitialMetadata method
  577. /// for semantics.
  578. /// Note that initial metadata will be affected by the
  579. /// \a ServerContext associated with this call.
  580. void SendInitialMetadata() override {
  581. GPR_ASSERT(!ctx_->sent_initial_metadata_);
  582. grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata> ops;
  583. ops.SendInitialMetadata(&ctx_->initial_metadata_,
  584. ctx_->initial_metadata_flags());
  585. if (ctx_->compression_level_set()) {
  586. ops.set_compression_level(ctx_->compression_level());
  587. }
  588. ctx_->sent_initial_metadata_ = true;
  589. call_->PerformOps(&ops);
  590. call_->cq()->Pluck(&ops);
  591. }
  592. /// See the \a WriterInterface.Write method for semantics.
  593. ///
  594. /// Side effect:
  595. /// Also sends initial metadata if not already sent (using the
  596. /// \a ClientContext associated with this call to fill in values).
  597. using internal::WriterInterface<W>::Write;
  598. bool Write(const W& msg, grpc::WriteOptions options) override {
  599. if (options.is_last_message()) {
  600. options.set_buffer_hint();
  601. }
  602. if (!ctx_->pending_ops_.SendMessagePtr(&msg, options).ok()) {
  603. return false;
  604. }
  605. if (!ctx_->sent_initial_metadata_) {
  606. ctx_->pending_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
  607. ctx_->initial_metadata_flags());
  608. if (ctx_->compression_level_set()) {
  609. ctx_->pending_ops_.set_compression_level(ctx_->compression_level());
  610. }
  611. ctx_->sent_initial_metadata_ = true;
  612. }
  613. call_->PerformOps(&ctx_->pending_ops_);
  614. // if this is the last message we defer the pluck until AFTER we start
  615. // the trailing md op. This prevents hangs. See
  616. // https://github.com/grpc/grpc/issues/11546
  617. if (options.is_last_message()) {
  618. ctx_->has_pending_ops_ = true;
  619. return true;
  620. }
  621. ctx_->has_pending_ops_ = false;
  622. return call_->cq()->Pluck(&ctx_->pending_ops_);
  623. }
  624. private:
  625. grpc::internal::Call* const call_;
  626. grpc::ServerContext* const ctx_;
  627. template <class ServiceType, class RequestType, class ResponseType>
  628. friend class internal::ServerStreamingHandler;
  629. ServerWriter(grpc::internal::Call* call, grpc::ServerContext* ctx)
  630. : call_(call), ctx_(ctx) {}
  631. };
  632. /// Server-side interface for bi-directional streaming.
  633. template <class W, class R>
  634. class ServerReaderWriterInterface : public internal::ServerStreamingInterface,
  635. public internal::WriterInterface<W>,
  636. public internal::ReaderInterface<R> {};
  637. /// Actual implementation of bi-directional streaming
  638. namespace internal {
  639. template <class W, class R>
  640. class ServerReaderWriterBody final {
  641. public:
  642. ServerReaderWriterBody(grpc::internal::Call* call, grpc::ServerContext* ctx)
  643. : call_(call), ctx_(ctx) {}
  644. void SendInitialMetadata() {
  645. GPR_ASSERT(!ctx_->sent_initial_metadata_);
  646. grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata> ops;
  647. ops.SendInitialMetadata(&ctx_->initial_metadata_,
  648. ctx_->initial_metadata_flags());
  649. if (ctx_->compression_level_set()) {
  650. ops.set_compression_level(ctx_->compression_level());
  651. }
  652. ctx_->sent_initial_metadata_ = true;
  653. call_->PerformOps(&ops);
  654. call_->cq()->Pluck(&ops);
  655. }
  656. bool NextMessageSize(uint32_t* sz) {
  657. int result = call_->max_receive_message_size();
  658. *sz = (result > 0) ? result : UINT32_MAX;
  659. return true;
  660. }
  661. bool Read(R* msg) {
  662. grpc::internal::CallOpSet<grpc::internal::CallOpRecvMessage<R>> ops;
  663. ops.RecvMessage(msg);
  664. call_->PerformOps(&ops);
  665. bool ok = call_->cq()->Pluck(&ops) && ops.got_message;
  666. if (!ok) {
  667. ctx_->MaybeMarkCancelledOnRead();
  668. }
  669. return ok;
  670. }
  671. bool Write(const W& msg, grpc::WriteOptions options) {
  672. if (options.is_last_message()) {
  673. options.set_buffer_hint();
  674. }
  675. if (!ctx_->pending_ops_.SendMessagePtr(&msg, options).ok()) {
  676. return false;
  677. }
  678. if (!ctx_->sent_initial_metadata_) {
  679. ctx_->pending_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
  680. ctx_->initial_metadata_flags());
  681. if (ctx_->compression_level_set()) {
  682. ctx_->pending_ops_.set_compression_level(ctx_->compression_level());
  683. }
  684. ctx_->sent_initial_metadata_ = true;
  685. }
  686. call_->PerformOps(&ctx_->pending_ops_);
  687. // if this is the last message we defer the pluck until AFTER we start
  688. // the trailing md op. This prevents hangs. See
  689. // https://github.com/grpc/grpc/issues/11546
  690. if (options.is_last_message()) {
  691. ctx_->has_pending_ops_ = true;
  692. return true;
  693. }
  694. ctx_->has_pending_ops_ = false;
  695. return call_->cq()->Pluck(&ctx_->pending_ops_);
  696. }
  697. private:
  698. grpc::internal::Call* const call_;
  699. grpc::ServerContext* const ctx_;
  700. };
  701. } // namespace internal
  702. /// Synchronous (blocking) server-side API for a bidirectional
  703. /// streaming call, where the incoming message stream coming from the client has
  704. /// messages of type \a R, and the outgoing message streaming coming from
  705. /// the server has messages of type \a W.
  706. template <class W, class R>
  707. class ServerReaderWriter final : public ServerReaderWriterInterface<W, R> {
  708. public:
  709. /// See the \a ServerStreamingInterface.SendInitialMetadata method
  710. /// for semantics. Note that initial metadata will be affected by the
  711. /// \a ServerContext associated with this call.
  712. void SendInitialMetadata() override { body_.SendInitialMetadata(); }
  713. bool NextMessageSize(uint32_t* sz) override {
  714. return body_.NextMessageSize(sz);
  715. }
  716. bool Read(R* msg) override { return body_.Read(msg); }
  717. /// See the \a WriterInterface.Write(const W& msg, WriteOptions options)
  718. /// method for semantics.
  719. /// Side effect:
  720. /// Also sends initial metadata if not already sent (using the \a
  721. /// ServerContext associated with this call).
  722. using internal::WriterInterface<W>::Write;
  723. bool Write(const W& msg, grpc::WriteOptions options) override {
  724. return body_.Write(msg, options);
  725. }
  726. private:
  727. internal::ServerReaderWriterBody<W, R> body_;
  728. friend class internal::TemplatedBidiStreamingHandler<ServerReaderWriter<W, R>,
  729. false>;
  730. ServerReaderWriter(grpc::internal::Call* call, grpc::ServerContext* ctx)
  731. : body_(call, ctx) {}
  732. };
  733. /// A class to represent a flow-controlled unary call. This is something
  734. /// of a hybrid between conventional unary and streaming. This is invoked
  735. /// through a unary call on the client side, but the server responds to it
  736. /// as though it were a single-ping-pong streaming call. The server can use
  737. /// the \a NextMessageSize method to determine an upper-bound on the size of
  738. /// the message. A key difference relative to streaming: ServerUnaryStreamer
  739. /// must have exactly 1 Read and exactly 1 Write, in that order, to function
  740. /// correctly. Otherwise, the RPC is in error.
  741. template <class RequestType, class ResponseType>
  742. class ServerUnaryStreamer final
  743. : public ServerReaderWriterInterface<ResponseType, RequestType> {
  744. public:
  745. /// Block to send initial metadata to client.
  746. /// Implicit input parameter:
  747. /// - the \a ServerContext associated with this call will be used for
  748. /// sending initial metadata.
  749. void SendInitialMetadata() override { body_.SendInitialMetadata(); }
  750. /// Get an upper bound on the request message size from the client.
  751. bool NextMessageSize(uint32_t* sz) override {
  752. return body_.NextMessageSize(sz);
  753. }
  754. /// Read a message of type \a R into \a msg. Completion will be notified by \a
  755. /// tag on the associated completion queue.
  756. /// This is thread-safe with respect to \a Write or \a WritesDone methods. It
  757. /// should not be called concurrently with other streaming APIs
  758. /// on the same stream. It is not meaningful to call it concurrently
  759. /// with another \a ReaderInterface::Read on the same stream since reads on
  760. /// the same stream are delivered in order.
  761. ///
  762. /// \param[out] msg Where to eventually store the read message.
  763. /// \param[in] tag The tag identifying the operation.
  764. bool Read(RequestType* request) override {
  765. if (read_done_) {
  766. return false;
  767. }
  768. read_done_ = true;
  769. return body_.Read(request);
  770. }
  771. /// Block to write \a msg to the stream with WriteOptions \a options.
  772. /// This is thread-safe with respect to \a ReaderInterface::Read
  773. ///
  774. /// \param msg The message to be written to the stream.
  775. /// \param options The WriteOptions affecting the write operation.
  776. ///
  777. /// \return \a true on success, \a false when the stream has been closed.
  778. using internal::WriterInterface<ResponseType>::Write;
  779. bool Write(const ResponseType& response,
  780. grpc::WriteOptions options) override {
  781. if (write_done_ || !read_done_) {
  782. return false;
  783. }
  784. write_done_ = true;
  785. return body_.Write(response, options);
  786. }
  787. private:
  788. internal::ServerReaderWriterBody<ResponseType, RequestType> body_;
  789. bool read_done_;
  790. bool write_done_;
  791. friend class internal::TemplatedBidiStreamingHandler<
  792. ServerUnaryStreamer<RequestType, ResponseType>, true>;
  793. ServerUnaryStreamer(grpc::internal::Call* call, grpc::ServerContext* ctx)
  794. : body_(call, ctx), read_done_(false), write_done_(false) {}
  795. };
  796. /// A class to represent a flow-controlled server-side streaming call.
  797. /// This is something of a hybrid between server-side and bidi streaming.
  798. /// This is invoked through a server-side streaming call on the client side,
  799. /// but the server responds to it as though it were a bidi streaming call that
  800. /// must first have exactly 1 Read and then any number of Writes.
  801. template <class RequestType, class ResponseType>
  802. class ServerSplitStreamer final
  803. : public ServerReaderWriterInterface<ResponseType, RequestType> {
  804. public:
  805. /// Block to send initial metadata to client.
  806. /// Implicit input parameter:
  807. /// - the \a ServerContext associated with this call will be used for
  808. /// sending initial metadata.
  809. void SendInitialMetadata() override { body_.SendInitialMetadata(); }
  810. /// Get an upper bound on the request message size from the client.
  811. bool NextMessageSize(uint32_t* sz) override {
  812. return body_.NextMessageSize(sz);
  813. }
  814. /// Read a message of type \a R into \a msg. Completion will be notified by \a
  815. /// tag on the associated completion queue.
  816. /// This is thread-safe with respect to \a Write or \a WritesDone methods. It
  817. /// should not be called concurrently with other streaming APIs
  818. /// on the same stream. It is not meaningful to call it concurrently
  819. /// with another \a ReaderInterface::Read on the same stream since reads on
  820. /// the same stream are delivered in order.
  821. ///
  822. /// \param[out] msg Where to eventually store the read message.
  823. /// \param[in] tag The tag identifying the operation.
  824. bool Read(RequestType* request) override {
  825. if (read_done_) {
  826. return false;
  827. }
  828. read_done_ = true;
  829. return body_.Read(request);
  830. }
  831. /// Block to write \a msg to the stream with WriteOptions \a options.
  832. /// This is thread-safe with respect to \a ReaderInterface::Read
  833. ///
  834. /// \param msg The message to be written to the stream.
  835. /// \param options The WriteOptions affecting the write operation.
  836. ///
  837. /// \return \a true on success, \a false when the stream has been closed.
  838. using internal::WriterInterface<ResponseType>::Write;
  839. bool Write(const ResponseType& response,
  840. grpc::WriteOptions options) override {
  841. return read_done_ && body_.Write(response, options);
  842. }
  843. private:
  844. internal::ServerReaderWriterBody<ResponseType, RequestType> body_;
  845. bool read_done_;
  846. friend class internal::TemplatedBidiStreamingHandler<
  847. ServerSplitStreamer<RequestType, ResponseType>, false>;
  848. ServerSplitStreamer(grpc::internal::Call* call, grpc::ServerContext* ctx)
  849. : body_(call, ctx), read_done_(false) {}
  850. };
  851. } // namespace grpc
  852. #endif // GRPCPP_SUPPORT_SYNC_STREAM_H