| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404 | /* * * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * *     * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. *     * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. *     * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *//// A ClientContext allows the person implementing a service client to:////// - Add custom metadata key-value pairs that will propagated to the server/// side./// - Control call settings such as compression and authentication./// - Initial and trailing metadata coming from the server./// - Get performance metrics (ie, census).////// Context settings are only relevant to the call they are invoked with, that/// is to say, they aren't sticky. Some of these settings, such as the/// compression options, can be made persistent at channel construction time/// (see \a grpc::CreateCustomChannel).////// \warning ClientContext instances should \em not be reused across rpcs.#ifndef GRPCXX_IMPL_CODEGEN_CLIENT_CONTEXT_H#define GRPCXX_IMPL_CODEGEN_CLIENT_CONTEXT_H#include <map>#include <memory>#include <mutex>#include <string>#include <grpc++/impl/codegen/config.h>#include <grpc++/impl/codegen/core_codegen_interface.h>#include <grpc++/impl/codegen/create_auth_context.h>#include <grpc++/impl/codegen/metadata_map.h>#include <grpc++/impl/codegen/security/auth_context.h>#include <grpc++/impl/codegen/slice.h>#include <grpc++/impl/codegen/status.h>#include <grpc++/impl/codegen/string_ref.h>#include <grpc++/impl/codegen/time.h>#include <grpc/impl/codegen/compression_types.h>#include <grpc/impl/codegen/propagation_bits.h>struct census_context;struct grpc_call;namespace grpc {class Channel;class ChannelInterface;class CompletionQueue;class CallCredentials;class RpcMethod;template <class R>class ClientReader;template <class W>class ClientWriter;template <class W, class R>class ClientReaderWriter;template <class R>class ClientAsyncReader;template <class W>class ClientAsyncWriter;template <class W, class R>class ClientAsyncReaderWriter;template <class R>class ClientAsyncResponseReader;class ServerContext;/// Options for \a ClientContext::FromServerContext specifying which traits from/// the \a ServerContext to propagate (copy) from it into a new \a/// ClientContext.////// \see ClientContext::FromServerContextclass PropagationOptions { public:  PropagationOptions() : propagate_(GRPC_PROPAGATE_DEFAULTS) {}  PropagationOptions& enable_deadline_propagation() {    propagate_ |= GRPC_PROPAGATE_DEADLINE;    return *this;  }  PropagationOptions& disable_deadline_propagation() {    propagate_ &= ~GRPC_PROPAGATE_DEADLINE;    return *this;  }  PropagationOptions& enable_census_stats_propagation() {    propagate_ |= GRPC_PROPAGATE_CENSUS_STATS_CONTEXT;    return *this;  }  PropagationOptions& disable_census_stats_propagation() {    propagate_ &= ~GRPC_PROPAGATE_CENSUS_STATS_CONTEXT;    return *this;  }  PropagationOptions& enable_census_tracing_propagation() {    propagate_ |= GRPC_PROPAGATE_CENSUS_TRACING_CONTEXT;    return *this;  }  PropagationOptions& disable_census_tracing_propagation() {    propagate_ &= ~GRPC_PROPAGATE_CENSUS_TRACING_CONTEXT;    return *this;  }  PropagationOptions& enable_cancellation_propagation() {    propagate_ |= GRPC_PROPAGATE_CANCELLATION;    return *this;  }  PropagationOptions& disable_cancellation_propagation() {    propagate_ &= ~GRPC_PROPAGATE_CANCELLATION;    return *this;  }  uint32_t c_bitmask() const { return propagate_; } private:  uint32_t propagate_;};namespace testing {class InteropClientContextInspector;}  // namespace testingclass ClientContext { public:  ClientContext();  ~ClientContext();  /// Create a new \a ClientContext as a child of an incoming server call,  /// according to \a options (\see PropagationOptions).  ///  /// \param server_context The source server context to use as the basis for  /// constructing the client context.  /// \param options The options controlling what to copy from the \a  /// server_context.  ///  /// \return A newly constructed \a ClientContext instance based on \a  /// server_context, with traits propagated (copied) according to \a options.  static std::unique_ptr<ClientContext> FromServerContext(      const ServerContext& server_context,      PropagationOptions options = PropagationOptions());  /// Add the (\a meta_key, \a meta_value) pair to the metadata associated with  /// a client call. These are made available at the server side by the \a  /// grpc::ServerContext::client_metadata() method.  ///  /// \warning This method should only be called before invoking the rpc.  ///  /// \param meta_key The metadata key. If \a meta_value is binary data, it must  /// end in "-bin".  /// \param meta_value The metadata value. If its value is binary, it must be  /// base64-encoding (see https://tools.ietf.org/html/rfc4648#section-4) and \a  /// meta_key must end in "-bin".  void AddMetadata(const grpc::string& meta_key,                   const grpc::string& meta_value);  /// Return a collection of initial metadata key-value pairs. Note that keys  /// may happen more than once (ie, a \a std::multimap is returned).  ///  /// \warning This method should only be called after initial metadata has been  /// received. For streaming calls, see \a  /// ClientReaderInterface::WaitForInitialMetadata().  ///  /// \return A multimap of initial metadata key-value pairs from the server.  const std::multimap<grpc::string_ref, grpc::string_ref>&  GetServerInitialMetadata() const {    GPR_CODEGEN_ASSERT(initial_metadata_received_);    return *recv_initial_metadata_.map();  }  /// Return a collection of trailing metadata key-value pairs. Note that keys  /// may happen more than once (ie, a \a std::multimap is returned).  ///  /// \warning This method is only callable once the stream has finished.  ///  /// \return A multimap of metadata trailing key-value pairs from the server.  const std::multimap<grpc::string_ref, grpc::string_ref>&  GetServerTrailingMetadata() const {    // TODO(yangg) check finished    return *trailing_metadata_.map();  }  /// Set the deadline for the client call.  ///  /// \warning This method should only be called before invoking the rpc.  ///  /// \param deadline the deadline for the client call. Units are determined by  /// the type used.  template <typename T>  void set_deadline(const T& deadline) {    TimePoint<T> deadline_tp(deadline);    deadline_ = deadline_tp.raw_time();  }  /// EXPERIMENTAL: Set this request to be idempotent  void set_idempotent(bool idempotent) { idempotent_ = idempotent; }  /// EXPERIMENTAL: Set this request to be cacheable  void set_cacheable(bool cacheable) { cacheable_ = cacheable; }  /// EXPERIMENTAL: Trigger wait-for-ready or not on this request  void set_wait_for_ready(bool wait_for_ready) {    wait_for_ready_ = wait_for_ready;    wait_for_ready_explicitly_set_ = true;  }  /// DEPRECATED: Use set_wait_for_ready() instead.  void set_fail_fast(bool fail_fast) { set_wait_for_ready(!fail_fast); }  /// Return the deadline for the client call.  std::chrono::system_clock::time_point deadline() const {    return Timespec2Timepoint(deadline_);  }  /// Return a \a gpr_timespec representation of the client call's deadline.  gpr_timespec raw_deadline() const { return deadline_; }  /// Set the per call authority header (see  /// https://tools.ietf.org/html/rfc7540#section-8.1.2.3).  void set_authority(const grpc::string& authority) { authority_ = authority; }  /// Return the authentication context for this client call.  ///  /// \see grpc::AuthContext.  std::shared_ptr<const AuthContext> auth_context() const {    if (auth_context_.get() == nullptr) {      auth_context_ = CreateAuthContext(call_);    }    return auth_context_;  }  /// Set credentials for the client call.  ///  /// A credentials object encapsulates all the state needed by a client to  /// authenticate with a server and make various assertions, e.g., about the  /// client’s identity, role, or whether it is authorized to make a particular  /// call.  ///  /// \see  http://www.grpc.io/docs/guides/auth.html  void set_credentials(const std::shared_ptr<CallCredentials>& creds) {    creds_ = creds;  }  /// Return the compression algorithm to be used by the client call.  grpc_compression_algorithm compression_algorithm() const {    return compression_algorithm_;  }  /// Set \a algorithm to be the compression algorithm used for the client call.  ///  /// \param algorithm The compression algorithm used for the client call.  void set_compression_algorithm(grpc_compression_algorithm algorithm);  /// Flag whether the initial metadata should be \a corked  ///  /// If \a corked is true, then the initial metadata will be colasced with the  /// write of first message in the stream.  ///  /// \param corked The flag indicating whether the initial metadata is to be  /// corked or not.  void set_initial_metadata_corked(bool corked) {    initial_metadata_corked_ = corked;  }  /// Return the peer uri in a string.  ///  /// \warning This value is never authenticated or subject to any security  /// related code. It must not be used for any authentication related  /// functionality. Instead, use auth_context.  ///  /// \return The call's peer URI.  grpc::string peer() const;  /// Get and set census context.  void set_census_context(struct census_context* ccp) { census_context_ = ccp; }  struct census_context* census_context() const {    return census_context_;  }  /// Send a best-effort out-of-band cancel. The call could be in any stage.  /// e.g. if it is already finished, it may still return success.  ///  /// There is no guarantee the call will be cancelled.  void TryCancel();  /// Global Callbacks  ///  /// Can be set exactly once per application to install hooks whenever  /// a client context is constructed and destructed.  class GlobalCallbacks {   public:    virtual ~GlobalCallbacks() {}    virtual void DefaultConstructor(ClientContext* context) = 0;    virtual void Destructor(ClientContext* context) = 0;  };  static void SetGlobalCallbacks(GlobalCallbacks* callbacks);  // Should be used for framework-level extensions only.  // Applications never need to call this method.  grpc_call* c_call() { return call_; } private:  // Disallow copy and assign.  ClientContext(const ClientContext&);  ClientContext& operator=(const ClientContext&);  friend class ::grpc::testing::InteropClientContextInspector;  friend class CallOpClientRecvStatus;  friend class CallOpRecvInitialMetadata;  friend class Channel;  template <class R>  friend class ::grpc::ClientReader;  template <class W>  friend class ::grpc::ClientWriter;  template <class W, class R>  friend class ::grpc::ClientReaderWriter;  template <class R>  friend class ::grpc::ClientAsyncReader;  template <class W>  friend class ::grpc::ClientAsyncWriter;  template <class W, class R>  friend class ::grpc::ClientAsyncReaderWriter;  template <class R>  friend class ::grpc::ClientAsyncResponseReader;  template <class InputMessage, class OutputMessage>  friend Status BlockingUnaryCall(ChannelInterface* channel,                                  const RpcMethod& method,                                  ClientContext* context,                                  const InputMessage& request,                                  OutputMessage* result);  grpc_call* call() const { return call_; }  void set_call(grpc_call* call, const std::shared_ptr<Channel>& channel);  uint32_t initial_metadata_flags() const {    return (idempotent_ ? GRPC_INITIAL_METADATA_IDEMPOTENT_REQUEST : 0) |           (wait_for_ready_ ? GRPC_INITIAL_METADATA_WAIT_FOR_READY : 0) |           (cacheable_ ? GRPC_INITIAL_METADATA_CACHEABLE_REQUEST : 0) |           (wait_for_ready_explicitly_set_                ? GRPC_INITIAL_METADATA_WAIT_FOR_READY_EXPLICITLY_SET                : 0) |           (initial_metadata_corked_ ? GRPC_INITIAL_METADATA_CORKED : 0);  }  grpc::string authority() { return authority_; }  bool initial_metadata_received_;  bool wait_for_ready_;  bool wait_for_ready_explicitly_set_;  bool idempotent_;  bool cacheable_;  std::shared_ptr<Channel> channel_;  std::mutex mu_;  grpc_call* call_;  bool call_canceled_;  gpr_timespec deadline_;  grpc::string authority_;  std::shared_ptr<CallCredentials> creds_;  mutable std::shared_ptr<const AuthContext> auth_context_;  struct census_context* census_context_;  std::multimap<grpc::string, grpc::string> send_initial_metadata_;  MetadataMap recv_initial_metadata_;  MetadataMap trailing_metadata_;  grpc_call* propagate_from_call_;  PropagationOptions propagation_options_;  grpc_compression_algorithm compression_algorithm_;  bool initial_metadata_corked_;};}  // namespace grpc#endif  // GRPCXX_IMPL_CODEGEN_CLIENT_CONTEXT_H
 |