Imported Upstream version 1.22.0
[platform/upstream/grpc.git] / include / grpcpp / impl / codegen / completion_queue_impl.h
1 /*
2  *
3  * Copyright 2015-2016 gRPC authors.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */
18
19 /// A completion queue implements a concurrent producer-consumer queue, with
20 /// two main API-exposed methods: \a Next and \a AsyncNext. These
21 /// methods are the essential component of the gRPC C++ asynchronous API.
22 /// There is also a \a Shutdown method to indicate that a given completion queue
23 /// will no longer have regular events. This must be called before the
24 /// completion queue is destroyed.
25 /// All completion queue APIs are thread-safe and may be used concurrently with
26 /// any other completion queue API invocation; it is acceptable to have
27 /// multiple threads calling \a Next or \a AsyncNext on the same or different
28 /// completion queues, or to call these methods concurrently with a \a Shutdown
29 /// elsewhere.
30 /// \remark{All other API calls on completion queue should be completed before
31 /// a completion queue destructor is called.}
32 #ifndef GRPCPP_IMPL_CODEGEN_COMPLETION_QUEUE_IMPL_H
33 #define GRPCPP_IMPL_CODEGEN_COMPLETION_QUEUE_IMPL_H
34
35 #include <grpc/impl/codegen/atm.h>
36 #include <grpcpp/impl/codegen/completion_queue_tag.h>
37 #include <grpcpp/impl/codegen/core_codegen_interface.h>
38 #include <grpcpp/impl/codegen/grpc_library.h>
39 #include <grpcpp/impl/codegen/status.h>
40 #include <grpcpp/impl/codegen/time.h>
41
42 struct grpc_completion_queue;
43
44 namespace grpc_impl {
45
46 class Channel;
47 class Server;
48 class ServerBuilder;
49 class ServerContext;
50 }  // namespace grpc_impl
51 namespace grpc {
52
53 template <class R>
54 class ClientReader;
55 template <class W>
56 class ClientWriter;
57 template <class W, class R>
58 class ClientReaderWriter;
59 template <class R>
60 class ServerReader;
61 template <class W>
62 class ServerWriter;
63 namespace internal {
64 template <class W, class R>
65 class ServerReaderWriterBody;
66 }  // namespace internal
67
68 class ChannelInterface;
69 class ServerInterface;
70
71 namespace internal {
72 class CompletionQueueTag;
73 class RpcMethod;
74 template <class ServiceType, class RequestType, class ResponseType>
75 class RpcMethodHandler;
76 template <class ServiceType, class RequestType, class ResponseType>
77 class ClientStreamingHandler;
78 template <class ServiceType, class RequestType, class ResponseType>
79 class ServerStreamingHandler;
80 template <class ServiceType, class RequestType, class ResponseType>
81 class BidiStreamingHandler;
82 template <class Streamer, bool WriteNeeded>
83 class TemplatedBidiStreamingHandler;
84 template <StatusCode code>
85 class ErrorMethodHandler;
86 template <class InputMessage, class OutputMessage>
87 class BlockingUnaryCallImpl;
88 template <class Op1, class Op2, class Op3, class Op4, class Op5, class Op6>
89 class CallOpSet;
90 }  // namespace internal
91
92 extern CoreCodegenInterface* g_core_codegen_interface;
93
94 }  // namespace grpc
95
96 namespace grpc_impl {
97
98 /// A thin wrapper around \ref grpc_completion_queue (see \ref
99 /// src/core/lib/surface/completion_queue.h).
100 /// See \ref doc/cpp/perf_notes.md for notes on best practices for high
101 /// performance servers.
102 class CompletionQueue : private ::grpc::GrpcLibraryCodegen {
103  public:
104   /// Default constructor. Implicitly creates a \a grpc_completion_queue
105   /// instance.
106   CompletionQueue()
107       : CompletionQueue(grpc_completion_queue_attributes{
108             GRPC_CQ_CURRENT_VERSION, GRPC_CQ_NEXT, GRPC_CQ_DEFAULT_POLLING,
109             nullptr}) {}
110
111   /// Wrap \a take, taking ownership of the instance.
112   ///
113   /// \param take The completion queue instance to wrap. Ownership is taken.
114   explicit CompletionQueue(grpc_completion_queue* take);
115
116   /// Destructor. Destroys the owned wrapped completion queue / instance.
117   ~CompletionQueue() {
118     ::grpc::g_core_codegen_interface->grpc_completion_queue_destroy(cq_);
119   }
120
121   /// Tri-state return for AsyncNext: SHUTDOWN, GOT_EVENT, TIMEOUT.
122   enum NextStatus {
123     SHUTDOWN,   ///< The completion queue has been shutdown and fully-drained
124     GOT_EVENT,  ///< Got a new event; \a tag will be filled in with its
125                 ///< associated value; \a ok indicating its success.
126     TIMEOUT     ///< deadline was reached.
127   };
128
129   /// Read from the queue, blocking until an event is available or the queue is
130   /// shutting down.
131   ///
132   /// \param tag [out] Updated to point to the read event's tag.
133   /// \param ok [out] true if read a successful event, false otherwise.
134   ///
135   /// Note that each tag sent to the completion queue (through RPC operations
136   /// or alarms) will be delivered out of the completion queue by a call to
137   /// Next (or a related method), regardless of whether the operation succeeded
138   /// or not. Success here means that this operation completed in the normal
139   /// valid manner.
140   ///
141   /// Server-side RPC request: \a ok indicates that the RPC has indeed
142   /// been started. If it is false, the server has been Shutdown
143   /// before this particular call got matched to an incoming RPC.
144   ///
145   /// Client-side StartCall/RPC invocation: \a ok indicates that the RPC is
146   /// going to go to the wire. If it is false, it not going to the wire. This
147   /// would happen if the channel is either permanently broken or
148   /// transiently broken but with the fail-fast option. (Note that async unary
149   /// RPCs don't post a CQ tag at this point, nor do client-streaming
150   /// or bidi-streaming RPCs that have the initial metadata corked option set.)
151   ///
152   /// Client-side Write, Client-side WritesDone, Server-side Write,
153   /// Server-side Finish, Server-side SendInitialMetadata (which is
154   /// typically included in Write or Finish when not done explicitly):
155   /// \a ok means that the data/metadata/status/etc is going to go to the
156   /// wire. If it is false, it not going to the wire because the call
157   /// is already dead (i.e., canceled, deadline expired, other side
158   /// dropped the channel, etc).
159   ///
160   /// Client-side Read, Server-side Read, Client-side
161   /// RecvInitialMetadata (which is typically included in Read if not
162   /// done explicitly): \a ok indicates whether there is a valid message
163   /// that got read. If not, you know that there are certainly no more
164   /// messages that can ever be read from this stream. For the client-side
165   /// operations, this only happens because the call is dead. For the
166   /// server-sider operation, though, this could happen because the client
167   /// has done a WritesDone already.
168   ///
169   /// Client-side Finish: \a ok should always be true
170   ///
171   /// Server-side AsyncNotifyWhenDone: \a ok should always be true
172   ///
173   /// Alarm: \a ok is true if it expired, false if it was canceled
174   ///
175   /// \return true if got an event, false if the queue is fully drained and
176   ///         shut down.
177   bool Next(void** tag, bool* ok) {
178     return (AsyncNextInternal(tag, ok,
179                               ::grpc::g_core_codegen_interface->gpr_inf_future(
180                                   GPR_CLOCK_REALTIME)) != SHUTDOWN);
181   }
182
183   /// Read from the queue, blocking up to \a deadline (or the queue's shutdown).
184   /// Both \a tag and \a ok are updated upon success (if an event is available
185   /// within the \a deadline).  A \a tag points to an arbitrary location usually
186   /// employed to uniquely identify an event.
187   ///
188   /// \param tag [out] Upon success, updated to point to the event's tag.
189   /// \param ok [out] Upon success, true if a successful event, false otherwise
190   ///        See documentation for CompletionQueue::Next for explanation of ok
191   /// \param deadline [in] How long to block in wait for an event.
192   ///
193   /// \return The type of event read.
194   template <typename T>
195   NextStatus AsyncNext(void** tag, bool* ok, const T& deadline) {
196     ::grpc::TimePoint<T> deadline_tp(deadline);
197     return AsyncNextInternal(tag, ok, deadline_tp.raw_time());
198   }
199
200   /// EXPERIMENTAL
201   /// First executes \a F, then reads from the queue, blocking up to
202   /// \a deadline (or the queue's shutdown).
203   /// Both \a tag and \a ok are updated upon success (if an event is available
204   /// within the \a deadline).  A \a tag points to an arbitrary location usually
205   /// employed to uniquely identify an event.
206   ///
207   /// \param f [in] Function to execute before calling AsyncNext on this queue.
208   /// \param tag [out] Upon success, updated to point to the event's tag.
209   /// \param ok [out] Upon success, true if read a regular event, false
210   /// otherwise.
211   /// \param deadline [in] How long to block in wait for an event.
212   ///
213   /// \return The type of event read.
214   template <typename T, typename F>
215   NextStatus DoThenAsyncNext(F&& f, void** tag, bool* ok, const T& deadline) {
216     CompletionQueueTLSCache cache = CompletionQueueTLSCache(this);
217     f();
218     if (cache.Flush(tag, ok)) {
219       return GOT_EVENT;
220     } else {
221       return AsyncNext(tag, ok, deadline);
222     }
223   }
224
225   /// Request the shutdown of the queue.
226   ///
227   /// \warning This method must be called at some point if this completion queue
228   /// is accessed with Next or AsyncNext. \a Next will not return false
229   /// until this method has been called and all pending tags have been drained.
230   /// (Likewise for \a AsyncNext returning \a NextStatus::SHUTDOWN .)
231   /// Only once either one of these methods does that (that is, once the queue
232   /// has been \em drained) can an instance of this class be destroyed.
233   /// Also note that applications must ensure that no work is enqueued on this
234   /// completion queue after this method is called.
235   void Shutdown();
236
237   /// Returns a \em raw pointer to the underlying \a grpc_completion_queue
238   /// instance.
239   ///
240   /// \warning Remember that the returned instance is owned. No transfer of
241   /// owership is performed.
242   grpc_completion_queue* cq() { return cq_; }
243
244  protected:
245   /// Private constructor of CompletionQueue only visible to friend classes
246   CompletionQueue(const grpc_completion_queue_attributes& attributes) {
247     cq_ = ::grpc::g_core_codegen_interface->grpc_completion_queue_create(
248         ::grpc::g_core_codegen_interface->grpc_completion_queue_factory_lookup(
249             &attributes),
250         &attributes, NULL);
251     InitialAvalanching();  // reserve this for the future shutdown
252   }
253
254  private:
255   // Friend synchronous wrappers so that they can access Pluck(), which is
256   // a semi-private API geared towards the synchronous implementation.
257   template <class R>
258   friend class ::grpc::ClientReader;
259   template <class W>
260   friend class ::grpc::ClientWriter;
261   template <class W, class R>
262   friend class ::grpc::ClientReaderWriter;
263   template <class R>
264   friend class ::grpc::ServerReader;
265   template <class W>
266   friend class ::grpc::ServerWriter;
267   template <class W, class R>
268   friend class ::grpc::internal::ServerReaderWriterBody;
269   template <class ServiceType, class RequestType, class ResponseType>
270   friend class ::grpc::internal::RpcMethodHandler;
271   template <class ServiceType, class RequestType, class ResponseType>
272   friend class ::grpc::internal::ClientStreamingHandler;
273   template <class ServiceType, class RequestType, class ResponseType>
274   friend class ::grpc::internal::ServerStreamingHandler;
275   template <class Streamer, bool WriteNeeded>
276   friend class ::grpc::internal::TemplatedBidiStreamingHandler;
277   template <::grpc::StatusCode code>
278   friend class ::grpc::internal::ErrorMethodHandler;
279   friend class ::grpc_impl::Server;
280   friend class ::grpc_impl::ServerContext;
281   friend class ::grpc::ServerInterface;
282   template <class InputMessage, class OutputMessage>
283   friend class ::grpc::internal::BlockingUnaryCallImpl;
284
285   // Friends that need access to constructor for callback CQ
286   friend class ::grpc_impl::Channel;
287
288   // For access to Register/CompleteAvalanching
289   template <class Op1, class Op2, class Op3, class Op4, class Op5, class Op6>
290   friend class ::grpc::internal::CallOpSet;
291
292   /// EXPERIMENTAL
293   /// Creates a Thread Local cache to store the first event
294   /// On this completion queue queued from this thread.  Once
295   /// initialized, it must be flushed on the same thread.
296   class CompletionQueueTLSCache {
297    public:
298     CompletionQueueTLSCache(CompletionQueue* cq);
299     ~CompletionQueueTLSCache();
300     bool Flush(void** tag, bool* ok);
301
302    private:
303     CompletionQueue* cq_;
304     bool flushed_;
305   };
306
307   NextStatus AsyncNextInternal(void** tag, bool* ok, gpr_timespec deadline);
308
309   /// Wraps \a grpc_completion_queue_pluck.
310   /// \warning Must not be mixed with calls to \a Next.
311   bool Pluck(::grpc::internal::CompletionQueueTag* tag) {
312     auto deadline =
313         ::grpc::g_core_codegen_interface->gpr_inf_future(GPR_CLOCK_REALTIME);
314     while (true) {
315       auto ev = ::grpc::g_core_codegen_interface->grpc_completion_queue_pluck(
316           cq_, tag, deadline, nullptr);
317       bool ok = ev.success != 0;
318       void* ignored = tag;
319       if (tag->FinalizeResult(&ignored, &ok)) {
320         GPR_CODEGEN_ASSERT(ignored == tag);
321         return ok;
322       }
323     }
324   }
325
326   /// Performs a single polling pluck on \a tag.
327   /// \warning Must not be mixed with calls to \a Next.
328   ///
329   /// TODO: sreek - This calls tag->FinalizeResult() even if the cq_ is already
330   /// shutdown. This is most likely a bug and if it is a bug, then change this
331   /// implementation to simple call the other TryPluck function with a zero
332   /// timeout. i.e:
333   ///      TryPluck(tag, gpr_time_0(GPR_CLOCK_REALTIME))
334   void TryPluck(::grpc::internal::CompletionQueueTag* tag) {
335     auto deadline =
336         ::grpc::g_core_codegen_interface->gpr_time_0(GPR_CLOCK_REALTIME);
337     auto ev = ::grpc::g_core_codegen_interface->grpc_completion_queue_pluck(
338         cq_, tag, deadline, nullptr);
339     if (ev.type == GRPC_QUEUE_TIMEOUT) return;
340     bool ok = ev.success != 0;
341     void* ignored = tag;
342     // the tag must be swallowed if using TryPluck
343     GPR_CODEGEN_ASSERT(!tag->FinalizeResult(&ignored, &ok));
344   }
345
346   /// Performs a single polling pluck on \a tag. Calls tag->FinalizeResult if
347   /// the pluck() was successful and returned the tag.
348   ///
349   /// This exects tag->FinalizeResult (if called) to return 'false' i.e expects
350   /// that the tag is internal not something that is returned to the user.
351   void TryPluck(::grpc::internal::CompletionQueueTag* tag,
352                 gpr_timespec deadline) {
353     auto ev = ::grpc::g_core_codegen_interface->grpc_completion_queue_pluck(
354         cq_, tag, deadline, nullptr);
355     if (ev.type == GRPC_QUEUE_TIMEOUT || ev.type == GRPC_QUEUE_SHUTDOWN) {
356       return;
357     }
358
359     bool ok = ev.success != 0;
360     void* ignored = tag;
361     GPR_CODEGEN_ASSERT(!tag->FinalizeResult(&ignored, &ok));
362   }
363
364   /// Manage state of avalanching operations : completion queue tags that
365   /// trigger other completion queue operations. The underlying core completion
366   /// queue should not really shutdown until all avalanching operations have
367   /// been finalized. Note that we maintain the requirement that an avalanche
368   /// registration must take place before CQ shutdown (which must be maintained
369   /// elsehwere)
370   void InitialAvalanching() {
371     gpr_atm_rel_store(&avalanches_in_flight_, static_cast<gpr_atm>(1));
372   }
373   void RegisterAvalanching() {
374     gpr_atm_no_barrier_fetch_add(&avalanches_in_flight_,
375                                  static_cast<gpr_atm>(1));
376   }
377   void CompleteAvalanching() {
378     if (gpr_atm_no_barrier_fetch_add(&avalanches_in_flight_,
379                                      static_cast<gpr_atm>(-1)) == 1) {
380       ::grpc::g_core_codegen_interface->grpc_completion_queue_shutdown(cq_);
381     }
382   }
383
384   grpc_completion_queue* cq_;  // owned
385
386   gpr_atm avalanches_in_flight_;
387 };
388
389 /// A specific type of completion queue used by the processing of notifications
390 /// by servers. Instantiated by \a ServerBuilder.
391 class ServerCompletionQueue : public CompletionQueue {
392  public:
393   bool IsFrequentlyPolled() { return polling_type_ != GRPC_CQ_NON_LISTENING; }
394
395  protected:
396   /// Default constructor
397   ServerCompletionQueue() : polling_type_(GRPC_CQ_DEFAULT_POLLING) {}
398
399  private:
400   /// \param completion_type indicates whether this is a NEXT or CALLBACK
401   /// completion queue.
402   /// \param polling_type Informs the GRPC library about the type of polling
403   /// allowed on this completion queue. See grpc_cq_polling_type's description
404   /// in grpc_types.h for more details.
405   /// \param shutdown_cb is the shutdown callback used for CALLBACK api queues
406   ServerCompletionQueue(grpc_cq_completion_type completion_type,
407                         grpc_cq_polling_type polling_type,
408                         grpc_experimental_completion_queue_functor* shutdown_cb)
409       : CompletionQueue(grpc_completion_queue_attributes{
410             GRPC_CQ_CURRENT_VERSION, completion_type, polling_type,
411             shutdown_cb}),
412         polling_type_(polling_type) {}
413
414   grpc_cq_polling_type polling_type_;
415   friend class ::grpc_impl::ServerBuilder;
416   friend class ::grpc_impl::Server;
417 };
418
419 }  // namespace grpc_impl
420
421 #endif  // GRPCPP_IMPL_CODEGEN_COMPLETION_QUEUE_IMPL_H