xref: /aosp_15_r20/external/grpc-grpc/include/grpcpp/completion_queue.h (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
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 
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_COMPLETION_QUEUE_H
33 #define GRPCPP_COMPLETION_QUEUE_H
34 
35 #include <list>
36 
37 #include <grpc/grpc.h>
38 #include <grpc/support/atm.h>
39 #include <grpc/support/log.h>
40 #include <grpc/support/time.h>
41 #include <grpcpp/impl/codegen/rpc_service_method.h>
42 #include <grpcpp/impl/codegen/status.h>
43 #include <grpcpp/impl/codegen/sync.h>
44 #include <grpcpp/impl/codegen/time.h>
45 #include <grpcpp/impl/completion_queue_tag.h>
46 #include <grpcpp/impl/grpc_library.h>
47 #include <grpcpp/impl/sync.h>
48 
49 struct grpc_completion_queue;
50 
51 namespace grpc {
52 template <class R>
53 class ClientReader;
54 template <class W>
55 class ClientWriter;
56 template <class W, class R>
57 class ClientReaderWriter;
58 template <class R>
59 class ServerReader;
60 template <class W>
61 class ServerWriter;
62 namespace internal {
63 template <class W, class R>
64 class ServerReaderWriterBody;
65 
66 template <class ResponseType>
67 void UnaryRunHandlerHelper(
68     const grpc::internal::MethodHandler::HandlerParameter&, ResponseType*,
69     grpc::Status&);
70 template <class ServiceType, class RequestType, class ResponseType,
71           class BaseRequestType, class BaseResponseType>
72 class RpcMethodHandler;
73 template <class ServiceType, class RequestType, class ResponseType>
74 class ClientStreamingHandler;
75 template <class ServiceType, class RequestType, class ResponseType>
76 class ServerStreamingHandler;
77 template <class Streamer, bool WriteNeeded>
78 class TemplatedBidiStreamingHandler;
79 template <grpc::StatusCode code>
80 class ErrorMethodHandler;
81 }  // namespace internal
82 
83 class Channel;
84 class ChannelInterface;
85 class Server;
86 class ServerBuilder;
87 class ServerContextBase;
88 class ServerInterface;
89 
90 namespace internal {
91 class CompletionQueueTag;
92 class RpcMethod;
93 template <class InputMessage, class OutputMessage>
94 class BlockingUnaryCallImpl;
95 template <class Op1, class Op2, class Op3, class Op4, class Op5, class Op6>
96 class CallOpSet;
97 }  // namespace internal
98 
99 /// A thin wrapper around \ref grpc_completion_queue (see \ref
100 /// src/core/lib/surface/completion_queue.h).
101 /// See \ref doc/cpp/perf_notes.md for notes on best practices for high
102 /// performance servers.
103 class CompletionQueue : private grpc::internal::GrpcLibrary {
104  public:
105   /// Default constructor. Implicitly creates a \a grpc_completion_queue
106   /// instance.
CompletionQueue()107   CompletionQueue()
108       : CompletionQueue(grpc_completion_queue_attributes{
109             GRPC_CQ_CURRENT_VERSION, GRPC_CQ_NEXT, GRPC_CQ_DEFAULT_POLLING,
110             nullptr}) {}
111 
112   /// Wrap \a take, taking ownership of the instance.
113   ///
114   /// \param take The completion queue instance to wrap. Ownership is taken.
115   explicit CompletionQueue(grpc_completion_queue* take);
116 
117   /// Destructor. Destroys the owned wrapped completion queue / instance.
~CompletionQueue()118   ~CompletionQueue() override { grpc_completion_queue_destroy(cq_); }
119 
120   /// Tri-state return for AsyncNext: SHUTDOWN, GOT_EVENT, TIMEOUT.
121   enum NextStatus {
122     SHUTDOWN,   ///< The completion queue has been shutdown and fully-drained
123     GOT_EVENT,  ///< Got a new event; \a tag will be filled in with its
124                 ///< associated value; \a ok indicating its success.
125     TIMEOUT     ///< deadline was reached.
126   };
127 
128   /// Read from the queue, blocking until an event is available or the queue is
129   /// shutting down.
130   ///
131   /// \param[out] tag Updated to point to the read event's tag.
132   /// \param[out] ok true if read a successful event, false otherwise.
133   ///
134   /// Note that each tag sent to the completion queue (through RPC operations
135   /// or alarms) will be delivered out of the completion queue by a call to
136   /// Next (or a related method), regardless of whether the operation succeeded
137   /// or not. Success here means that this operation completed in the normal
138   /// valid manner.
139   ///
140   /// Server-side RPC request: \a ok indicates that the RPC has indeed
141   /// been started. If it is false, the server has been Shutdown
142   /// before this particular call got matched to an incoming RPC.
143   ///
144   /// Client-side StartCall/RPC invocation: \a ok indicates that the RPC is
145   /// going to go to the wire. If it is false, it not going to the wire. This
146   /// would happen if the channel is either permanently broken or
147   /// transiently broken but with the fail-fast option. (Note that async unary
148   /// RPCs don't post a CQ tag at this point, nor do client-streaming
149   /// or bidi-streaming RPCs that have the initial metadata corked option set.)
150   ///
151   /// Client-side Write, Client-side WritesDone, Server-side Write,
152   /// Server-side Finish, Server-side SendInitialMetadata (which is
153   /// typically included in Write or Finish when not done explicitly):
154   /// \a ok means that the data/metadata/status/etc is going to go to the
155   /// wire. If it is false, it not going to the wire because the call
156   /// is already dead (i.e., canceled, deadline expired, other side
157   /// dropped the channel, etc).
158   ///
159   /// Client-side Read, Server-side Read, Client-side
160   /// RecvInitialMetadata (which is typically included in Read if not
161   /// done explicitly): \a ok indicates whether there is a valid message
162   /// that got read. If not, you know that there are certainly no more
163   /// messages that can ever be read from this stream. For the client-side
164   /// operations, this only happens because the call is dead. For the
165   /// server-sider operation, though, this could happen because the client
166   /// has done a WritesDone already.
167   ///
168   /// Client-side Finish: \a ok should always be true
169   ///
170   /// Server-side AsyncNotifyWhenDone: \a ok should always be true
171   ///
172   /// Alarm: \a ok is true if it expired, false if it was canceled
173   ///
174   /// \return true if got an event, false if the queue is fully drained and
175   ///         shut down.
Next(void ** tag,bool * ok)176   bool Next(void** tag, bool* ok) {
177     // Check return type == GOT_EVENT... cases:
178     // SHUTDOWN  - queue has been shutdown, return false.
179     // TIMEOUT   - we passed infinity time => queue has been shutdown, return
180     //             false.
181     // GOT_EVENT - we actually got an event, return true.
182     return (AsyncNextInternal(tag, ok, gpr_inf_future(GPR_CLOCK_REALTIME)) ==
183             GOT_EVENT);
184   }
185 
186   /// Read from the queue, blocking up to \a deadline (or the queue's shutdown).
187   /// Both \a tag and \a ok are updated upon success (if an event is available
188   /// within the \a deadline).  A \a tag points to an arbitrary location usually
189   /// employed to uniquely identify an event.
190   ///
191   /// \param[out] tag Upon success, updated to point to the event's tag.
192   /// \param[out] ok Upon success, true if a successful event, false otherwise
193   ///        See documentation for CompletionQueue::Next for explanation of ok
194   /// \param[in] deadline How long to block in wait for an event.
195   ///
196   /// \return The type of event read.
197   template <typename T>
AsyncNext(void ** tag,bool * ok,const T & deadline)198   NextStatus AsyncNext(void** tag, bool* ok, const T& deadline) {
199     grpc::TimePoint<T> deadline_tp(deadline);
200     return AsyncNextInternal(tag, ok, deadline_tp.raw_time());
201   }
202 
203   /// EXPERIMENTAL
204   /// First executes \a F, then reads from the queue, blocking up to
205   /// \a deadline (or the queue's shutdown).
206   /// Both \a tag and \a ok are updated upon success (if an event is available
207   /// within the \a deadline).  A \a tag points to an arbitrary location usually
208   /// employed to uniquely identify an event.
209   ///
210   /// \param[in] f Function to execute before calling AsyncNext on this queue.
211   /// \param[out] tag Upon success, updated to point to the event's tag.
212   /// \param[out] ok Upon success, true if read a regular event, false
213   /// otherwise.
214   /// \param[in] deadline How long to block in wait for an event.
215   ///
216   /// \return The type of event read.
217   template <typename T, typename F>
DoThenAsyncNext(F && f,void ** tag,bool * ok,const T & deadline)218   NextStatus DoThenAsyncNext(F&& f, void** tag, bool* ok, const T& deadline) {
219     CompletionQueueTLSCache cache = CompletionQueueTLSCache(this);
220     f();
221     if (cache.Flush(tag, ok)) {
222       return GOT_EVENT;
223     } else {
224       return AsyncNext(tag, ok, deadline);
225     }
226   }
227 
228   /// Request the shutdown of the queue.
229   ///
230   /// \warning This method must be called at some point if this completion queue
231   /// is accessed with Next or AsyncNext. \a Next will not return false
232   /// until this method has been called and all pending tags have been drained.
233   /// (Likewise for \a AsyncNext returning \a NextStatus::SHUTDOWN .)
234   /// Only once either one of these methods does that (that is, once the queue
235   /// has been \em drained) can an instance of this class be destroyed.
236   /// Also note that applications must ensure that no work is enqueued on this
237   /// completion queue after this method is called.
238   void Shutdown();
239 
240   /// Returns a \em raw pointer to the underlying \a grpc_completion_queue
241   /// instance.
242   ///
243   /// \warning Remember that the returned instance is owned. No transfer of
244   /// ownership is performed.
cq()245   grpc_completion_queue* cq() { return cq_; }
246 
247  protected:
248   /// Private constructor of CompletionQueue only visible to friend classes
CompletionQueue(const grpc_completion_queue_attributes & attributes)249   explicit CompletionQueue(const grpc_completion_queue_attributes& attributes) {
250     cq_ = grpc_completion_queue_create(
251         grpc_completion_queue_factory_lookup(&attributes), &attributes,
252         nullptr);
253     InitialAvalanching();  // reserve this for the future shutdown
254   }
255 
256  private:
257   // Friends for access to server registration lists that enable checking and
258   // logging on shutdown
259   friend class grpc::ServerBuilder;
260   friend class grpc::Server;
261 
262   // Friend synchronous wrappers so that they can access Pluck(), which is
263   // a semi-private API geared towards the synchronous implementation.
264   template <class R>
265   friend class grpc::ClientReader;
266   template <class W>
267   friend class grpc::ClientWriter;
268   template <class W, class R>
269   friend class grpc::ClientReaderWriter;
270   template <class R>
271   friend class grpc::ServerReader;
272   template <class W>
273   friend class grpc::ServerWriter;
274   template <class W, class R>
275   friend class grpc::internal::ServerReaderWriterBody;
276   template <class ResponseType>
277   friend void grpc::internal::UnaryRunHandlerHelper(
278       const grpc::internal::MethodHandler::HandlerParameter&, ResponseType*,
279       grpc::Status&);
280   template <class ServiceType, class RequestType, class ResponseType>
281   friend class grpc::internal::ClientStreamingHandler;
282   template <class ServiceType, class RequestType, class ResponseType>
283   friend class grpc::internal::ServerStreamingHandler;
284   template <class Streamer, bool WriteNeeded>
285   friend class grpc::internal::TemplatedBidiStreamingHandler;
286   template <grpc::StatusCode code>
287   friend class grpc::internal::ErrorMethodHandler;
288   friend class grpc::ServerContextBase;
289   friend class grpc::ServerInterface;
290   template <class InputMessage, class OutputMessage>
291   friend class grpc::internal::BlockingUnaryCallImpl;
292 
293   // Friends that need access to constructor for callback CQ
294   friend class grpc::Channel;
295 
296   // For access to Register/CompleteAvalanching
297   template <class Op1, class Op2, class Op3, class Op4, class Op5, class Op6>
298   friend class grpc::internal::CallOpSet;
299 
300   /// EXPERIMENTAL
301   /// Creates a Thread Local cache to store the first event
302   /// On this completion queue queued from this thread.  Once
303   /// initialized, it must be flushed on the same thread.
304   class CompletionQueueTLSCache {
305    public:
306     explicit CompletionQueueTLSCache(CompletionQueue* cq);
307     ~CompletionQueueTLSCache();
308     bool Flush(void** tag, bool* ok);
309 
310    private:
311     CompletionQueue* cq_;
312     bool flushed_;
313   };
314 
315   NextStatus AsyncNextInternal(void** tag, bool* ok, gpr_timespec deadline);
316 
317   /// Wraps \a grpc_completion_queue_pluck.
318   /// \warning Must not be mixed with calls to \a Next.
Pluck(grpc::internal::CompletionQueueTag * tag)319   bool Pluck(grpc::internal::CompletionQueueTag* tag) {
320     auto deadline = gpr_inf_future(GPR_CLOCK_REALTIME);
321     while (true) {
322       auto ev = grpc_completion_queue_pluck(cq_, tag, deadline, nullptr);
323       bool ok = ev.success != 0;
324       void* ignored = tag;
325       if (tag->FinalizeResult(&ignored, &ok)) {
326         GPR_ASSERT(ignored == tag);
327         return ok;
328       }
329     }
330   }
331 
332   /// Performs a single polling pluck on \a tag.
333   /// \warning Must not be mixed with calls to \a Next.
334   ///
335   /// TODO: sreek - This calls tag->FinalizeResult() even if the cq_ is already
336   /// shutdown. This is most likely a bug and if it is a bug, then change this
337   /// implementation to simple call the other TryPluck function with a zero
338   /// timeout. i.e:
339   ///      TryPluck(tag, gpr_time_0(GPR_CLOCK_REALTIME))
TryPluck(grpc::internal::CompletionQueueTag * tag)340   void TryPluck(grpc::internal::CompletionQueueTag* tag) {
341     auto deadline = gpr_time_0(GPR_CLOCK_REALTIME);
342     auto ev = grpc_completion_queue_pluck(cq_, tag, deadline, nullptr);
343     if (ev.type == GRPC_QUEUE_TIMEOUT) return;
344     bool ok = ev.success != 0;
345     void* ignored = tag;
346     // the tag must be swallowed if using TryPluck
347     GPR_ASSERT(!tag->FinalizeResult(&ignored, &ok));
348   }
349 
350   /// Performs a single polling pluck on \a tag. Calls tag->FinalizeResult if
351   /// the pluck() was successful and returned the tag.
352   ///
353   /// This exects tag->FinalizeResult (if called) to return 'false' i.e expects
354   /// that the tag is internal not something that is returned to the user.
TryPluck(grpc::internal::CompletionQueueTag * tag,gpr_timespec deadline)355   void TryPluck(grpc::internal::CompletionQueueTag* tag,
356                 gpr_timespec deadline) {
357     auto ev = grpc_completion_queue_pluck(cq_, tag, deadline, nullptr);
358     if (ev.type == GRPC_QUEUE_TIMEOUT || ev.type == GRPC_QUEUE_SHUTDOWN) {
359       return;
360     }
361 
362     bool ok = ev.success != 0;
363     void* ignored = tag;
364     GPR_ASSERT(!tag->FinalizeResult(&ignored, &ok));
365   }
366 
367   /// Manage state of avalanching operations : completion queue tags that
368   /// trigger other completion queue operations. The underlying core completion
369   /// queue should not really shutdown until all avalanching operations have
370   /// been finalized. Note that we maintain the requirement that an avalanche
371   /// registration must take place before CQ shutdown (which must be maintained
372   /// elsewhere)
InitialAvalanching()373   void InitialAvalanching() {
374     gpr_atm_rel_store(&avalanches_in_flight_, gpr_atm{1});
375   }
RegisterAvalanching()376   void RegisterAvalanching() {
377     gpr_atm_no_barrier_fetch_add(&avalanches_in_flight_, gpr_atm{1});
378   }
CompleteAvalanching()379   void CompleteAvalanching() {
380     if (gpr_atm_no_barrier_fetch_add(&avalanches_in_flight_, gpr_atm{-1}) ==
381         1) {
382       grpc_completion_queue_shutdown(cq_);
383     }
384   }
385 
RegisterServer(const grpc::Server * server)386   void RegisterServer(const grpc::Server* server) {
387     (void)server;
388 #ifndef NDEBUG
389     grpc::internal::MutexLock l(&server_list_mutex_);
390     server_list_.push_back(server);
391 #endif
392   }
UnregisterServer(const grpc::Server * server)393   void UnregisterServer(const grpc::Server* server) {
394     (void)server;
395 #ifndef NDEBUG
396     grpc::internal::MutexLock l(&server_list_mutex_);
397     server_list_.remove(server);
398 #endif
399   }
ServerListEmpty()400   bool ServerListEmpty() const {
401 #ifndef NDEBUG
402     grpc::internal::MutexLock l(&server_list_mutex_);
403     return server_list_.empty();
404 #endif
405     return true;
406   }
407 
408   static CompletionQueue* CallbackAlternativeCQ();
409   static void ReleaseCallbackAlternativeCQ(CompletionQueue* cq);
410 
411   grpc_completion_queue* cq_;  // owned
412 
413   gpr_atm avalanches_in_flight_;
414 
415   // List of servers associated with this CQ. Even though this is only used with
416   // NDEBUG, instantiate it in all cases since otherwise the size will be
417   // inconsistent.
418   mutable grpc::internal::Mutex server_list_mutex_;
419   std::list<const grpc::Server*>
420       server_list_ /* GUARDED_BY(server_list_mutex_) */;
421 };
422 
423 /// A specific type of completion queue used by the processing of notifications
424 /// by servers. Instantiated by \a ServerBuilder or Server (for health checker).
425 class ServerCompletionQueue : public CompletionQueue {
426  public:
IsFrequentlyPolled()427   bool IsFrequentlyPolled() { return polling_type_ != GRPC_CQ_NON_LISTENING; }
428 
429  protected:
430   /// Default constructor
ServerCompletionQueue()431   ServerCompletionQueue() : polling_type_(GRPC_CQ_DEFAULT_POLLING) {}
432 
433  private:
434   /// \param completion_type indicates whether this is a NEXT or CALLBACK
435   /// completion queue.
436   /// \param polling_type Informs the GRPC library about the type of polling
437   /// allowed on this completion queue. See grpc_cq_polling_type's description
438   /// in grpc_types.h for more details.
439   /// \param shutdown_cb is the shutdown callback used for CALLBACK api queues
ServerCompletionQueue(grpc_cq_completion_type completion_type,grpc_cq_polling_type polling_type,grpc_completion_queue_functor * shutdown_cb)440   ServerCompletionQueue(grpc_cq_completion_type completion_type,
441                         grpc_cq_polling_type polling_type,
442                         grpc_completion_queue_functor* shutdown_cb)
443       : CompletionQueue(grpc_completion_queue_attributes{
444             GRPC_CQ_CURRENT_VERSION, completion_type, polling_type,
445             shutdown_cb}),
446         polling_type_(polling_type) {}
447 
448   grpc_cq_polling_type polling_type_;
449   friend class grpc::ServerBuilder;
450   friend class grpc::Server;
451 };
452 
453 }  // namespace grpc
454 
455 #endif  // GRPCPP_COMPLETION_QUEUE_H
456