591a9ff954900123a222a3c6e968b2ce4c34d70d
[platform/upstream/grpc.git] / include / grpcpp / impl / codegen / server_context.h
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 #ifndef GRPCPP_IMPL_CODEGEN_SERVER_CONTEXT_H
20 #define GRPCPP_IMPL_CODEGEN_SERVER_CONTEXT_H
21
22 #include <map>
23 #include <memory>
24 #include <vector>
25
26 #include <grpc/impl/codegen/compression_types.h>
27
28 #include <grpcpp/impl/codegen/call.h>
29 #include <grpcpp/impl/codegen/call_op_set.h>
30 #include <grpcpp/impl/codegen/callback_common.h>
31 #include <grpcpp/impl/codegen/completion_queue_tag.h>
32 #include <grpcpp/impl/codegen/config.h>
33 #include <grpcpp/impl/codegen/create_auth_context.h>
34 #include <grpcpp/impl/codegen/metadata_map.h>
35 #include <grpcpp/impl/codegen/security/auth_context.h>
36 #include <grpcpp/impl/codegen/server_interceptor.h>
37 #include <grpcpp/impl/codegen/string_ref.h>
38 #include <grpcpp/impl/codegen/time.h>
39
40 struct grpc_metadata;
41 struct grpc_call;
42 struct census_context;
43
44 namespace grpc {
45 class ClientContext;
46 class GenericServerContext;
47 class CompletionQueue;
48 class Server;
49 class ServerInterface;
50 template <class W, class R>
51 class ServerAsyncReader;
52 template <class W>
53 class ServerAsyncWriter;
54 template <class W>
55 class ServerAsyncResponseWriter;
56 template <class W, class R>
57 class ServerAsyncReaderWriter;
58 template <class R>
59 class ServerReader;
60 template <class W>
61 class ServerWriter;
62
63 namespace internal {
64 template <class W, class R>
65 class ServerReaderWriterBody;
66 template <class ServiceType, class RequestType, class ResponseType>
67 class RpcMethodHandler;
68 template <class ServiceType, class RequestType, class ResponseType>
69 class ClientStreamingHandler;
70 template <class ServiceType, class RequestType, class ResponseType>
71 class ServerStreamingHandler;
72 template <class ServiceType, class RequestType, class ResponseType>
73 class BidiStreamingHandler;
74 template <class RequestType, class ResponseType>
75 class CallbackUnaryHandler;
76 template <class RequestType, class ResponseType>
77 class CallbackClientStreamingHandler;
78 template <class RequestType, class ResponseType>
79 class CallbackServerStreamingHandler;
80 template <class RequestType, class ResponseType>
81 class CallbackBidiHandler;
82 template <class Streamer, bool WriteNeeded>
83 class TemplatedBidiStreamingHandler;
84 template <StatusCode code>
85 class ErrorMethodHandler;
86 class Call;
87 class ServerReactor;
88 }  // namespace internal
89
90 namespace testing {
91 class InteropServerContextInspector;
92 class ServerContextTestSpouse;
93 }  // namespace testing
94
95 /// A ServerContext allows the person implementing a service handler to:
96 ///
97 /// - Add custom initial and trailing metadata key-value pairs that will
98 ///   propagated to the client side.
99 /// - Control call settings such as compression and authentication.
100 /// - Access metadata coming from the client.
101 /// - Get performance metrics (ie, census).
102 ///
103 /// Context settings are only relevant to the call handler they are supplied to,
104 /// that is to say, they aren't sticky across multiple calls. Some of these
105 /// settings, such as the compression options, can be made persistent at server
106 /// construction time by specifying the appropriate \a ChannelArguments
107 /// to a \a grpc::ServerBuilder, via \a ServerBuilder::AddChannelArgument.
108 ///
109 /// \warning ServerContext instances should \em not be reused across rpcs.
110 class ServerContext {
111  public:
112   ServerContext();  // for async calls
113   ~ServerContext();
114
115   /// Return the deadline for the server call.
116   std::chrono::system_clock::time_point deadline() const {
117     return Timespec2Timepoint(deadline_);
118   }
119
120   /// Return a \a gpr_timespec representation of the server call's deadline.
121   gpr_timespec raw_deadline() const { return deadline_; }
122
123   /// Add the (\a key, \a value) pair to the initial metadata
124   /// associated with a server call. These are made available at the client side
125   /// by the \a grpc::ClientContext::GetServerInitialMetadata() method.
126   ///
127   /// \warning This method should only be called before sending initial metadata
128   /// to the client (which can happen explicitly, or implicitly when sending a
129   /// a response message or status to the client).
130   ///
131   /// \param key The metadata key. If \a value is binary data, it must
132   /// end in "-bin".
133   /// \param value The metadata value. If its value is binary, the key name
134   /// must end in "-bin".
135   ///
136   /// Metadata must conform to the following format:
137   /// Custom-Metadata -> Binary-Header / ASCII-Header
138   /// Binary-Header -> {Header-Name "-bin" } {binary value}
139   /// ASCII-Header -> Header-Name ASCII-Value
140   /// Header-Name -> 1*( %x30-39 / %x61-7A / "_" / "-" / ".") ; 0-9 a-z _ - .
141   /// ASCII-Value -> 1*( %x20-%x7E ) ; space and printable ASCII
142   void AddInitialMetadata(const grpc::string& key, const grpc::string& value);
143
144   /// Add the (\a key, \a value) pair to the initial metadata
145   /// associated with a server call. These are made available at the client
146   /// side by the \a grpc::ClientContext::GetServerTrailingMetadata() method.
147   ///
148   /// \warning This method should only be called before sending trailing
149   /// metadata to the client (which happens when the call is finished and a
150   /// status is sent to the client).
151   ///
152   /// \param key The metadata key. If \a value is binary data,
153   /// it must end in "-bin".
154   /// \param value The metadata value. If its value is binary, the key name
155   /// must end in "-bin".
156   ///
157   /// Metadata must conform to the following format:
158   /// Custom-Metadata -> Binary-Header / ASCII-Header
159   /// Binary-Header -> {Header-Name "-bin" } {binary value}
160   /// ASCII-Header -> Header-Name ASCII-Value
161   /// Header-Name -> 1*( %x30-39 / %x61-7A / "_" / "-" / ".") ; 0-9 a-z _ - .
162   /// ASCII-Value -> 1*( %x20-%x7E ) ; space and printable ASCII
163   void AddTrailingMetadata(const grpc::string& key, const grpc::string& value);
164
165   /// IsCancelled is always safe to call when using sync or callback API.
166   /// When using async API, it is only safe to call IsCancelled after
167   /// the AsyncNotifyWhenDone tag has been delivered.
168   bool IsCancelled() const;
169
170   /// Cancel the Call from the server. This is a best-effort API and
171   /// depending on when it is called, the RPC may still appear successful to
172   /// the client.
173   /// For example, if TryCancel() is called on a separate thread, it might race
174   /// with the server handler which might return success to the client before
175   /// TryCancel() was even started by the thread.
176   ///
177   /// It is the caller's responsibility to prevent such races and ensure that if
178   /// TryCancel() is called, the serverhandler must return Status::CANCELLED.
179   /// The only exception is that if the serverhandler is already returning an
180   /// error status code, it is ok to not return Status::CANCELLED even if
181   /// TryCancel() was called.
182   ///
183   /// Note that TryCancel() does not change any of the tags that are pending
184   /// on the completion queue. All pending tags will still be delivered
185   /// (though their ok result may reflect the effect of cancellation).
186   void TryCancel() const;
187
188   /// Return a collection of initial metadata key-value pairs sent from the
189   /// client. Note that keys may happen more than
190   /// once (ie, a \a std::multimap is returned).
191   ///
192   /// It is safe to use this method after initial metadata has been received,
193   /// Calls always begin with the client sending initial metadata, so this is
194   /// safe to access as soon as the call has begun on the server side.
195   ///
196   /// \return A multimap of initial metadata key-value pairs from the server.
197   const std::multimap<grpc::string_ref, grpc::string_ref>& client_metadata()
198       const {
199     return *client_metadata_.map();
200   }
201
202   /// Return the compression algorithm to be used by the server call.
203   grpc_compression_level compression_level() const {
204     return compression_level_;
205   }
206
207   /// Set \a level to be the compression level used for the server call.
208   ///
209   /// \param level The compression level used for the server call.
210   void set_compression_level(grpc_compression_level level) {
211     compression_level_set_ = true;
212     compression_level_ = level;
213   }
214
215   /// Return a bool indicating whether the compression level for this call
216   /// has been set (either implicitly or through a previous call to
217   /// \a set_compression_level.
218   bool compression_level_set() const { return compression_level_set_; }
219
220   /// Return the compression algorithm the server call will request be used.
221   /// Note that the gRPC runtime may decide to ignore this request, for example,
222   /// due to resource constraints, or if the server is aware the client doesn't
223   /// support the requested algorithm.
224   grpc_compression_algorithm compression_algorithm() const {
225     return compression_algorithm_;
226   }
227   /// Set \a algorithm to be the compression algorithm used for the server call.
228   ///
229   /// \param algorithm The compression algorithm used for the server call.
230   void set_compression_algorithm(grpc_compression_algorithm algorithm);
231
232   /// Set the serialized load reporting costs in \a cost_data for the call.
233   void SetLoadReportingCosts(const std::vector<grpc::string>& cost_data);
234
235   /// Return the authentication context for this server call.
236   ///
237   /// \see grpc::AuthContext.
238   std::shared_ptr<const AuthContext> auth_context() const {
239     if (auth_context_.get() == nullptr) {
240       auth_context_ = CreateAuthContext(call_);
241     }
242     return auth_context_;
243   }
244
245   /// Return the peer uri in a string.
246   /// WARNING: this value is never authenticated or subject to any security
247   /// related code. It must not be used for any authentication related
248   /// functionality. Instead, use auth_context.
249   grpc::string peer() const;
250
251   /// Get the census context associated with this server call.
252   const struct census_context* census_context() const;
253
254   /// Async only. Has to be called before the rpc starts.
255   /// Returns the tag in completion queue when the rpc finishes.
256   /// IsCancelled() can then be called to check whether the rpc was cancelled.
257   /// TODO(vjpai): Fix this so that the tag is returned even if the call never
258   /// starts (https://github.com/grpc/grpc/issues/10136).
259   void AsyncNotifyWhenDone(void* tag) {
260     has_notify_when_done_tag_ = true;
261     async_notify_when_done_tag_ = tag;
262   }
263
264   /// Should be used for framework-level extensions only.
265   /// Applications never need to call this method.
266   grpc_call* c_call() { return call_; }
267
268  private:
269   friend class ::grpc::testing::InteropServerContextInspector;
270   friend class ::grpc::testing::ServerContextTestSpouse;
271   friend class ::grpc::ServerInterface;
272   friend class ::grpc::Server;
273   template <class W, class R>
274   friend class ::grpc::ServerAsyncReader;
275   template <class W>
276   friend class ::grpc::ServerAsyncWriter;
277   template <class W>
278   friend class ::grpc::ServerAsyncResponseWriter;
279   template <class W, class R>
280   friend class ::grpc::ServerAsyncReaderWriter;
281   template <class R>
282   friend class ::grpc::ServerReader;
283   template <class W>
284   friend class ::grpc::ServerWriter;
285   template <class W, class R>
286   friend class ::grpc::internal::ServerReaderWriterBody;
287   template <class ServiceType, class RequestType, class ResponseType>
288   friend class ::grpc::internal::RpcMethodHandler;
289   template <class ServiceType, class RequestType, class ResponseType>
290   friend class ::grpc::internal::ClientStreamingHandler;
291   template <class ServiceType, class RequestType, class ResponseType>
292   friend class ::grpc::internal::ServerStreamingHandler;
293   template <class Streamer, bool WriteNeeded>
294   friend class ::grpc::internal::TemplatedBidiStreamingHandler;
295   template <class RequestType, class ResponseType>
296   friend class ::grpc::internal::CallbackUnaryHandler;
297   template <class RequestType, class ResponseType>
298   friend class ::grpc::internal::CallbackClientStreamingHandler;
299   template <class RequestType, class ResponseType>
300   friend class ::grpc::internal::CallbackServerStreamingHandler;
301   template <class RequestType, class ResponseType>
302   friend class ::grpc::internal::CallbackBidiHandler;
303   template <StatusCode code>
304   friend class internal::ErrorMethodHandler;
305   friend class ::grpc::ClientContext;
306   friend class ::grpc::GenericServerContext;
307
308   /// Prevent copying.
309   ServerContext(const ServerContext&);
310   ServerContext& operator=(const ServerContext&);
311
312   class CompletionOp;
313
314   void BeginCompletionOp(internal::Call* call,
315                          std::function<void(bool)> callback,
316                          internal::ServerReactor* reactor);
317   /// Return the tag queued by BeginCompletionOp()
318   internal::CompletionQueueTag* GetCompletionOpTag();
319
320   ServerContext(gpr_timespec deadline, grpc_metadata_array* arr);
321
322   void set_call(grpc_call* call) { call_ = call; }
323
324   void BindDeadlineAndMetadata(gpr_timespec deadline, grpc_metadata_array* arr);
325
326   void Clear();
327
328   void Setup(gpr_timespec deadline);
329
330   uint32_t initial_metadata_flags() const { return 0; }
331
332   void SetCancelCallback(std::function<void()> callback);
333   void ClearCancelCallback();
334
335   experimental::ServerRpcInfo* set_server_rpc_info(
336       const char* method, internal::RpcMethod::RpcType type,
337       const std::vector<
338           std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>&
339           creators) {
340     if (creators.size() != 0) {
341       rpc_info_ = new experimental::ServerRpcInfo(this, method, type);
342       rpc_info_->RegisterInterceptors(creators);
343     }
344     return rpc_info_;
345   }
346
347   CompletionOp* completion_op_;
348   bool has_notify_when_done_tag_;
349   void* async_notify_when_done_tag_;
350   internal::CallbackWithSuccessTag completion_tag_;
351
352   gpr_timespec deadline_;
353   grpc_call* call_;
354   CompletionQueue* cq_;
355   bool sent_initial_metadata_;
356   mutable std::shared_ptr<const AuthContext> auth_context_;
357   mutable internal::MetadataMap client_metadata_;
358   std::multimap<grpc::string, grpc::string> initial_metadata_;
359   std::multimap<grpc::string, grpc::string> trailing_metadata_;
360
361   bool compression_level_set_;
362   grpc_compression_level compression_level_;
363   grpc_compression_algorithm compression_algorithm_;
364
365   internal::CallOpSet<internal::CallOpSendInitialMetadata,
366                       internal::CallOpSendMessage>
367       pending_ops_;
368   bool has_pending_ops_;
369
370   experimental::ServerRpcInfo* rpc_info_;
371 };
372
373 }  // namespace grpc
374
375 #endif  // GRPCPP_IMPL_CODEGEN_SERVER_CONTEXT_H