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_SERVER_CONTEXT_H
20#define GRPCPP_SERVER_CONTEXT_H
21
22#include <grpc/impl/codegen/port_platform.h>
23
24#include <atomic>
25#include <cassert>
26#include <map>
27#include <memory>
28#include <type_traits>
29#include <vector>
30
31#include <grpc/impl/codegen/compression_types.h>
32#include <grpcpp/impl/call.h>
33#include <grpcpp/impl/call_op_set.h>
34#include <grpcpp/impl/codegen/completion_queue_tag.h>
35#include <grpcpp/impl/codegen/create_auth_context.h>
36#include <grpcpp/impl/codegen/metadata_map.h>
37#include <grpcpp/impl/rpc_service_method.h>
38#include <grpcpp/security/auth_context.h>
39#include <grpcpp/support/callback_common.h>
40#include <grpcpp/support/config.h>
41#include <grpcpp/support/message_allocator.h>
42#include <grpcpp/support/server_callback.h>
43#include <grpcpp/support/server_interceptor.h>
44#include <grpcpp/support/status.h>
45#include <grpcpp/support/string_ref.h>
46#include <grpcpp/support/time.h>
47
48struct grpc_metadata;
49struct grpc_call;
50struct census_context;
51
52namespace grpc {
53template <class W, class R>
54class ServerAsyncReader;
55template <class W>
56class ServerAsyncWriter;
57template <class W>
58class ServerAsyncResponseWriter;
59template <class W, class R>
60class ServerAsyncReaderWriter;
61template <class R>
62class ServerReader;
63template <class W>
64class ServerWriter;
65
66extern CoreCodegenInterface* g_core_codegen_interface;
67
68namespace internal {
69template <class ServiceType, class RequestType, class ResponseType>
70class BidiStreamingHandler;
71template <class RequestType, class ResponseType>
72class CallbackUnaryHandler;
73template <class RequestType, class ResponseType>
74class CallbackClientStreamingHandler;
75template <class RequestType, class ResponseType>
76class CallbackServerStreamingHandler;
77template <class RequestType, class ResponseType>
78class CallbackBidiHandler;
79template <class ServiceType, class RequestType, class ResponseType>
80class ClientStreamingHandler;
81template <class ResponseType>
82void UnaryRunHandlerHelper(const MethodHandler::HandlerParameter&,
83 ResponseType*, Status&);
84template <class ServiceType, class RequestType, class ResponseType,
85 class BaseRequestType, class BaseResponseType>
86class RpcMethodHandler;
87template <class Base>
88class FinishOnlyReactor;
89template <class W, class R>
90class ServerReaderWriterBody;
91template <class ServiceType, class RequestType, class ResponseType>
92class ServerStreamingHandler;
93class ServerReactor;
94template <class Streamer, bool WriteNeeded>
95class TemplatedBidiStreamingHandler;
96template <grpc::StatusCode code>
97class ErrorMethodHandler;
98} // namespace internal
99
100class ClientContext;
101class CompletionQueue;
102class GenericServerContext;
103class Server;
104class ServerInterface;
105class ContextAllocator;
106class GenericCallbackServerContext;
107
108namespace internal {
109class Call;
110} // namespace internal
111
112namespace testing {
113class InteropServerContextInspector;
114class ServerContextTestSpouse;
115class DefaultReactorTestPeer;
116} // namespace testing
117
118namespace experimental {
119class OrcaServerInterceptor;
120class CallMetricRecorder;
121} // namespace experimental
122
123/// Base class of ServerContext.
124class ServerContextBase {
125 public:
126 virtual ~ServerContextBase();
127
128 /// Return the deadline for the server call.
129 std::chrono::system_clock::time_point deadline() const {
130 return grpc::Timespec2Timepoint(t: deadline_);
131 }
132
133 /// Return a \a gpr_timespec representation of the server call's deadline.
134 gpr_timespec raw_deadline() const { return deadline_; }
135
136 /// Add the (\a key, \a value) pair to the initial metadata
137 /// associated with a server call. These are made available at the client side
138 /// by the \a grpc::ClientContext::GetServerInitialMetadata() method.
139 ///
140 /// \warning This method should only be called before sending initial metadata
141 /// to the client (which can happen explicitly, or implicitly when sending a
142 /// a response message or status to the client).
143 ///
144 /// \param key The metadata key. If \a value is binary data, it must
145 /// end in "-bin".
146 /// \param value The metadata value. If its value is binary, the key name
147 /// must end in "-bin".
148 ///
149 /// Metadata must conform to the following format:
150 /**
151 \verbatim
152 Custom-Metadata -> Binary-Header / ASCII-Header
153 Binary-Header -> {Header-Name "-bin" } {binary value}
154 ASCII-Header -> Header-Name ASCII-Value
155 Header-Name -> 1*( %x30-39 / %x61-7A / "_" / "-" / ".") ; 0-9 a-z _ - .
156 ASCII-Value -> 1*( %x20-%x7E ) ; space and printable ASCII
157 \endverbatim
158 **/
159 void AddInitialMetadata(const std::string& key, const std::string& value);
160
161 /// Add the (\a key, \a value) pair to the initial metadata
162 /// associated with a server call. These are made available at the client
163 /// side by the \a grpc::ClientContext::GetServerTrailingMetadata() method.
164 ///
165 /// \warning This method should only be called before sending trailing
166 /// metadata to the client (which happens when the call is finished and a
167 /// status is sent to the client).
168 ///
169 /// \param key The metadata key. If \a value is binary data,
170 /// it must end in "-bin".
171 /// \param value The metadata value. If its value is binary, the key name
172 /// must end in "-bin".
173 ///
174 /// Metadata must conform to the following format:
175 /**
176 \verbatim
177 Custom-Metadata -> Binary-Header / ASCII-Header
178 Binary-Header -> {Header-Name "-bin" } {binary value}
179 ASCII-Header -> Header-Name ASCII-Value
180 Header-Name -> 1*( %x30-39 / %x61-7A / "_" / "-" / ".") ; 0-9 a-z _ - .
181 ASCII-Value -> 1*( %x20-%x7E ) ; space and printable ASCII
182 \endverbatim
183 **/
184 void AddTrailingMetadata(const std::string& key, const std::string& value);
185
186 /// Return whether this RPC failed before the server could provide its status
187 /// back to the client. This could be because of explicit API cancellation
188 /// from the client-side or server-side, because of deadline exceeded, network
189 /// connection reset, HTTP/2 parameter configuration (e.g., max message size,
190 /// max connection age), etc. It does NOT include failure due to a non-OK
191 /// status return from the server application's request handler, including
192 /// Status::CANCELLED.
193 ///
194 /// IsCancelled is always safe to call when using sync or callback API.
195 /// When using async API, it is only safe to call IsCancelled after
196 /// the AsyncNotifyWhenDone tag has been delivered. Thread-safe.
197 bool IsCancelled() const;
198
199 /// Cancel the Call from the server. This is a best-effort API and
200 /// depending on when it is called, the RPC may still appear successful to
201 /// the client. For example, if TryCancel() is called on a separate thread, it
202 /// might race with the server handler which might return success to the
203 /// client before TryCancel() was even started by the thread.
204 ///
205 /// It is the caller's responsibility to prevent such races and ensure that if
206 /// TryCancel() is called, the serverhandler must return Status::CANCELLED.
207 /// The only exception is that if the serverhandler is already returning an
208 /// error status code, it is ok to not return Status::CANCELLED even if
209 /// TryCancel() was called.
210 ///
211 /// For reasons such as the above, it is generally preferred to explicitly
212 /// finish an RPC by returning Status::CANCELLED rather than using TryCancel.
213 ///
214 /// Note that TryCancel() does not change any of the tags that are pending
215 /// on the completion queue. All pending tags will still be delivered
216 /// (though their ok result may reflect the effect of cancellation).
217 void TryCancel() const;
218
219 /// Return a collection of initial metadata key-value pairs sent from the
220 /// client. Note that keys may happen more than
221 /// once (ie, a \a std::multimap is returned).
222 ///
223 /// It is safe to use this method after initial metadata has been received,
224 /// Calls always begin with the client sending initial metadata, so this is
225 /// safe to access as soon as the call has begun on the server side.
226 ///
227 /// \return A multimap of initial metadata key-value pairs from the server.
228 const std::multimap<grpc::string_ref, grpc::string_ref>& client_metadata()
229 const {
230 return *client_metadata_.map();
231 }
232
233 /// Return the compression algorithm to be used by the server call.
234 grpc_compression_level compression_level() const {
235 return compression_level_;
236 }
237
238 /// Set \a level to be the compression level used for the server call.
239 ///
240 /// \param level The compression level used for the server call.
241 void set_compression_level(grpc_compression_level level) {
242 compression_level_set_ = true;
243 compression_level_ = level;
244 }
245
246 /// Return a bool indicating whether the compression level for this call
247 /// has been set (either implicitly or through a previous call to
248 /// \a set_compression_level.
249 bool compression_level_set() const { return compression_level_set_; }
250
251 /// Return the compression algorithm the server call will request be used.
252 /// Note that the gRPC runtime may decide to ignore this request, for example,
253 /// due to resource constraints, or if the server is aware the client doesn't
254 /// support the requested algorithm.
255 grpc_compression_algorithm compression_algorithm() const {
256 return compression_algorithm_;
257 }
258 /// Set \a algorithm to be the compression algorithm used for the server call.
259 ///
260 /// \param algorithm The compression algorithm used for the server call.
261 void set_compression_algorithm(grpc_compression_algorithm algorithm);
262
263 /// Set the serialized load reporting costs in \a cost_data for the call.
264 void SetLoadReportingCosts(const std::vector<std::string>& cost_data);
265
266 /// Return the authentication context for this server call.
267 ///
268 /// \see grpc::AuthContext.
269 std::shared_ptr<const grpc::AuthContext> auth_context() const {
270 if (auth_context_ == nullptr) {
271 auth_context_ = grpc::CreateAuthContext(call: call_.call);
272 }
273 return auth_context_;
274 }
275
276 /// Return the peer uri in a string.
277 /// WARNING: this value is never authenticated or subject to any security
278 /// related code. It must not be used for any authentication related
279 /// functionality. Instead, use auth_context.
280 std::string peer() const;
281
282 /// Get the census context associated with this server call.
283 const struct census_context* census_context() const;
284
285 /// Should be used for framework-level extensions only.
286 /// Applications never need to call this method.
287 grpc_call* c_call() { return call_.call; }
288
289 /// Get the \a CallMetricRecorder object for the current RPC.
290 /// Use it to record metrics during your RPC to send back to the
291 /// client in order to make load balancing decisions. This will
292 /// return nullptr if the feature hasn't been enabled using
293 /// \a EnableCallMetricRecording.
294 experimental::CallMetricRecorder* ExperimentalGetCallMetricRecorder() {
295 return call_metric_recorder_;
296 }
297
298 /// EXPERIMENTAL API
299 /// Returns the call's authority.
300 grpc::string_ref ExperimentalGetAuthority() const;
301
302 protected:
303 /// Async only. Has to be called before the rpc starts.
304 /// Returns the tag in completion queue when the rpc finishes.
305 /// IsCancelled() can then be called to check whether the rpc was cancelled.
306 /// TODO(vjpai): Fix this so that the tag is returned even if the call never
307 /// starts (https://github.com/grpc/grpc/issues/10136).
308 void AsyncNotifyWhenDone(void* tag) {
309 has_notify_when_done_tag_ = true;
310 async_notify_when_done_tag_ = tag;
311 }
312
313 /// NOTE: This is an API for advanced users who need custom allocators.
314 /// Get and maybe mutate the allocator state associated with the current RPC.
315 /// Currently only applicable for callback unary RPC methods.
316 RpcAllocatorState* GetRpcAllocatorState() { return message_allocator_state_; }
317
318 /// Get a library-owned default unary reactor for use in minimal reaction
319 /// cases. This supports typical unary RPC usage of providing a response and
320 /// status. It supports immediate Finish (finish from within the method
321 /// handler) or delayed Finish (finish called after the method handler
322 /// invocation). It does not support reacting to cancellation or completion,
323 /// or early sending of initial metadata. Since this is a library-owned
324 /// reactor, it should not be delete'd or freed in any way. This is more
325 /// efficient than creating a user-owned reactor both because of avoiding an
326 /// allocation and because its minimal reactions are optimized using a core
327 /// surface flag that allows their reactions to run inline without any
328 /// thread-hop.
329 ///
330 /// This method should not be called more than once or called after return
331 /// from the method handler.
332 grpc::ServerUnaryReactor* DefaultReactor() {
333 // Short-circuit the case where a default reactor was already set up by
334 // the TestPeer.
335 if (test_unary_ != nullptr) {
336 return reinterpret_cast<Reactor*>(&default_reactor_);
337 }
338 new (&default_reactor_) Reactor;
339#ifndef NDEBUG
340 bool old = false;
341 assert(default_reactor_used_.compare_exchange_strong(
342 old, true, std::memory_order_relaxed));
343#else
344 default_reactor_used_.store(i: true, m: std::memory_order_relaxed);
345#endif
346 return reinterpret_cast<Reactor*>(&default_reactor_);
347 }
348
349 /// Constructors for use by derived classes
350 ServerContextBase();
351 ServerContextBase(gpr_timespec deadline, grpc_metadata_array* arr);
352
353 void set_context_allocator(ContextAllocator* context_allocator) {
354 context_allocator_ = context_allocator;
355 }
356
357 ContextAllocator* context_allocator() const { return context_allocator_; }
358
359 private:
360 friend class grpc::testing::InteropServerContextInspector;
361 friend class grpc::testing::ServerContextTestSpouse;
362 friend class grpc::testing::DefaultReactorTestPeer;
363 friend class grpc::ServerInterface;
364 friend class grpc::Server;
365 template <class W, class R>
366 friend class grpc::ServerAsyncReader;
367 template <class W>
368 friend class grpc::ServerAsyncWriter;
369 template <class W>
370 friend class grpc::ServerAsyncResponseWriter;
371 template <class W, class R>
372 friend class grpc::ServerAsyncReaderWriter;
373 template <class R>
374 friend class grpc::ServerReader;
375 template <class W>
376 friend class grpc::ServerWriter;
377 template <class W, class R>
378 friend class grpc::internal::ServerReaderWriterBody;
379 template <class ResponseType>
380 friend void grpc::internal::UnaryRunHandlerHelper(
381 const internal::MethodHandler::HandlerParameter& param, ResponseType* rsp,
382 Status& status);
383 template <class ServiceType, class RequestType, class ResponseType,
384 class BaseRequestType, class BaseResponseType>
385 friend class grpc::internal::RpcMethodHandler;
386 template <class ServiceType, class RequestType, class ResponseType>
387 friend class grpc::internal::ClientStreamingHandler;
388 template <class ServiceType, class RequestType, class ResponseType>
389 friend class grpc::internal::ServerStreamingHandler;
390 template <class Streamer, bool WriteNeeded>
391 friend class grpc::internal::TemplatedBidiStreamingHandler;
392 template <class RequestType, class ResponseType>
393 friend class grpc::internal::CallbackUnaryHandler;
394 template <class RequestType, class ResponseType>
395 friend class grpc::internal::CallbackClientStreamingHandler;
396 template <class RequestType, class ResponseType>
397 friend class grpc::internal::CallbackServerStreamingHandler;
398 template <class RequestType, class ResponseType>
399 friend class grpc::internal::CallbackBidiHandler;
400 template <grpc::StatusCode code>
401 friend class grpc::internal::ErrorMethodHandler;
402 template <class Base>
403 friend class grpc::internal::FinishOnlyReactor;
404 friend class grpc::ClientContext;
405 friend class grpc::GenericServerContext;
406 friend class grpc::GenericCallbackServerContext;
407 friend class grpc::experimental::OrcaServerInterceptor;
408
409 /// Prevent copying.
410 ServerContextBase(const ServerContextBase&);
411 ServerContextBase& operator=(const ServerContextBase&);
412
413 class CompletionOp;
414
415 void BeginCompletionOp(
416 grpc::internal::Call* call, std::function<void(bool)> callback,
417 grpc::internal::ServerCallbackCall* callback_controller);
418 /// Return the tag queued by BeginCompletionOp()
419 grpc::internal::CompletionQueueTag* GetCompletionOpTag();
420
421 void set_call(grpc_call* call) { call_.call = call; }
422
423 void BindDeadlineAndMetadata(gpr_timespec deadline, grpc_metadata_array* arr);
424
425 uint32_t initial_metadata_flags() const { return 0; }
426
427 grpc::experimental::ServerRpcInfo* set_server_rpc_info(
428 const char* method, grpc::internal::RpcMethod::RpcType type,
429 const std::vector<std::unique_ptr<
430 grpc::experimental::ServerInterceptorFactoryInterface>>& creators) {
431 if (!creators.empty()) {
432 rpc_info_ = new grpc::experimental::ServerRpcInfo(this, method, type);
433 rpc_info_->RegisterInterceptors(creators);
434 }
435 return rpc_info_;
436 }
437
438 void set_message_allocator_state(RpcAllocatorState* allocator_state) {
439 message_allocator_state_ = allocator_state;
440 }
441
442 void MaybeMarkCancelledOnRead() {
443 if (g_core_codegen_interface->grpc_call_failed_before_recv_message(
444 c: call_.call)) {
445 marked_cancelled_.store(i: true, m: std::memory_order_release);
446 }
447 }
448
449 void CreateCallMetricRecorder();
450
451 struct CallWrapper {
452 ~CallWrapper();
453
454 grpc_call* call = nullptr;
455 };
456
457 // NOTE: call_ must be the first data member of this object so that its
458 // destructor is the last to be called, since its destructor may unref
459 // the underlying core call which holds the arena that may be used to
460 // hold this object.
461 CallWrapper call_;
462
463 CompletionOp* completion_op_ = nullptr;
464 bool has_notify_when_done_tag_ = false;
465 void* async_notify_when_done_tag_ = nullptr;
466 grpc::internal::CallbackWithSuccessTag completion_tag_;
467
468 gpr_timespec deadline_;
469 grpc::CompletionQueue* cq_ = nullptr;
470 bool sent_initial_metadata_ = false;
471 mutable std::shared_ptr<const grpc::AuthContext> auth_context_;
472 mutable grpc::internal::MetadataMap client_metadata_;
473 std::multimap<std::string, std::string> initial_metadata_;
474 std::multimap<std::string, std::string> trailing_metadata_;
475
476 bool compression_level_set_ = false;
477 grpc_compression_level compression_level_;
478 grpc_compression_algorithm compression_algorithm_;
479
480 grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata,
481 grpc::internal::CallOpSendMessage>
482 pending_ops_;
483 bool has_pending_ops_ = false;
484
485 grpc::experimental::ServerRpcInfo* rpc_info_ = nullptr;
486 RpcAllocatorState* message_allocator_state_ = nullptr;
487 ContextAllocator* context_allocator_ = nullptr;
488 experimental::CallMetricRecorder* call_metric_recorder_ = nullptr;
489
490 class Reactor : public grpc::ServerUnaryReactor {
491 public:
492 void OnCancel() override {}
493 void OnDone() override {}
494 // Override InternalInlineable for this class since its reactions are
495 // trivial and thus do not need to be run from the executor (triggering a
496 // thread hop). This should only be used by internal reactors (thus the
497 // name) and not by user application code.
498 bool InternalInlineable() override { return true; }
499 };
500
501 void SetupTestDefaultReactor(std::function<void(grpc::Status)> func) {
502 // NOLINTNEXTLINE(modernize-make-unique)
503 test_unary_.reset(p: new TestServerCallbackUnary(this, std::move(func)));
504 }
505 bool test_status_set() const {
506 return (test_unary_ != nullptr) && test_unary_->status_set();
507 }
508 grpc::Status test_status() const { return test_unary_->status(); }
509
510 class TestServerCallbackUnary : public grpc::ServerCallbackUnary {
511 public:
512 TestServerCallbackUnary(ServerContextBase* ctx,
513 std::function<void(grpc::Status)> func)
514 : reactor_(ctx->DefaultReactor()), func_(std::move(func)) {
515 this->BindReactor(reactor: reactor_);
516 }
517 void Finish(grpc::Status s) override {
518 status_ = s;
519 func_(std::move(s));
520 status_set_.store(i: true, m: std::memory_order_release);
521 }
522 void SendInitialMetadata() override {}
523
524 bool status_set() const {
525 return status_set_.load(m: std::memory_order_acquire);
526 }
527 grpc::Status status() const { return status_; }
528
529 private:
530 void CallOnDone() override {}
531 grpc::internal::ServerReactor* reactor() override { return reactor_; }
532
533 grpc::ServerUnaryReactor* const reactor_;
534 std::atomic_bool status_set_{false};
535 grpc::Status status_;
536 const std::function<void(grpc::Status s)> func_;
537 };
538
539 typename std::aligned_storage<sizeof(Reactor), alignof(Reactor)>::type
540 default_reactor_;
541 std::atomic_bool default_reactor_used_{false};
542
543 std::atomic_bool marked_cancelled_{false};
544
545 std::unique_ptr<TestServerCallbackUnary> test_unary_;
546};
547
548/// A ServerContext or CallbackServerContext allows the code implementing a
549/// service handler to:
550///
551/// - Add custom initial and trailing metadata key-value pairs that will
552/// propagated to the client side.
553/// - Control call settings such as compression and authentication.
554/// - Access metadata coming from the client.
555/// - Get performance metrics (ie, census).
556///
557/// Context settings are only relevant to the call handler they are supplied to,
558/// that is to say, they aren't sticky across multiple calls. Some of these
559/// settings, such as the compression options, can be made persistent at server
560/// construction time by specifying the appropriate \a ChannelArguments
561/// to a \a grpc::ServerBuilder, via \a ServerBuilder::AddChannelArgument.
562///
563/// \warning ServerContext instances should \em not be reused across rpcs.
564class ServerContext : public ServerContextBase {
565 public:
566 ServerContext() {} // for async calls
567
568 using ServerContextBase::AddInitialMetadata;
569 using ServerContextBase::AddTrailingMetadata;
570 using ServerContextBase::auth_context;
571 using ServerContextBase::c_call;
572 using ServerContextBase::census_context;
573 using ServerContextBase::client_metadata;
574 using ServerContextBase::compression_algorithm;
575 using ServerContextBase::compression_level;
576 using ServerContextBase::compression_level_set;
577 using ServerContextBase::deadline;
578 using ServerContextBase::IsCancelled;
579 using ServerContextBase::peer;
580 using ServerContextBase::raw_deadline;
581 using ServerContextBase::set_compression_algorithm;
582 using ServerContextBase::set_compression_level;
583 using ServerContextBase::SetLoadReportingCosts;
584 using ServerContextBase::TryCancel;
585
586 // Sync/CQ-based Async ServerContext only
587 using ServerContextBase::AsyncNotifyWhenDone;
588
589 private:
590 // Constructor for internal use by server only
591 friend class grpc::Server;
592 ServerContext(gpr_timespec deadline, grpc_metadata_array* arr)
593 : ServerContextBase(deadline, arr) {}
594
595 // CallbackServerContext only
596 using ServerContextBase::DefaultReactor;
597 using ServerContextBase::GetRpcAllocatorState;
598
599 /// Prevent copying.
600 ServerContext(const ServerContext&) = delete;
601 ServerContext& operator=(const ServerContext&) = delete;
602};
603
604class CallbackServerContext : public ServerContextBase {
605 public:
606 /// Public constructors are for direct use only by mocking tests. In practice,
607 /// these objects will be owned by the library.
608 CallbackServerContext() {}
609
610 using ServerContextBase::AddInitialMetadata;
611 using ServerContextBase::AddTrailingMetadata;
612 using ServerContextBase::auth_context;
613 using ServerContextBase::c_call;
614 using ServerContextBase::census_context;
615 using ServerContextBase::client_metadata;
616 using ServerContextBase::compression_algorithm;
617 using ServerContextBase::compression_level;
618 using ServerContextBase::compression_level_set;
619 using ServerContextBase::context_allocator;
620 using ServerContextBase::deadline;
621 using ServerContextBase::IsCancelled;
622 using ServerContextBase::peer;
623 using ServerContextBase::raw_deadline;
624 using ServerContextBase::set_compression_algorithm;
625 using ServerContextBase::set_compression_level;
626 using ServerContextBase::set_context_allocator;
627 using ServerContextBase::SetLoadReportingCosts;
628 using ServerContextBase::TryCancel;
629
630 // CallbackServerContext only
631 using ServerContextBase::DefaultReactor;
632 using ServerContextBase::GetRpcAllocatorState;
633
634 private:
635 // Sync/CQ-based Async ServerContext only
636 using ServerContextBase::AsyncNotifyWhenDone;
637
638 /// Prevent copying.
639 CallbackServerContext(const CallbackServerContext&) = delete;
640 CallbackServerContext& operator=(const CallbackServerContext&) = delete;
641};
642
643/// A CallbackServerContext allows users to use the contents of the
644/// CallbackServerContext or GenericCallbackServerContext structure for the
645/// callback API.
646/// The library will invoke the allocator any time a new call is initiated.
647/// and call the Release method after the server OnDone.
648class ContextAllocator {
649 public:
650 virtual ~ContextAllocator() {}
651
652 virtual CallbackServerContext* NewCallbackServerContext() { return nullptr; }
653
654 virtual GenericCallbackServerContext* NewGenericCallbackServerContext() {
655 return nullptr;
656 }
657
658 virtual void Release(CallbackServerContext*) {}
659
660 virtual void Release(GenericCallbackServerContext*) {}
661};
662
663} // namespace grpc
664
665static_assert(
666 std::is_base_of<grpc::ServerContextBase, grpc::ServerContext>::value,
667 "improper base class");
668static_assert(std::is_base_of<grpc::ServerContextBase,
669 grpc::CallbackServerContext>::value,
670 "improper base class");
671static_assert(sizeof(grpc::ServerContextBase) == sizeof(grpc::ServerContext),
672 "wrong size");
673static_assert(sizeof(grpc::ServerContextBase) ==
674 sizeof(grpc::CallbackServerContext),
675 "wrong size");
676
677#endif // GRPCPP_SERVER_CONTEXT_H
678

source code of include/grpcpp/server_context.h