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