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