This commit is contained in:
Yao
2024-12-20 17:49:45 +08:00
parent 86b0363ce1
commit 654d456c7d
7011 changed files with 1705926 additions and 7 deletions

94
Pods/gRPC-C++/include/grpcpp/impl/call.h generated Normal file
View File

@@ -0,0 +1,94 @@
//
//
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CALL_H
#define GRPCPP_IMPL_CALL_H
#include <grpc/impl/grpc_types.h>
#include <grpcpp/impl/call_hook.h>
namespace grpc {
class CompletionQueue;
namespace experimental {
class ClientRpcInfo;
class ServerRpcInfo;
} // namespace experimental
namespace internal {
class CallHook;
class CallOpSetInterface;
/// Straightforward wrapping of the C call object
class Call final {
public:
Call()
: call_hook_(nullptr),
cq_(nullptr),
call_(nullptr),
max_receive_message_size_(-1) {}
/// call is owned by the caller
Call(grpc_call* call, CallHook* call_hook, grpc::CompletionQueue* cq)
: call_hook_(call_hook),
cq_(cq),
call_(call),
max_receive_message_size_(-1) {}
Call(grpc_call* call, CallHook* call_hook, grpc::CompletionQueue* cq,
experimental::ClientRpcInfo* rpc_info)
: call_hook_(call_hook),
cq_(cq),
call_(call),
max_receive_message_size_(-1),
client_rpc_info_(rpc_info) {}
Call(grpc_call* call, CallHook* call_hook, grpc::CompletionQueue* cq,
int max_receive_message_size, experimental::ServerRpcInfo* rpc_info)
: call_hook_(call_hook),
cq_(cq),
call_(call),
max_receive_message_size_(max_receive_message_size),
server_rpc_info_(rpc_info) {}
void PerformOps(CallOpSetInterface* ops) {
call_hook_->PerformOpsOnCall(ops, this);
}
grpc_call* call() const { return call_; }
grpc::CompletionQueue* cq() const { return cq_; }
int max_receive_message_size() const { return max_receive_message_size_; }
experimental::ClientRpcInfo* client_rpc_info() const {
return client_rpc_info_;
}
experimental::ServerRpcInfo* server_rpc_info() const {
return server_rpc_info_;
}
private:
CallHook* call_hook_;
grpc::CompletionQueue* cq_;
grpc_call* call_;
int max_receive_message_size_;
experimental::ClientRpcInfo* client_rpc_info_ = nullptr;
experimental::ServerRpcInfo* server_rpc_info_ = nullptr;
};
} // namespace internal
} // namespace grpc
#endif // GRPCPP_IMPL_CALL_H

View File

@@ -0,0 +1,39 @@
//
//
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CALL_HOOK_H
#define GRPCPP_IMPL_CALL_HOOK_H
namespace grpc {
namespace internal {
class CallOpSetInterface;
class Call;
/// This is an interface that Channel and Server implement to allow them to hook
/// performing ops.
class CallHook {
public:
virtual ~CallHook() {}
virtual void PerformOpsOnCall(CallOpSetInterface* ops, Call* call) = 0;
};
} // namespace internal
} // namespace grpc
#endif // GRPCPP_IMPL_CALL_HOOK_H

View File

@@ -0,0 +1,1036 @@
//
//
// Copyright 2018 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CALL_OP_SET_H
#define GRPCPP_IMPL_CALL_OP_SET_H
#include <cstring>
#include <map>
#include <memory>
#include <grpc/grpc.h>
#include <grpc/impl/compression_types.h>
#include <grpc/impl/grpc_types.h>
#include <grpc/slice.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpcpp/client_context.h>
#include <grpcpp/completion_queue.h>
#include <grpcpp/impl/call.h>
#include <grpcpp/impl/call_hook.h>
#include <grpcpp/impl/call_op_set_interface.h>
#include <grpcpp/impl/codegen/intercepted_channel.h>
#include <grpcpp/impl/completion_queue_tag.h>
#include <grpcpp/impl/interceptor_common.h>
#include <grpcpp/impl/serialization_traits.h>
#include <grpcpp/support/byte_buffer.h>
#include <grpcpp/support/config.h>
#include <grpcpp/support/slice.h>
#include <grpcpp/support/string_ref.h>
namespace grpc {
namespace internal {
class Call;
class CallHook;
// TODO(yangg) if the map is changed before we send, the pointers will be a
// mess. Make sure it does not happen.
inline grpc_metadata* FillMetadataArray(
const std::multimap<std::string, std::string>& metadata,
size_t* metadata_count, const std::string& optional_error_details) {
*metadata_count = metadata.size() + (optional_error_details.empty() ? 0 : 1);
if (*metadata_count == 0) {
return nullptr;
}
grpc_metadata* metadata_array = static_cast<grpc_metadata*>(
gpr_malloc((*metadata_count) * sizeof(grpc_metadata)));
size_t i = 0;
for (auto iter = metadata.cbegin(); iter != metadata.cend(); ++iter, ++i) {
metadata_array[i].key = SliceReferencingString(iter->first);
metadata_array[i].value = SliceReferencingString(iter->second);
}
if (!optional_error_details.empty()) {
metadata_array[i].key = grpc_slice_from_static_buffer(
kBinaryErrorDetailsKey, sizeof(kBinaryErrorDetailsKey) - 1);
metadata_array[i].value = SliceReferencingString(optional_error_details);
}
return metadata_array;
}
} // namespace internal
/// Per-message write options.
class WriteOptions {
public:
WriteOptions() : flags_(0), last_message_(false) {}
/// Clear all flags.
inline void Clear() { flags_ = 0; }
/// Returns raw flags bitset.
inline uint32_t flags() const { return flags_; }
/// Sets flag for the disabling of compression for the next message write.
///
/// \sa GRPC_WRITE_NO_COMPRESS
inline WriteOptions& set_no_compression() {
SetBit(GRPC_WRITE_NO_COMPRESS);
return *this;
}
/// Clears flag for the disabling of compression for the next message write.
///
/// \sa GRPC_WRITE_NO_COMPRESS
inline WriteOptions& clear_no_compression() {
ClearBit(GRPC_WRITE_NO_COMPRESS);
return *this;
}
/// Get value for the flag indicating whether compression for the next
/// message write is forcefully disabled.
///
/// \sa GRPC_WRITE_NO_COMPRESS
inline bool get_no_compression() const {
return GetBit(GRPC_WRITE_NO_COMPRESS);
}
/// Sets flag indicating that the write may be buffered and need not go out on
/// the wire immediately.
///
/// \sa GRPC_WRITE_BUFFER_HINT
inline WriteOptions& set_buffer_hint() {
SetBit(GRPC_WRITE_BUFFER_HINT);
return *this;
}
/// Clears flag indicating that the write may be buffered and need not go out
/// on the wire immediately.
///
/// \sa GRPC_WRITE_BUFFER_HINT
inline WriteOptions& clear_buffer_hint() {
ClearBit(GRPC_WRITE_BUFFER_HINT);
return *this;
}
/// Get value for the flag indicating that the write may be buffered and need
/// not go out on the wire immediately.
///
/// \sa GRPC_WRITE_BUFFER_HINT
inline bool get_buffer_hint() const { return GetBit(GRPC_WRITE_BUFFER_HINT); }
/// corked bit: aliases set_buffer_hint currently, with the intent that
/// set_buffer_hint will be removed in the future
inline WriteOptions& set_corked() {
SetBit(GRPC_WRITE_BUFFER_HINT);
return *this;
}
inline WriteOptions& clear_corked() {
ClearBit(GRPC_WRITE_BUFFER_HINT);
return *this;
}
inline bool is_corked() const { return GetBit(GRPC_WRITE_BUFFER_HINT); }
/// last-message bit: indicates this is the last message in a stream
/// client-side: makes Write the equivalent of performing Write, WritesDone
/// in a single step
/// server-side: hold the Write until the service handler returns (sync api)
/// or until Finish is called (async api)
inline WriteOptions& set_last_message() {
last_message_ = true;
return *this;
}
/// Clears flag indicating that this is the last message in a stream,
/// disabling coalescing.
inline WriteOptions& clear_last_message() {
last_message_ = false;
return *this;
}
/// Get value for the flag indicating that this is the last message, and
/// should be coalesced with trailing metadata.
///
/// \sa GRPC_WRITE_LAST_MESSAGE
bool is_last_message() const { return last_message_; }
/// Guarantee that all bytes have been written to the socket before completing
/// this write (usually writes are completed when they pass flow control).
inline WriteOptions& set_write_through() {
SetBit(GRPC_WRITE_THROUGH);
return *this;
}
inline WriteOptions& clear_write_through() {
ClearBit(GRPC_WRITE_THROUGH);
return *this;
}
inline bool is_write_through() const { return GetBit(GRPC_WRITE_THROUGH); }
private:
void SetBit(const uint32_t mask) { flags_ |= mask; }
void ClearBit(const uint32_t mask) { flags_ &= ~mask; }
bool GetBit(const uint32_t mask) const { return (flags_ & mask) != 0; }
uint32_t flags_;
bool last_message_;
};
namespace internal {
/// Default argument for CallOpSet. The Unused parameter is unused by
/// the class, but can be used for generating multiple names for the
/// same thing.
template <int Unused>
class CallNoOp {
protected:
void AddOp(grpc_op* /*ops*/, size_t* /*nops*/) {}
void FinishOp(bool* /*status*/) {}
void SetInterceptionHookPoint(
InterceptorBatchMethodsImpl* /*interceptor_methods*/) {}
void SetFinishInterceptionHookPoint(
InterceptorBatchMethodsImpl* /*interceptor_methods*/) {}
void SetHijackingState(InterceptorBatchMethodsImpl* /*interceptor_methods*/) {
}
};
class CallOpSendInitialMetadata {
public:
CallOpSendInitialMetadata() : send_(false) {
maybe_compression_level_.is_set = false;
}
void SendInitialMetadata(std::multimap<std::string, std::string>* metadata,
uint32_t flags) {
maybe_compression_level_.is_set = false;
send_ = true;
flags_ = flags;
metadata_map_ = metadata;
}
void set_compression_level(grpc_compression_level level) {
maybe_compression_level_.is_set = true;
maybe_compression_level_.level = level;
}
protected:
void AddOp(grpc_op* ops, size_t* nops) {
if (!send_ || hijacked_) return;
grpc_op* op = &ops[(*nops)++];
op->op = GRPC_OP_SEND_INITIAL_METADATA;
op->flags = flags_;
op->reserved = nullptr;
initial_metadata_ =
FillMetadataArray(*metadata_map_, &initial_metadata_count_, "");
op->data.send_initial_metadata.count = initial_metadata_count_;
op->data.send_initial_metadata.metadata = initial_metadata_;
op->data.send_initial_metadata.maybe_compression_level.is_set =
maybe_compression_level_.is_set;
if (maybe_compression_level_.is_set) {
op->data.send_initial_metadata.maybe_compression_level.level =
maybe_compression_level_.level;
}
}
void FinishOp(bool* /*status*/) {
if (!send_ || hijacked_) return;
gpr_free(initial_metadata_);
send_ = false;
}
void SetInterceptionHookPoint(
InterceptorBatchMethodsImpl* interceptor_methods) {
if (!send_) return;
interceptor_methods->AddInterceptionHookPoint(
experimental::InterceptionHookPoints::PRE_SEND_INITIAL_METADATA);
interceptor_methods->SetSendInitialMetadata(metadata_map_);
}
void SetFinishInterceptionHookPoint(
InterceptorBatchMethodsImpl* /*interceptor_methods*/) {}
void SetHijackingState(InterceptorBatchMethodsImpl* /*interceptor_methods*/) {
hijacked_ = true;
}
bool hijacked_ = false;
bool send_;
uint32_t flags_;
size_t initial_metadata_count_;
std::multimap<std::string, std::string>* metadata_map_;
grpc_metadata* initial_metadata_;
struct {
bool is_set;
grpc_compression_level level;
} maybe_compression_level_;
};
class CallOpSendMessage {
public:
CallOpSendMessage() : send_buf_() {}
/// Send \a message using \a options for the write. The \a options are cleared
/// after use.
template <class M>
GRPC_MUST_USE_RESULT Status SendMessage(const M& message,
WriteOptions options);
template <class M>
GRPC_MUST_USE_RESULT Status SendMessage(const M& message);
/// Send \a message using \a options for the write. The \a options are cleared
/// after use. This form of SendMessage allows gRPC to reference \a message
/// beyond the lifetime of SendMessage.
template <class M>
GRPC_MUST_USE_RESULT Status SendMessagePtr(const M* message,
WriteOptions options);
/// This form of SendMessage allows gRPC to reference \a message beyond the
/// lifetime of SendMessage.
template <class M>
GRPC_MUST_USE_RESULT Status SendMessagePtr(const M* message);
protected:
void AddOp(grpc_op* ops, size_t* nops) {
if (msg_ == nullptr && !send_buf_.Valid()) return;
if (hijacked_) {
serializer_ = nullptr;
return;
}
if (msg_ != nullptr) {
GPR_ASSERT(serializer_(msg_).ok());
}
serializer_ = nullptr;
grpc_op* op = &ops[(*nops)++];
op->op = GRPC_OP_SEND_MESSAGE;
op->flags = write_options_.flags();
op->reserved = nullptr;
op->data.send_message.send_message = send_buf_.c_buffer();
// Flags are per-message: clear them after use.
write_options_.Clear();
}
void FinishOp(bool* status) {
if (msg_ == nullptr && !send_buf_.Valid()) return;
send_buf_.Clear();
if (hijacked_ && failed_send_) {
// Hijacking interceptor failed this Op
*status = false;
} else if (!*status) {
// This Op was passed down to core and the Op failed
failed_send_ = true;
}
}
void SetInterceptionHookPoint(
InterceptorBatchMethodsImpl* interceptor_methods) {
if (msg_ == nullptr && !send_buf_.Valid()) return;
interceptor_methods->AddInterceptionHookPoint(
experimental::InterceptionHookPoints::PRE_SEND_MESSAGE);
interceptor_methods->SetSendMessage(&send_buf_, &msg_, &failed_send_,
serializer_);
}
void SetFinishInterceptionHookPoint(
InterceptorBatchMethodsImpl* interceptor_methods) {
if (msg_ != nullptr || send_buf_.Valid()) {
interceptor_methods->AddInterceptionHookPoint(
experimental::InterceptionHookPoints::POST_SEND_MESSAGE);
}
send_buf_.Clear();
msg_ = nullptr;
// The contents of the SendMessage value that was previously set
// has had its references stolen by core's operations
interceptor_methods->SetSendMessage(nullptr, nullptr, &failed_send_,
nullptr);
}
void SetHijackingState(InterceptorBatchMethodsImpl* /*interceptor_methods*/) {
hijacked_ = true;
}
private:
const void* msg_ = nullptr; // The original non-serialized message
bool hijacked_ = false;
bool failed_send_ = false;
ByteBuffer send_buf_;
WriteOptions write_options_;
std::function<Status(const void*)> serializer_;
};
template <class M>
Status CallOpSendMessage::SendMessage(const M& message, WriteOptions options) {
write_options_ = options;
// Serialize immediately since we do not have access to the message pointer
bool own_buf;
Status result = SerializationTraits<M>::Serialize(
message, send_buf_.bbuf_ptr(), &own_buf);
if (!own_buf) {
send_buf_.Duplicate();
}
return result;
}
template <class M>
Status CallOpSendMessage::SendMessage(const M& message) {
return SendMessage(message, WriteOptions());
}
template <class M>
Status CallOpSendMessage::SendMessagePtr(const M* message,
WriteOptions options) {
msg_ = message;
write_options_ = options;
// Store the serializer for later since we have access to the message
serializer_ = [this](const void* message) {
bool own_buf;
// TODO(vjpai): Remove the void below when possible
// The void in the template parameter below should not be needed
// (since it should be implicit) but is needed due to an observed
// difference in behavior between clang and gcc for certain internal users
Status result = SerializationTraits<M>::Serialize(
*static_cast<const M*>(message), send_buf_.bbuf_ptr(), &own_buf);
if (!own_buf) {
send_buf_.Duplicate();
}
return result;
};
return Status();
}
template <class M>
Status CallOpSendMessage::SendMessagePtr(const M* message) {
return SendMessagePtr(message, WriteOptions());
}
template <class R>
class CallOpRecvMessage {
public:
void RecvMessage(R* message) { message_ = message; }
// Do not change status if no message is received.
void AllowNoMessage() { allow_not_getting_message_ = true; }
bool got_message = false;
protected:
void AddOp(grpc_op* ops, size_t* nops) {
if (message_ == nullptr || hijacked_) return;
grpc_op* op = &ops[(*nops)++];
op->op = GRPC_OP_RECV_MESSAGE;
op->flags = 0;
op->reserved = nullptr;
op->data.recv_message.recv_message = recv_buf_.c_buffer_ptr();
}
void FinishOp(bool* status) {
if (message_ == nullptr) return;
if (recv_buf_.Valid()) {
if (*status) {
got_message = *status =
SerializationTraits<R>::Deserialize(recv_buf_.bbuf_ptr(), message_)
.ok();
recv_buf_.Release();
} else {
got_message = false;
recv_buf_.Clear();
}
} else if (hijacked_) {
if (hijacked_recv_message_failed_) {
FinishOpRecvMessageFailureHandler(status);
} else {
// The op was hijacked and it was successful. There is no further action
// to be performed since the message is already in its non-serialized
// form.
}
} else {
FinishOpRecvMessageFailureHandler(status);
}
}
void SetInterceptionHookPoint(
InterceptorBatchMethodsImpl* interceptor_methods) {
if (message_ == nullptr) return;
interceptor_methods->SetRecvMessage(message_,
&hijacked_recv_message_failed_);
}
void SetFinishInterceptionHookPoint(
InterceptorBatchMethodsImpl* interceptor_methods) {
if (message_ == nullptr) return;
interceptor_methods->AddInterceptionHookPoint(
experimental::InterceptionHookPoints::POST_RECV_MESSAGE);
if (!got_message) interceptor_methods->SetRecvMessage(nullptr, nullptr);
}
void SetHijackingState(InterceptorBatchMethodsImpl* interceptor_methods) {
hijacked_ = true;
if (message_ == nullptr) return;
interceptor_methods->AddInterceptionHookPoint(
experimental::InterceptionHookPoints::PRE_RECV_MESSAGE);
got_message = true;
}
private:
// Sets got_message and \a status for a failed recv message op
void FinishOpRecvMessageFailureHandler(bool* status) {
got_message = false;
if (!allow_not_getting_message_) {
*status = false;
}
}
R* message_ = nullptr;
ByteBuffer recv_buf_;
bool allow_not_getting_message_ = false;
bool hijacked_ = false;
bool hijacked_recv_message_failed_ = false;
};
class DeserializeFunc {
public:
virtual Status Deserialize(ByteBuffer* buf) = 0;
virtual ~DeserializeFunc() {}
};
template <class R>
class DeserializeFuncType final : public DeserializeFunc {
public:
explicit DeserializeFuncType(R* message) : message_(message) {}
Status Deserialize(ByteBuffer* buf) override {
return SerializationTraits<R>::Deserialize(buf->bbuf_ptr(), message_);
}
~DeserializeFuncType() override {}
private:
R* message_; // Not a managed pointer because management is external to this
};
class CallOpGenericRecvMessage {
public:
template <class R>
void RecvMessage(R* message) {
// Use an explicit base class pointer to avoid resolution error in the
// following unique_ptr::reset for some old implementations.
DeserializeFunc* func = new DeserializeFuncType<R>(message);
deserialize_.reset(func);
message_ = message;
}
// Do not change status if no message is received.
void AllowNoMessage() { allow_not_getting_message_ = true; }
bool got_message = false;
protected:
void AddOp(grpc_op* ops, size_t* nops) {
if (!deserialize_ || hijacked_) return;
grpc_op* op = &ops[(*nops)++];
op->op = GRPC_OP_RECV_MESSAGE;
op->flags = 0;
op->reserved = nullptr;
op->data.recv_message.recv_message = recv_buf_.c_buffer_ptr();
}
void FinishOp(bool* status) {
if (!deserialize_) return;
if (recv_buf_.Valid()) {
if (*status) {
got_message = true;
*status = deserialize_->Deserialize(&recv_buf_).ok();
recv_buf_.Release();
} else {
got_message = false;
recv_buf_.Clear();
}
} else if (hijacked_) {
if (hijacked_recv_message_failed_) {
FinishOpRecvMessageFailureHandler(status);
} else {
// The op was hijacked and it was successful. There is no further action
// to be performed since the message is already in its non-serialized
// form.
}
} else {
got_message = false;
if (!allow_not_getting_message_) {
*status = false;
}
}
}
void SetInterceptionHookPoint(
InterceptorBatchMethodsImpl* interceptor_methods) {
if (!deserialize_) return;
interceptor_methods->SetRecvMessage(message_,
&hijacked_recv_message_failed_);
}
void SetFinishInterceptionHookPoint(
InterceptorBatchMethodsImpl* interceptor_methods) {
if (!deserialize_) return;
interceptor_methods->AddInterceptionHookPoint(
experimental::InterceptionHookPoints::POST_RECV_MESSAGE);
if (!got_message) interceptor_methods->SetRecvMessage(nullptr, nullptr);
deserialize_.reset();
}
void SetHijackingState(InterceptorBatchMethodsImpl* interceptor_methods) {
hijacked_ = true;
if (!deserialize_) return;
interceptor_methods->AddInterceptionHookPoint(
experimental::InterceptionHookPoints::PRE_RECV_MESSAGE);
got_message = true;
}
private:
// Sets got_message and \a status for a failed recv message op
void FinishOpRecvMessageFailureHandler(bool* status) {
got_message = false;
if (!allow_not_getting_message_) {
*status = false;
}
}
void* message_ = nullptr;
std::unique_ptr<DeserializeFunc> deserialize_;
ByteBuffer recv_buf_;
bool allow_not_getting_message_ = false;
bool hijacked_ = false;
bool hijacked_recv_message_failed_ = false;
};
class CallOpClientSendClose {
public:
CallOpClientSendClose() : send_(false) {}
void ClientSendClose() { send_ = true; }
protected:
void AddOp(grpc_op* ops, size_t* nops) {
if (!send_ || hijacked_) return;
grpc_op* op = &ops[(*nops)++];
op->op = GRPC_OP_SEND_CLOSE_FROM_CLIENT;
op->flags = 0;
op->reserved = nullptr;
}
void FinishOp(bool* /*status*/) { send_ = false; }
void SetInterceptionHookPoint(
InterceptorBatchMethodsImpl* interceptor_methods) {
if (!send_) return;
interceptor_methods->AddInterceptionHookPoint(
experimental::InterceptionHookPoints::PRE_SEND_CLOSE);
}
void SetFinishInterceptionHookPoint(
InterceptorBatchMethodsImpl* /*interceptor_methods*/) {}
void SetHijackingState(InterceptorBatchMethodsImpl* /*interceptor_methods*/) {
hijacked_ = true;
}
private:
bool hijacked_ = false;
bool send_;
};
class CallOpServerSendStatus {
public:
CallOpServerSendStatus() : send_status_available_(false) {}
void ServerSendStatus(
std::multimap<std::string, std::string>* trailing_metadata,
const Status& status) {
send_error_details_ = status.error_details();
metadata_map_ = trailing_metadata;
send_status_available_ = true;
send_status_code_ = static_cast<grpc_status_code>(status.error_code());
send_error_message_ = status.error_message();
}
protected:
void AddOp(grpc_op* ops, size_t* nops) {
if (!send_status_available_ || hijacked_) return;
trailing_metadata_ = FillMetadataArray(
*metadata_map_, &trailing_metadata_count_, send_error_details_);
grpc_op* op = &ops[(*nops)++];
op->op = GRPC_OP_SEND_STATUS_FROM_SERVER;
op->data.send_status_from_server.trailing_metadata_count =
trailing_metadata_count_;
op->data.send_status_from_server.trailing_metadata = trailing_metadata_;
op->data.send_status_from_server.status = send_status_code_;
error_message_slice_ = SliceReferencingString(send_error_message_);
op->data.send_status_from_server.status_details =
send_error_message_.empty() ? nullptr : &error_message_slice_;
op->flags = 0;
op->reserved = nullptr;
}
void FinishOp(bool* /*status*/) {
if (!send_status_available_ || hijacked_) return;
gpr_free(trailing_metadata_);
send_status_available_ = false;
}
void SetInterceptionHookPoint(
InterceptorBatchMethodsImpl* interceptor_methods) {
if (!send_status_available_) return;
interceptor_methods->AddInterceptionHookPoint(
experimental::InterceptionHookPoints::PRE_SEND_STATUS);
interceptor_methods->SetSendTrailingMetadata(metadata_map_);
interceptor_methods->SetSendStatus(&send_status_code_, &send_error_details_,
&send_error_message_);
}
void SetFinishInterceptionHookPoint(
InterceptorBatchMethodsImpl* /*interceptor_methods*/) {}
void SetHijackingState(InterceptorBatchMethodsImpl* /*interceptor_methods*/) {
hijacked_ = true;
}
private:
bool hijacked_ = false;
bool send_status_available_;
grpc_status_code send_status_code_;
std::string send_error_details_;
std::string send_error_message_;
size_t trailing_metadata_count_;
std::multimap<std::string, std::string>* metadata_map_;
grpc_metadata* trailing_metadata_;
grpc_slice error_message_slice_;
};
class CallOpRecvInitialMetadata {
public:
CallOpRecvInitialMetadata() : metadata_map_(nullptr) {}
void RecvInitialMetadata(grpc::ClientContext* context) {
context->initial_metadata_received_ = true;
metadata_map_ = &context->recv_initial_metadata_;
}
protected:
void AddOp(grpc_op* ops, size_t* nops) {
if (metadata_map_ == nullptr || hijacked_) return;
grpc_op* op = &ops[(*nops)++];
op->op = GRPC_OP_RECV_INITIAL_METADATA;
op->data.recv_initial_metadata.recv_initial_metadata = metadata_map_->arr();
op->flags = 0;
op->reserved = nullptr;
}
void FinishOp(bool* /*status*/) {
if (metadata_map_ == nullptr || hijacked_) return;
}
void SetInterceptionHookPoint(
InterceptorBatchMethodsImpl* interceptor_methods) {
interceptor_methods->SetRecvInitialMetadata(metadata_map_);
}
void SetFinishInterceptionHookPoint(
InterceptorBatchMethodsImpl* interceptor_methods) {
if (metadata_map_ == nullptr) return;
interceptor_methods->AddInterceptionHookPoint(
experimental::InterceptionHookPoints::POST_RECV_INITIAL_METADATA);
metadata_map_ = nullptr;
}
void SetHijackingState(InterceptorBatchMethodsImpl* interceptor_methods) {
hijacked_ = true;
if (metadata_map_ == nullptr) return;
interceptor_methods->AddInterceptionHookPoint(
experimental::InterceptionHookPoints::PRE_RECV_INITIAL_METADATA);
}
private:
bool hijacked_ = false;
MetadataMap* metadata_map_;
};
class CallOpClientRecvStatus {
public:
CallOpClientRecvStatus()
: recv_status_(nullptr), debug_error_string_(nullptr) {}
void ClientRecvStatus(grpc::ClientContext* context, Status* status) {
client_context_ = context;
metadata_map_ = &client_context_->trailing_metadata_;
recv_status_ = status;
error_message_ = grpc_empty_slice();
}
protected:
void AddOp(grpc_op* ops, size_t* nops) {
if (recv_status_ == nullptr || hijacked_) return;
grpc_op* op = &ops[(*nops)++];
op->op = GRPC_OP_RECV_STATUS_ON_CLIENT;
op->data.recv_status_on_client.trailing_metadata = metadata_map_->arr();
op->data.recv_status_on_client.status = &status_code_;
op->data.recv_status_on_client.status_details = &error_message_;
op->data.recv_status_on_client.error_string = &debug_error_string_;
op->flags = 0;
op->reserved = nullptr;
}
void FinishOp(bool* /*status*/) {
if (recv_status_ == nullptr || hijacked_) return;
if (static_cast<StatusCode>(status_code_) == StatusCode::OK) {
*recv_status_ = Status();
GPR_DEBUG_ASSERT(debug_error_string_ == nullptr);
} else {
*recv_status_ =
Status(static_cast<StatusCode>(status_code_),
GRPC_SLICE_IS_EMPTY(error_message_)
? std::string()
: std::string(GRPC_SLICE_START_PTR(error_message_),
GRPC_SLICE_END_PTR(error_message_)),
metadata_map_->GetBinaryErrorDetails());
if (debug_error_string_ != nullptr) {
client_context_->set_debug_error_string(debug_error_string_);
gpr_free(const_cast<char*>(debug_error_string_));
}
}
// TODO(soheil): Find callers that set debug string even for status OK,
// and fix them.
grpc_slice_unref(error_message_);
}
void SetInterceptionHookPoint(
InterceptorBatchMethodsImpl* interceptor_methods) {
interceptor_methods->SetRecvStatus(recv_status_);
interceptor_methods->SetRecvTrailingMetadata(metadata_map_);
}
void SetFinishInterceptionHookPoint(
InterceptorBatchMethodsImpl* interceptor_methods) {
if (recv_status_ == nullptr) return;
interceptor_methods->AddInterceptionHookPoint(
experimental::InterceptionHookPoints::POST_RECV_STATUS);
recv_status_ = nullptr;
}
void SetHijackingState(InterceptorBatchMethodsImpl* interceptor_methods) {
hijacked_ = true;
if (recv_status_ == nullptr) return;
interceptor_methods->AddInterceptionHookPoint(
experimental::InterceptionHookPoints::PRE_RECV_STATUS);
}
private:
bool hijacked_ = false;
grpc::ClientContext* client_context_;
MetadataMap* metadata_map_;
Status* recv_status_;
const char* debug_error_string_;
grpc_status_code status_code_;
grpc_slice error_message_;
};
template <class Op1 = CallNoOp<1>, class Op2 = CallNoOp<2>,
class Op3 = CallNoOp<3>, class Op4 = CallNoOp<4>,
class Op5 = CallNoOp<5>, class Op6 = CallNoOp<6>>
class CallOpSet;
/// Primary implementation of CallOpSetInterface.
/// Since we cannot use variadic templates, we declare slots up to
/// the maximum count of ops we'll need in a set. We leverage the
/// empty base class optimization to slim this class (especially
/// when there are many unused slots used). To avoid duplicate base classes,
/// the template parameter for CallNoOp is varied by argument position.
template <class Op1, class Op2, class Op3, class Op4, class Op5, class Op6>
class CallOpSet : public CallOpSetInterface,
public Op1,
public Op2,
public Op3,
public Op4,
public Op5,
public Op6 {
public:
CallOpSet() : core_cq_tag_(this), return_tag_(this) {}
// The copy constructor and assignment operator reset the value of
// core_cq_tag_, return_tag_, done_intercepting_ and interceptor_methods_
// since those are only meaningful on a specific object, not across objects.
CallOpSet(const CallOpSet& other)
: core_cq_tag_(this),
return_tag_(this),
call_(other.call_),
done_intercepting_(false),
interceptor_methods_(InterceptorBatchMethodsImpl()) {}
CallOpSet& operator=(const CallOpSet& other) {
if (&other == this) {
return *this;
}
core_cq_tag_ = this;
return_tag_ = this;
call_ = other.call_;
done_intercepting_ = false;
interceptor_methods_ = InterceptorBatchMethodsImpl();
return *this;
}
void FillOps(Call* call) override {
done_intercepting_ = false;
grpc_call_ref(call->call());
call_ =
*call; // It's fine to create a copy of call since it's just pointers
if (RunInterceptors()) {
ContinueFillOpsAfterInterception();
} else {
// After the interceptors are run, ContinueFillOpsAfterInterception will
// be run
}
}
bool FinalizeResult(void** tag, bool* status) override {
if (done_intercepting_) {
// Complete the avalanching since we are done with this batch of ops
call_.cq()->CompleteAvalanching();
// We have already finished intercepting and filling in the results. This
// round trip from the core needed to be made because interceptors were
// run
*tag = return_tag_;
*status = saved_status_;
grpc_call_unref(call_.call());
return true;
}
this->Op1::FinishOp(status);
this->Op2::FinishOp(status);
this->Op3::FinishOp(status);
this->Op4::FinishOp(status);
this->Op5::FinishOp(status);
this->Op6::FinishOp(status);
saved_status_ = *status;
if (RunInterceptorsPostRecv()) {
*tag = return_tag_;
grpc_call_unref(call_.call());
return true;
}
// Interceptors are going to be run, so we can't return the tag just yet.
// After the interceptors are run, ContinueFinalizeResultAfterInterception
return false;
}
void set_output_tag(void* return_tag) { return_tag_ = return_tag; }
void* core_cq_tag() override { return core_cq_tag_; }
/// set_core_cq_tag is used to provide a different core CQ tag than "this".
/// This is used for callback-based tags, where the core tag is the core
/// callback function. It does not change the use or behavior of any other
/// function (such as FinalizeResult)
void set_core_cq_tag(void* core_cq_tag) { core_cq_tag_ = core_cq_tag; }
// This will be called while interceptors are run if the RPC is a hijacked
// RPC. This should set hijacking state for each of the ops.
void SetHijackingState() override {
this->Op1::SetHijackingState(&interceptor_methods_);
this->Op2::SetHijackingState(&interceptor_methods_);
this->Op3::SetHijackingState(&interceptor_methods_);
this->Op4::SetHijackingState(&interceptor_methods_);
this->Op5::SetHijackingState(&interceptor_methods_);
this->Op6::SetHijackingState(&interceptor_methods_);
}
// Should be called after interceptors are done running
void ContinueFillOpsAfterInterception() override {
static const size_t MAX_OPS = 6;
grpc_op ops[MAX_OPS];
size_t nops = 0;
this->Op1::AddOp(ops, &nops);
this->Op2::AddOp(ops, &nops);
this->Op3::AddOp(ops, &nops);
this->Op4::AddOp(ops, &nops);
this->Op5::AddOp(ops, &nops);
this->Op6::AddOp(ops, &nops);
grpc_call_error err =
grpc_call_start_batch(call_.call(), ops, nops, core_cq_tag(), nullptr);
if (err != GRPC_CALL_OK) {
// A failure here indicates an API misuse; for example, doing a Write
// while another Write is already pending on the same RPC or invoking
// WritesDone multiple times
gpr_log(GPR_ERROR, "API misuse of type %s observed",
grpc_call_error_to_string(err));
GPR_ASSERT(false);
}
}
// Should be called after interceptors are done running on the finalize result
// path
void ContinueFinalizeResultAfterInterception() override {
done_intercepting_ = true;
// The following call_start_batch is internally-generated so no need for an
// explanatory log on failure.
GPR_ASSERT(grpc_call_start_batch(call_.call(), nullptr, 0, core_cq_tag(),
nullptr) == GRPC_CALL_OK);
}
private:
// Returns true if no interceptors need to be run
bool RunInterceptors() {
interceptor_methods_.ClearState();
interceptor_methods_.SetCallOpSetInterface(this);
interceptor_methods_.SetCall(&call_);
this->Op1::SetInterceptionHookPoint(&interceptor_methods_);
this->Op2::SetInterceptionHookPoint(&interceptor_methods_);
this->Op3::SetInterceptionHookPoint(&interceptor_methods_);
this->Op4::SetInterceptionHookPoint(&interceptor_methods_);
this->Op5::SetInterceptionHookPoint(&interceptor_methods_);
this->Op6::SetInterceptionHookPoint(&interceptor_methods_);
if (interceptor_methods_.InterceptorsListEmpty()) {
return true;
}
// This call will go through interceptors and would need to
// schedule new batches, so delay completion queue shutdown
call_.cq()->RegisterAvalanching();
return interceptor_methods_.RunInterceptors();
}
// Returns true if no interceptors need to be run
bool RunInterceptorsPostRecv() {
// Call and OpSet had already been set on the set state.
// SetReverse also clears previously set hook points
interceptor_methods_.SetReverse();
this->Op1::SetFinishInterceptionHookPoint(&interceptor_methods_);
this->Op2::SetFinishInterceptionHookPoint(&interceptor_methods_);
this->Op3::SetFinishInterceptionHookPoint(&interceptor_methods_);
this->Op4::SetFinishInterceptionHookPoint(&interceptor_methods_);
this->Op5::SetFinishInterceptionHookPoint(&interceptor_methods_);
this->Op6::SetFinishInterceptionHookPoint(&interceptor_methods_);
return interceptor_methods_.RunInterceptors();
}
void* core_cq_tag_;
void* return_tag_;
Call call_;
bool done_intercepting_ = false;
InterceptorBatchMethodsImpl interceptor_methods_;
bool saved_status_;
};
} // namespace internal
} // namespace grpc
#endif // GRPCPP_IMPL_CALL_OP_SET_H

View File

@@ -0,0 +1,61 @@
//
//
// Copyright 2018 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CALL_OP_SET_INTERFACE_H
#define GRPCPP_IMPL_CALL_OP_SET_INTERFACE_H
// IWYU pragma: private
#include <grpcpp/impl/completion_queue_tag.h>
namespace grpc {
namespace internal {
class Call;
/// An abstract collection of call ops, used to generate the
/// grpc_call_op structure to pass down to the lower layers,
/// and as it is-a CompletionQueueTag, also massages the final
/// completion into the correct form for consumption in the C++
/// API.
class CallOpSetInterface : public CompletionQueueTag {
public:
/// Fills in grpc_op, starting from ops[*nops] and moving
/// upwards.
virtual void FillOps(internal::Call* call) = 0;
/// Get the tag to be used at the core completion queue. Generally, the
/// value of core_cq_tag will be "this". However, it can be overridden if we
/// want core to process the tag differently (e.g., as a core callback)
virtual void* core_cq_tag() = 0;
// This will be called while interceptors are run if the RPC is a hijacked
// RPC. This should set hijacking state for each of the ops.
virtual void SetHijackingState() = 0;
// Should be called after interceptors are done running
virtual void ContinueFillOpsAfterInterception() = 0;
// Should be called after interceptors are done running on the finalize result
// path
virtual void ContinueFinalizeResultAfterInterception() = 0;
};
} // namespace internal
} // namespace grpc
#endif // GRPCPP_IMPL_CALL_OP_SET_INTERFACE_H

View File

@@ -0,0 +1,39 @@
//
//
// Copyright 2017 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CHANNEL_ARGUMENT_OPTION_H
#define GRPCPP_IMPL_CHANNEL_ARGUMENT_OPTION_H
#include <map>
#include <memory>
#include <grpcpp/impl/server_builder_option.h>
#include <grpcpp/support/channel_arguments.h>
namespace grpc {
std::unique_ptr<ServerBuilderOption> MakeChannelArgumentOption(
const std::string& name, const std::string& value);
std::unique_ptr<ServerBuilderOption> MakeChannelArgumentOption(
const std::string& name, int value);
std::unique_ptr<ServerBuilderOption> MakeChannelArgumentOption(
const std::string& name, void* value);
} // namespace grpc
#endif // GRPCPP_IMPL_CHANNEL_ARGUMENT_OPTION_H

View File

@@ -0,0 +1,170 @@
//
//
// Copyright 2016 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CHANNEL_INTERFACE_H
#define GRPCPP_IMPL_CHANNEL_INTERFACE_H
#include <grpc/impl/connectivity_state.h>
#include <grpcpp/impl/call.h>
#include <grpcpp/support/status.h>
#include <grpcpp/support/time.h>
namespace grpc {
template <class R>
class ClientReader;
template <class W>
class ClientWriter;
template <class W, class R>
class ClientReaderWriter;
namespace internal {
template <class InputMessage, class OutputMessage>
class CallbackUnaryCallImpl;
template <class R>
class ClientAsyncReaderFactory;
template <class W>
class ClientAsyncWriterFactory;
template <class W, class R>
class ClientAsyncReaderWriterFactory;
class ClientAsyncResponseReaderHelper;
template <class W, class R>
class ClientCallbackReaderWriterFactory;
template <class R>
class ClientCallbackReaderFactory;
template <class W>
class ClientCallbackWriterFactory;
class ClientCallbackUnaryFactory;
} // namespace internal
class ChannelInterface;
class ClientContext;
class CompletionQueue;
namespace experimental {
class DelegatingChannel;
}
namespace internal {
class Call;
class CallOpSetInterface;
class RpcMethod;
class InterceptedChannel;
template <class InputMessage, class OutputMessage>
class BlockingUnaryCallImpl;
} // namespace internal
/// Codegen interface for \a grpc::Channel.
class ChannelInterface {
public:
virtual ~ChannelInterface() {}
/// Get the current channel state. If the channel is in IDLE and
/// \a try_to_connect is set to true, try to connect.
virtual grpc_connectivity_state GetState(bool try_to_connect) = 0;
/// Return the \a tag on \a cq when the channel state is changed or \a
/// deadline expires. \a GetState needs to called to get the current state.
template <typename T>
void NotifyOnStateChange(grpc_connectivity_state last_observed, T deadline,
grpc::CompletionQueue* cq, void* tag) {
TimePoint<T> deadline_tp(deadline);
NotifyOnStateChangeImpl(last_observed, deadline_tp.raw_time(), cq, tag);
}
/// Blocking wait for channel state change or \a deadline expiration.
/// \a GetState needs to called to get the current state.
template <typename T>
bool WaitForStateChange(grpc_connectivity_state last_observed, T deadline) {
TimePoint<T> deadline_tp(deadline);
return WaitForStateChangeImpl(last_observed, deadline_tp.raw_time());
}
/// Wait for this channel to be connected
template <typename T>
bool WaitForConnected(T deadline) {
grpc_connectivity_state state;
while ((state = GetState(true)) != GRPC_CHANNEL_READY) {
if (!WaitForStateChange(state, deadline)) return false;
}
return true;
}
private:
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::internal::ClientAsyncReaderFactory;
template <class W>
friend class grpc::internal::ClientAsyncWriterFactory;
template <class W, class R>
friend class grpc::internal::ClientAsyncReaderWriterFactory;
friend class grpc::internal::ClientAsyncResponseReaderHelper;
template <class W, class R>
friend class grpc::internal::ClientCallbackReaderWriterFactory;
template <class R>
friend class grpc::internal::ClientCallbackReaderFactory;
template <class W>
friend class grpc::internal::ClientCallbackWriterFactory;
friend class grpc::internal::ClientCallbackUnaryFactory;
template <class InputMessage, class OutputMessage>
friend class grpc::internal::BlockingUnaryCallImpl;
template <class InputMessage, class OutputMessage>
friend class grpc::internal::CallbackUnaryCallImpl;
friend class grpc::internal::RpcMethod;
friend class grpc::experimental::DelegatingChannel;
friend class grpc::internal::InterceptedChannel;
virtual internal::Call CreateCall(const internal::RpcMethod& method,
grpc::ClientContext* context,
grpc::CompletionQueue* cq) = 0;
virtual void PerformOpsOnCall(internal::CallOpSetInterface* ops,
internal::Call* call) = 0;
virtual void* RegisterMethod(const char* method) = 0;
virtual void NotifyOnStateChangeImpl(grpc_connectivity_state last_observed,
gpr_timespec deadline,
grpc::CompletionQueue* cq,
void* tag) = 0;
virtual bool WaitForStateChangeImpl(grpc_connectivity_state last_observed,
gpr_timespec deadline) = 0;
// EXPERIMENTAL
// This is needed to keep codegen_test_minimal happy. InterceptedChannel needs
// to make use of this but can't directly call Channel's implementation
// because of the test.
// Returns an empty Call object (rather than being pure) since this is a new
// method and adding a new pure method to an interface would be a breaking
// change (even though this is private and non-API)
virtual internal::Call CreateCallInternal(
const internal::RpcMethod& /*method*/, grpc::ClientContext* /*context*/,
grpc::CompletionQueue* /*cq*/, size_t /*interceptor_pos*/) {
return internal::Call();
}
// A method to get the callbackable completion queue associated with this
// channel. If the return value is nullptr, this channel doesn't support
// callback operations.
// TODO(vjpai): Consider a better default like using a global CQ
// Returns nullptr (rather than being pure) since this is a post-1.0 method
// and adding a new pure method to an interface would be a breaking change
// (even though this is private and non-API)
virtual grpc::CompletionQueue* CallbackCQ() { return nullptr; }
};
} // namespace grpc
#endif // GRPCPP_IMPL_CHANNEL_INTERFACE_H

View File

@@ -0,0 +1,102 @@
//
//
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CLIENT_UNARY_CALL_H
#define GRPCPP_IMPL_CLIENT_UNARY_CALL_H
#include <grpcpp/impl/call.h>
#include <grpcpp/impl/call_op_set.h>
#include <grpcpp/impl/channel_interface.h>
#include <grpcpp/support/config.h>
#include <grpcpp/support/status.h>
namespace grpc {
class ClientContext;
namespace internal {
class RpcMethod;
/// Wrapper that performs a blocking unary call. May optionally specify the base
/// class of the Request and Response so that the internal calls and structures
/// below this may be based on those base classes and thus achieve code reuse
/// across different RPCs (e.g., for protobuf, MessageLite would be a base
/// class).
template <class InputMessage, class OutputMessage,
class BaseInputMessage = InputMessage,
class BaseOutputMessage = OutputMessage>
Status BlockingUnaryCall(ChannelInterface* channel, const RpcMethod& method,
grpc::ClientContext* context,
const InputMessage& request, OutputMessage* result) {
static_assert(std::is_base_of<BaseInputMessage, InputMessage>::value,
"Invalid input message specification");
static_assert(std::is_base_of<BaseOutputMessage, OutputMessage>::value,
"Invalid output message specification");
return BlockingUnaryCallImpl<BaseInputMessage, BaseOutputMessage>(
channel, method, context, request, result)
.status();
}
template <class InputMessage, class OutputMessage>
class BlockingUnaryCallImpl {
public:
BlockingUnaryCallImpl(ChannelInterface* channel, const RpcMethod& method,
grpc::ClientContext* context,
const InputMessage& request, OutputMessage* result) {
grpc::CompletionQueue cq(grpc_completion_queue_attributes{
GRPC_CQ_CURRENT_VERSION, GRPC_CQ_PLUCK, GRPC_CQ_DEFAULT_POLLING,
nullptr}); // Pluckable completion queue
grpc::internal::Call call(channel->CreateCall(method, context, &cq));
CallOpSet<CallOpSendInitialMetadata, CallOpSendMessage,
CallOpRecvInitialMetadata, CallOpRecvMessage<OutputMessage>,
CallOpClientSendClose, CallOpClientRecvStatus>
ops;
status_ = ops.SendMessagePtr(&request);
if (!status_.ok()) {
return;
}
ops.SendInitialMetadata(&context->send_initial_metadata_,
context->initial_metadata_flags());
ops.RecvInitialMetadata(context);
ops.RecvMessage(result);
ops.AllowNoMessage();
ops.ClientSendClose();
ops.ClientRecvStatus(context, &status_);
call.PerformOps(&ops);
cq.Pluck(&ops);
// Some of the ops might fail. If the ops fail in the core layer, status
// would reflect the error. But, if the ops fail in the C++ layer, the
// status would still be the same as the one returned by gRPC Core. This can
// happen if deserialization of the message fails.
// TODO(yashykt): If deserialization fails, but the status received is OK,
// then it might be a good idea to change the status to something better
// than StatusCode::UNIMPLEMENTED to reflect this.
if (!ops.got_message && status_.ok()) {
status_ = Status(StatusCode::UNIMPLEMENTED,
"No message returned for unary request");
}
}
Status status() { return status_; }
private:
Status status_;
};
} // namespace internal
} // namespace grpc
#endif // GRPCPP_IMPL_CLIENT_UNARY_CALL_H

View File

@@ -0,0 +1,27 @@
//
//
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CODEGEN_ASYNC_GENERIC_SERVICE_H
#define GRPCPP_IMPL_CODEGEN_ASYNC_GENERIC_SERVICE_H
// IWYU pragma: private
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/generic/async_generic_service.h>
#endif // GRPCPP_IMPL_CODEGEN_ASYNC_GENERIC_SERVICE_H

View File

@@ -0,0 +1,26 @@
//
//
// Copyright 2019 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef GRPCPP_IMPL_CODEGEN_ASYNC_STREAM_H
#define GRPCPP_IMPL_CODEGEN_ASYNC_STREAM_H
// IWYU pragma: private
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/support/async_stream.h>
#endif // GRPCPP_IMPL_CODEGEN_ASYNC_STREAM_H

View File

@@ -0,0 +1,27 @@
//
//
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CODEGEN_ASYNC_UNARY_CALL_H
#define GRPCPP_IMPL_CODEGEN_ASYNC_UNARY_CALL_H
// IWYU pragma: private
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/support/async_unary_call.h>
#endif // GRPCPP_IMPL_CODEGEN_ASYNC_UNARY_CALL_H

View File

@@ -0,0 +1,27 @@
//
//
// Copyright 2017 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CODEGEN_BYTE_BUFFER_H
#define GRPCPP_IMPL_CODEGEN_BYTE_BUFFER_H
// IWYU pragma: private
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/support/byte_buffer.h>
#endif // GRPCPP_IMPL_CODEGEN_BYTE_BUFFER_H

View File

@@ -0,0 +1,26 @@
//
//
// Copyright 2018 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CODEGEN_CALL_H
#define GRPCPP_IMPL_CODEGEN_CALL_H
// IWYU pragma: private
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/impl/call.h>
#endif // GRPCPP_IMPL_CODEGEN_CALL_H

View File

@@ -0,0 +1,27 @@
//
//
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CODEGEN_CALL_HOOK_H
#define GRPCPP_IMPL_CODEGEN_CALL_HOOK_H
// IWYU pragma: private
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/impl/call_hook.h>
#endif // GRPCPP_IMPL_CODEGEN_CALL_HOOK_H

View File

@@ -0,0 +1,27 @@
//
//
// Copyright 2018 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CODEGEN_CALL_OP_SET_H
#define GRPCPP_IMPL_CODEGEN_CALL_OP_SET_H
// IWYU pragma: private
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/impl/call_op_set.h>
#endif // GRPCPP_IMPL_CODEGEN_CALL_OP_SET_H

View File

@@ -0,0 +1,26 @@
//
//
// Copyright 2018 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CODEGEN_CALL_OP_SET_INTERFACE_H
#define GRPCPP_IMPL_CODEGEN_CALL_OP_SET_INTERFACE_H
// IWYU pragma: private
#include <grpcpp/impl/call_op_set_interface.h>
#endif // GRPCPP_IMPL_CODEGEN_CALL_OP_SET_INTERFACE_H

View File

@@ -0,0 +1,27 @@
//
//
// Copyright 2018 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CODEGEN_CALLBACK_COMMON_H
#define GRPCPP_IMPL_CODEGEN_CALLBACK_COMMON_H
// IWYU pragma: private
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/support/callback_common.h>
#endif // GRPCPP_IMPL_CODEGEN_CALLBACK_COMMON_H

View File

@@ -0,0 +1,27 @@
//
//
// Copyright 2016 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CODEGEN_CHANNEL_INTERFACE_H
#define GRPCPP_IMPL_CODEGEN_CHANNEL_INTERFACE_H
// IWYU pragma: private
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/impl/channel_interface.h>
#endif // GRPCPP_IMPL_CODEGEN_CHANNEL_INTERFACE_H

View File

@@ -0,0 +1,26 @@
//
//
// Copyright 2019 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef GRPCPP_IMPL_CODEGEN_CLIENT_CALLBACK_H
#define GRPCPP_IMPL_CODEGEN_CLIENT_CALLBACK_H
// IWYU pragma: private
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/support/client_callback.h>
#endif // GRPCPP_IMPL_CODEGEN_CLIENT_CALLBACK_H

View File

@@ -0,0 +1,27 @@
//
//
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CODEGEN_CLIENT_CONTEXT_H
#define GRPCPP_IMPL_CODEGEN_CLIENT_CONTEXT_H
// IWYU pragma: private
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/client_context.h>
#endif // GRPCPP_IMPL_CODEGEN_CLIENT_CONTEXT_H

View File

@@ -0,0 +1,27 @@
//
//
// Copyright 2018 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CODEGEN_CLIENT_INTERCEPTOR_H
#define GRPCPP_IMPL_CODEGEN_CLIENT_INTERCEPTOR_H
// IWYU pragma: private
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/support/client_interceptor.h>
#endif // GRPCPP_IMPL_CODEGEN_CLIENT_INTERCEPTOR_H

View File

@@ -0,0 +1,27 @@
//
//
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CODEGEN_CLIENT_UNARY_CALL_H
#define GRPCPP_IMPL_CODEGEN_CLIENT_UNARY_CALL_H
// IWYU pragma: private
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/impl/client_unary_call.h>
#endif // GRPCPP_IMPL_CODEGEN_CLIENT_UNARY_CALL_H

View File

@@ -0,0 +1,27 @@
//
//
// Copyright 2015-2016 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CODEGEN_COMPLETION_QUEUE_H
#define GRPCPP_IMPL_CODEGEN_COMPLETION_QUEUE_H
// IWYU pragma: private
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/completion_queue.h>
#endif // GRPCPP_IMPL_CODEGEN_COMPLETION_QUEUE_H

View File

@@ -0,0 +1,27 @@
//
//
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CODEGEN_COMPLETION_QUEUE_TAG_H
#define GRPCPP_IMPL_CODEGEN_COMPLETION_QUEUE_TAG_H
// IWYU pragma: private
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/impl/completion_queue_tag.h>
#endif // GRPCPP_IMPL_CODEGEN_COMPLETION_QUEUE_TAG_H

View File

@@ -0,0 +1,27 @@
//
//
// Copyright 2016 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CODEGEN_CONFIG_H
#define GRPCPP_IMPL_CODEGEN_CONFIG_H
// IWYU pragma: private
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/support/config.h>
#endif // GRPCPP_IMPL_CODEGEN_CONFIG_H

View File

@@ -0,0 +1,27 @@
//
//
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CODEGEN_CREATE_AUTH_CONTEXT_H
#define GRPCPP_IMPL_CODEGEN_CREATE_AUTH_CONTEXT_H
// IWYU pragma: private
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/impl/create_auth_context.h>
#endif // GRPCPP_IMPL_CODEGEN_CREATE_AUTH_CONTEXT_H

View File

@@ -0,0 +1,27 @@
//
//
// Copyright 2019 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CODEGEN_DELEGATING_CHANNEL_H
#define GRPCPP_IMPL_CODEGEN_DELEGATING_CHANNEL_H
// IWYU pragma: private
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/impl/delegating_channel.h>
#endif // GRPCPP_IMPL_CODEGEN_DELEGATING_CHANNEL_H

View File

@@ -0,0 +1,27 @@
//
//
// Copyright 2018 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CODEGEN_INTERCEPTED_CHANNEL_H
#define GRPCPP_IMPL_CODEGEN_INTERCEPTED_CHANNEL_H
// IWYU pragma: private
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/impl/intercepted_channel.h>
#endif // GRPCPP_IMPL_CODEGEN_INTERCEPTED_CHANNEL_H

View File

@@ -0,0 +1,27 @@
//
//
// Copyright 2018 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CODEGEN_INTERCEPTOR_H
#define GRPCPP_IMPL_CODEGEN_INTERCEPTOR_H
// IWYU pragma: private
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/support/interceptor.h>
#endif // GRPCPP_IMPL_CODEGEN_INTERCEPTOR_H

View File

@@ -0,0 +1,27 @@
//
//
// Copyright 2018 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CODEGEN_INTERCEPTOR_COMMON_H
#define GRPCPP_IMPL_CODEGEN_INTERCEPTOR_COMMON_H
// IWYU pragma: private
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/impl/interceptor_common.h>
#endif // GRPCPP_IMPL_CODEGEN_INTERCEPTOR_COMMON_H

View File

@@ -0,0 +1,27 @@
//
//
// Copyright 2019 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CODEGEN_MESSAGE_ALLOCATOR_H
#define GRPCPP_IMPL_CODEGEN_MESSAGE_ALLOCATOR_H
// IWYU pragma: private
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/support/message_allocator.h>
#endif // GRPCPP_IMPL_CODEGEN_MESSAGE_ALLOCATOR_H

View File

@@ -0,0 +1,27 @@
//
//
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CODEGEN_METADATA_MAP_H
#define GRPCPP_IMPL_CODEGEN_METADATA_MAP_H
// IWYU pragma: private
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/impl/metadata_map.h>
#endif // GRPCPP_IMPL_CODEGEN_METADATA_MAP_H

View File

@@ -0,0 +1,27 @@
//
//
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CODEGEN_METHOD_HANDLER_H
#define GRPCPP_IMPL_CODEGEN_METHOD_HANDLER_H
// IWYU pragma: private
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/support/method_handler.h>
#endif // GRPCPP_IMPL_CODEGEN_METHOD_HANDLER_H

View File

@@ -0,0 +1,24 @@
//
//
// Copyright 2018 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CODEGEN_METHOD_HANDLER_IMPL_H
#define GRPCPP_IMPL_CODEGEN_METHOD_HANDLER_IMPL_H
// IWYU pragma: private
#endif // GRPCPP_IMPL_CODEGEN_METHOD_HANDLER_IMPL_H

View File

@@ -0,0 +1,27 @@
//
//
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CODEGEN_RPC_METHOD_H
#define GRPCPP_IMPL_CODEGEN_RPC_METHOD_H
// IWYU pragma: private
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/impl/rpc_method.h>
#endif // GRPCPP_IMPL_CODEGEN_RPC_METHOD_H

View File

@@ -0,0 +1,27 @@
//
//
// Copyright 2016 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CODEGEN_RPC_SERVICE_METHOD_H
#define GRPCPP_IMPL_CODEGEN_RPC_SERVICE_METHOD_H
// IWYU pragma: private
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/impl/rpc_service_method.h>
#endif // GRPCPP_IMPL_CODEGEN_RPC_SERVICE_METHOD_H

View File

@@ -0,0 +1,27 @@
//
//
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CODEGEN_SECURITY_AUTH_CONTEXT_H
#define GRPCPP_IMPL_CODEGEN_SECURITY_AUTH_CONTEXT_H
// IWYU pragma: private
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/security/auth_context.h>
#endif // GRPCPP_IMPL_CODEGEN_SECURITY_AUTH_CONTEXT_H

View File

@@ -0,0 +1,27 @@
//
//
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CODEGEN_SERIALIZATION_TRAITS_H
#define GRPCPP_IMPL_CODEGEN_SERIALIZATION_TRAITS_H
// IWYU pragma: private
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/impl/serialization_traits.h>
#endif // GRPCPP_IMPL_CODEGEN_SERIALIZATION_TRAITS_H

View File

@@ -0,0 +1,26 @@
//
//
// Copyright 2019 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef GRPCPP_IMPL_CODEGEN_SERVER_CALLBACK_H
#define GRPCPP_IMPL_CODEGEN_SERVER_CALLBACK_H
// IWYU pragma: private
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/support/server_callback.h>
#endif // GRPCPP_IMPL_CODEGEN_SERVER_CALLBACK_H

View File

@@ -0,0 +1,26 @@
//
//
// Copyright 2019 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef GRPCPP_IMPL_CODEGEN_SERVER_CALLBACK_HANDLERS_H
#define GRPCPP_IMPL_CODEGEN_SERVER_CALLBACK_HANDLERS_H
// IWYU pragma: private
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/impl/server_callback_handlers.h>
#endif // GRPCPP_IMPL_CODEGEN_SERVER_CALLBACK_HANDLERS_H

View File

@@ -0,0 +1,27 @@
//
//
// Copyright 2019 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CODEGEN_SERVER_CONTEXT_H
#define GRPCPP_IMPL_CODEGEN_SERVER_CONTEXT_H
// IWYU pragma: private
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/server_context.h>
#endif // GRPCPP_IMPL_CODEGEN_SERVER_CONTEXT_H

View File

@@ -0,0 +1,27 @@
//
//
// Copyright 2018 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CODEGEN_SERVER_INTERCEPTOR_H
#define GRPCPP_IMPL_CODEGEN_SERVER_INTERCEPTOR_H
// IWYU pragma: private
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/support/server_interceptor.h>
#endif // GRPCPP_IMPL_CODEGEN_SERVER_INTERCEPTOR_H

View File

@@ -0,0 +1,27 @@
//
//
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CODEGEN_SERVER_INTERFACE_H
#define GRPCPP_IMPL_CODEGEN_SERVER_INTERFACE_H
// IWYU pragma: private
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/server_interface.h>
#endif // GRPCPP_IMPL_CODEGEN_SERVER_INTERFACE_H

View File

@@ -0,0 +1,27 @@
//
//
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CODEGEN_SERVICE_TYPE_H
#define GRPCPP_IMPL_CODEGEN_SERVICE_TYPE_H
// IWYU pragma: private
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/impl/service_type.h>
#endif // GRPCPP_IMPL_CODEGEN_SERVICE_TYPE_H

View File

@@ -0,0 +1,27 @@
//
//
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CODEGEN_SLICE_H
#define GRPCPP_IMPL_CODEGEN_SLICE_H
// IWYU pragma: private
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/support/slice.h>
#endif // GRPCPP_IMPL_CODEGEN_SLICE_H

View File

@@ -0,0 +1,27 @@
//
//
// Copyright 2016 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CODEGEN_STATUS_H
#define GRPCPP_IMPL_CODEGEN_STATUS_H
// IWYU pragma: private
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/support/status.h>
#endif // GRPCPP_IMPL_CODEGEN_STATUS_H

View File

@@ -0,0 +1,27 @@
//
//
// Copyright 2016 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CODEGEN_STATUS_CODE_ENUM_H
#define GRPCPP_IMPL_CODEGEN_STATUS_CODE_ENUM_H
// IWYU pragma: private, include <grpcpp/support/status.h>
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/support/status_code_enum.h>
#endif // GRPCPP_IMPL_CODEGEN_STATUS_CODE_ENUM_H

View File

@@ -0,0 +1,27 @@
//
//
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CODEGEN_STRING_REF_H
#define GRPCPP_IMPL_CODEGEN_STRING_REF_H
// IWYU pragma: private
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/support/string_ref.h>
#endif // GRPCPP_IMPL_CODEGEN_STRING_REF_H

View File

@@ -0,0 +1,27 @@
//
//
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CODEGEN_STUB_OPTIONS_H
#define GRPCPP_IMPL_CODEGEN_STUB_OPTIONS_H
// IWYU pragma: private
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/support/stub_options.h>
#endif // GRPCPP_IMPL_CODEGEN_STUB_OPTIONS_H

View File

@@ -0,0 +1,27 @@
//
//
// Copyright 2019 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CODEGEN_SYNC_H
#define GRPCPP_IMPL_CODEGEN_SYNC_H
// IWYU pragma: private
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/impl/sync.h>
#endif // GRPCPP_IMPL_CODEGEN_SYNC_H

View File

@@ -0,0 +1,26 @@
//
//
// Copyright 2019 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef GRPCPP_IMPL_CODEGEN_SYNC_STREAM_H
#define GRPCPP_IMPL_CODEGEN_SYNC_STREAM_H
// IWYU pragma: private
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/support/sync_stream.h>
#endif // GRPCPP_IMPL_CODEGEN_SYNC_STREAM_H

View File

@@ -0,0 +1,27 @@
//
//
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CODEGEN_TIME_H
#define GRPCPP_IMPL_CODEGEN_TIME_H
// IWYU pragma: private
/// TODO(chengyuc): Remove this file after solving compatibility.
#include <grpcpp/support/time.h>
#endif // GRPCPP_IMPL_CODEGEN_TIME_H

View File

@@ -0,0 +1,54 @@
//
//
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_COMPLETION_QUEUE_TAG_H
#define GRPCPP_IMPL_COMPLETION_QUEUE_TAG_H
namespace grpc {
namespace internal {
/// An interface allowing implementors to process and filter event tags.
class CompletionQueueTag {
public:
virtual ~CompletionQueueTag() {}
/// FinalizeResult must be called before informing user code that the
/// operation bound to the underlying core completion queue tag has
/// completed. In practice, this means:
///
/// 1. For the sync API - before returning from Pluck
/// 2. For the CQ-based async API - before returning from Next
/// 3. For the callback-based API - before invoking the user callback
///
/// This is the method that translates from core-side tag/status to
/// C++ API-observable tag/status.
///
/// The return value is the status of the operation (returning status is the
/// general behavior of this function). If this function returns false, the
/// tag is dropped and not returned from the completion queue: this concept is
/// for events that are observed at core but not requested by the user
/// application (e.g., server shutdown, for server unimplemented method
/// responses, or for cases where a server-side RPC doesn't have a completion
/// notification registered using AsyncNotifyWhenDone)
virtual bool FinalizeResult(void** tag, bool* status) = 0;
};
} // namespace internal
} // namespace grpc
#endif // GRPCPP_IMPL_COMPLETION_QUEUE_TAG_H

View File

@@ -0,0 +1,34 @@
//
//
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_CREATE_AUTH_CONTEXT_H
#define GRPCPP_IMPL_CREATE_AUTH_CONTEXT_H
#include <memory>
#include <grpc/impl/grpc_types.h>
#include <grpcpp/security/auth_context.h>
namespace grpc {
/// TODO(ctiller): not sure we want to make this a permanent thing
std::shared_ptr<const AuthContext> CreateAuthContext(grpc_call* call);
} // namespace grpc
#endif // GRPCPP_IMPL_CREATE_AUTH_CONTEXT_H

View File

@@ -0,0 +1,91 @@
//
//
// Copyright 2019 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_DELEGATING_CHANNEL_H
#define GRPCPP_IMPL_DELEGATING_CHANNEL_H
#include <memory>
#include <grpcpp/impl/channel_interface.h>
namespace grpc {
namespace experimental {
class DelegatingChannel : public grpc::ChannelInterface {
public:
~DelegatingChannel() override {}
explicit DelegatingChannel(
std::shared_ptr<grpc::ChannelInterface> delegate_channel)
: delegate_channel_(delegate_channel) {}
grpc_connectivity_state GetState(bool try_to_connect) override {
return delegate_channel()->GetState(try_to_connect);
}
std::shared_ptr<grpc::ChannelInterface> delegate_channel() {
return delegate_channel_;
}
private:
internal::Call CreateCall(const internal::RpcMethod& method,
ClientContext* context,
grpc::CompletionQueue* cq) final {
return delegate_channel()->CreateCall(method, context, cq);
}
void PerformOpsOnCall(internal::CallOpSetInterface* ops,
internal::Call* call) final {
delegate_channel()->PerformOpsOnCall(ops, call);
}
void* RegisterMethod(const char* method) final {
return delegate_channel()->RegisterMethod(method);
}
void NotifyOnStateChangeImpl(grpc_connectivity_state last_observed,
gpr_timespec deadline, grpc::CompletionQueue* cq,
void* tag) override {
delegate_channel()->NotifyOnStateChangeImpl(last_observed, deadline, cq,
tag);
}
bool WaitForStateChangeImpl(grpc_connectivity_state last_observed,
gpr_timespec deadline) override {
return delegate_channel()->WaitForStateChangeImpl(last_observed, deadline);
}
internal::Call CreateCallInternal(const internal::RpcMethod& method,
ClientContext* context,
grpc::CompletionQueue* cq,
size_t interceptor_pos) final {
return delegate_channel()->CreateCallInternal(method, context, cq,
interceptor_pos);
}
grpc::CompletionQueue* CallbackCQ() final {
return delegate_channel()->CallbackCQ();
}
std::shared_ptr<grpc::ChannelInterface> delegate_channel_;
};
} // namespace experimental
} // namespace grpc
#endif // GRPCPP_IMPL_DELEGATING_CHANNEL_H

View File

@@ -0,0 +1,53 @@
//
//
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_GRPC_LIBRARY_H
#define GRPCPP_IMPL_GRPC_LIBRARY_H
#include <iostream>
#include <grpc/grpc.h>
#include <grpcpp/impl/codegen/config.h>
namespace grpc {
namespace internal {
/// Classes that require gRPC to be initialized should inherit from this class.
class GrpcLibrary {
public:
explicit GrpcLibrary(bool call_grpc_init = true) : grpc_init_called_(false) {
if (call_grpc_init) {
grpc_init();
grpc_init_called_ = true;
}
}
virtual ~GrpcLibrary() {
if (grpc_init_called_) {
grpc_shutdown();
}
}
private:
bool grpc_init_called_;
};
} // namespace internal
} // namespace grpc
#endif // GRPCPP_IMPL_GRPC_LIBRARY_H

View File

@@ -0,0 +1,83 @@
//
//
// Copyright 2018 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_INTERCEPTED_CHANNEL_H
#define GRPCPP_IMPL_INTERCEPTED_CHANNEL_H
#include <grpcpp/impl/channel_interface.h>
namespace grpc {
class CompletionQueue;
namespace internal {
class InterceptorBatchMethodsImpl;
/// An InterceptedChannel is available to client Interceptors. An
/// InterceptedChannel is unique to an interceptor, and when an RPC is started
/// on this channel, only those interceptors that come after this interceptor
/// see the RPC.
class InterceptedChannel : public ChannelInterface {
public:
~InterceptedChannel() override { channel_ = nullptr; }
/// Get the current channel state. If the channel is in IDLE and
/// \a try_to_connect is set to true, try to connect.
grpc_connectivity_state GetState(bool try_to_connect) override {
return channel_->GetState(try_to_connect);
}
private:
InterceptedChannel(ChannelInterface* channel, size_t pos)
: channel_(channel), interceptor_pos_(pos) {}
Call CreateCall(const RpcMethod& method, grpc::ClientContext* context,
grpc::CompletionQueue* cq) override {
return channel_->CreateCallInternal(method, context, cq, interceptor_pos_);
}
void PerformOpsOnCall(CallOpSetInterface* ops, Call* call) override {
return channel_->PerformOpsOnCall(ops, call);
}
void* RegisterMethod(const char* method) override {
return channel_->RegisterMethod(method);
}
void NotifyOnStateChangeImpl(grpc_connectivity_state last_observed,
gpr_timespec deadline, grpc::CompletionQueue* cq,
void* tag) override {
return channel_->NotifyOnStateChangeImpl(last_observed, deadline, cq, tag);
}
bool WaitForStateChangeImpl(grpc_connectivity_state last_observed,
gpr_timespec deadline) override {
return channel_->WaitForStateChangeImpl(last_observed, deadline);
}
grpc::CompletionQueue* CallbackCQ() override {
return channel_->CallbackCQ();
}
ChannelInterface* channel_;
size_t interceptor_pos_;
friend class InterceptorBatchMethodsImpl;
};
} // namespace internal
} // namespace grpc
#endif // GRPCPP_IMPL_INTERCEPTED_CHANNEL_H

View File

@@ -0,0 +1,536 @@
//
//
// Copyright 2018 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_INTERCEPTOR_COMMON_H
#define GRPCPP_IMPL_INTERCEPTOR_COMMON_H
#include <array>
#include <functional>
#include <grpc/impl/grpc_types.h>
#include <grpc/support/log.h>
#include <grpcpp/impl/call.h>
#include <grpcpp/impl/call_op_set_interface.h>
#include <grpcpp/impl/intercepted_channel.h>
#include <grpcpp/support/client_interceptor.h>
#include <grpcpp/support/server_interceptor.h>
namespace grpc {
namespace internal {
class InterceptorBatchMethodsImpl
: public experimental::InterceptorBatchMethods {
public:
InterceptorBatchMethodsImpl() {
for (auto i = static_cast<experimental::InterceptionHookPoints>(0);
i < experimental::InterceptionHookPoints::NUM_INTERCEPTION_HOOKS;
i = static_cast<experimental::InterceptionHookPoints>(
static_cast<size_t>(i) + 1)) {
hooks_[static_cast<size_t>(i)] = false;
}
}
~InterceptorBatchMethodsImpl() override {}
bool QueryInterceptionHookPoint(
experimental::InterceptionHookPoints type) override {
return hooks_[static_cast<size_t>(type)];
}
void Proceed() override {
if (call_->client_rpc_info() != nullptr) {
return ProceedClient();
}
GPR_ASSERT(call_->server_rpc_info() != nullptr);
ProceedServer();
}
void Hijack() override {
// Only the client can hijack when sending down initial metadata
GPR_ASSERT(!reverse_ && ops_ != nullptr &&
call_->client_rpc_info() != nullptr);
// It is illegal to call Hijack twice
GPR_ASSERT(!ran_hijacking_interceptor_);
auto* rpc_info = call_->client_rpc_info();
rpc_info->hijacked_ = true;
rpc_info->hijacked_interceptor_ = current_interceptor_index_;
ClearHookPoints();
ops_->SetHijackingState();
ran_hijacking_interceptor_ = true;
rpc_info->RunInterceptor(this, current_interceptor_index_);
}
void AddInterceptionHookPoint(experimental::InterceptionHookPoints type) {
hooks_[static_cast<size_t>(type)] = true;
}
ByteBuffer* GetSerializedSendMessage() override {
GPR_ASSERT(orig_send_message_ != nullptr);
if (*orig_send_message_ != nullptr) {
GPR_ASSERT(serializer_(*orig_send_message_).ok());
*orig_send_message_ = nullptr;
}
return send_message_;
}
const void* GetSendMessage() override {
GPR_ASSERT(orig_send_message_ != nullptr);
return *orig_send_message_;
}
void ModifySendMessage(const void* message) override {
GPR_ASSERT(orig_send_message_ != nullptr);
*orig_send_message_ = message;
}
bool GetSendMessageStatus() override { return !*fail_send_message_; }
std::multimap<std::string, std::string>* GetSendInitialMetadata() override {
return send_initial_metadata_;
}
Status GetSendStatus() override {
return Status(static_cast<StatusCode>(*code_), *error_message_,
*error_details_);
}
void ModifySendStatus(const Status& status) override {
*code_ = static_cast<grpc_status_code>(status.error_code());
*error_details_ = status.error_details();
*error_message_ = status.error_message();
}
std::multimap<std::string, std::string>* GetSendTrailingMetadata() override {
return send_trailing_metadata_;
}
void* GetRecvMessage() override { return recv_message_; }
std::multimap<grpc::string_ref, grpc::string_ref>* GetRecvInitialMetadata()
override {
return recv_initial_metadata_->map();
}
Status* GetRecvStatus() override { return recv_status_; }
void FailHijackedSendMessage() override {
GPR_ASSERT(hooks_[static_cast<size_t>(
experimental::InterceptionHookPoints::PRE_SEND_MESSAGE)]);
*fail_send_message_ = true;
}
std::multimap<grpc::string_ref, grpc::string_ref>* GetRecvTrailingMetadata()
override {
return recv_trailing_metadata_->map();
}
void SetSendMessage(ByteBuffer* buf, const void** msg,
bool* fail_send_message,
std::function<Status(const void*)> serializer) {
send_message_ = buf;
orig_send_message_ = msg;
fail_send_message_ = fail_send_message;
serializer_ = serializer;
}
void SetSendInitialMetadata(
std::multimap<std::string, std::string>* metadata) {
send_initial_metadata_ = metadata;
}
void SetSendStatus(grpc_status_code* code, std::string* error_details,
std::string* error_message) {
code_ = code;
error_details_ = error_details;
error_message_ = error_message;
}
void SetSendTrailingMetadata(
std::multimap<std::string, std::string>* metadata) {
send_trailing_metadata_ = metadata;
}
void SetRecvMessage(void* message, bool* hijacked_recv_message_failed) {
recv_message_ = message;
hijacked_recv_message_failed_ = hijacked_recv_message_failed;
}
void SetRecvInitialMetadata(MetadataMap* map) {
recv_initial_metadata_ = map;
}
void SetRecvStatus(Status* status) { recv_status_ = status; }
void SetRecvTrailingMetadata(MetadataMap* map) {
recv_trailing_metadata_ = map;
}
std::unique_ptr<ChannelInterface> GetInterceptedChannel() override {
auto* info = call_->client_rpc_info();
if (info == nullptr) {
return std::unique_ptr<ChannelInterface>(nullptr);
}
// The intercepted channel starts from the interceptor just after the
// current interceptor
return std::unique_ptr<ChannelInterface>(new InterceptedChannel(
info->channel(), current_interceptor_index_ + 1));
}
void FailHijackedRecvMessage() override {
GPR_ASSERT(hooks_[static_cast<size_t>(
experimental::InterceptionHookPoints::PRE_RECV_MESSAGE)]);
*hijacked_recv_message_failed_ = true;
}
// Clears all state
void ClearState() {
reverse_ = false;
ran_hijacking_interceptor_ = false;
ClearHookPoints();
}
// Prepares for Post_recv operations
void SetReverse() {
reverse_ = true;
ran_hijacking_interceptor_ = false;
ClearHookPoints();
}
// This needs to be set before interceptors are run
void SetCall(Call* call) { call_ = call; }
// This needs to be set before interceptors are run using RunInterceptors().
// Alternatively, RunInterceptors(std::function<void(void)> f) can be used.
void SetCallOpSetInterface(CallOpSetInterface* ops) { ops_ = ops; }
// SetCall should have been called before this.
// Returns true if the interceptors list is empty
bool InterceptorsListEmpty() {
auto* client_rpc_info = call_->client_rpc_info();
if (client_rpc_info != nullptr) {
return client_rpc_info->interceptors_.empty();
}
auto* server_rpc_info = call_->server_rpc_info();
return server_rpc_info == nullptr || server_rpc_info->interceptors_.empty();
}
// This should be used only by subclasses of CallOpSetInterface. SetCall and
// SetCallOpSetInterface should have been called before this. After all the
// interceptors are done running, either ContinueFillOpsAfterInterception or
// ContinueFinalizeOpsAfterInterception will be called. Note that neither of
// them is invoked if there were no interceptors registered.
bool RunInterceptors() {
GPR_ASSERT(ops_);
auto* client_rpc_info = call_->client_rpc_info();
if (client_rpc_info != nullptr) {
if (client_rpc_info->interceptors_.empty()) {
return true;
} else {
RunClientInterceptors();
return false;
}
}
auto* server_rpc_info = call_->server_rpc_info();
if (server_rpc_info == nullptr || server_rpc_info->interceptors_.empty()) {
return true;
}
RunServerInterceptors();
return false;
}
// Returns true if no interceptors are run. Returns false otherwise if there
// are interceptors registered. After the interceptors are done running \a f
// will be invoked. This is to be used only by BaseAsyncRequest and
// SyncRequest.
bool RunInterceptors(std::function<void(void)> f) {
// This is used only by the server for initial call request
GPR_ASSERT(reverse_ == true);
GPR_ASSERT(call_->client_rpc_info() == nullptr);
auto* server_rpc_info = call_->server_rpc_info();
if (server_rpc_info == nullptr || server_rpc_info->interceptors_.empty()) {
return true;
}
callback_ = std::move(f);
RunServerInterceptors();
return false;
}
private:
void RunClientInterceptors() {
auto* rpc_info = call_->client_rpc_info();
if (!reverse_) {
current_interceptor_index_ = 0;
} else {
if (rpc_info->hijacked_) {
current_interceptor_index_ = rpc_info->hijacked_interceptor_;
} else {
current_interceptor_index_ = rpc_info->interceptors_.size() - 1;
}
}
rpc_info->RunInterceptor(this, current_interceptor_index_);
}
void RunServerInterceptors() {
auto* rpc_info = call_->server_rpc_info();
if (!reverse_) {
current_interceptor_index_ = 0;
} else {
current_interceptor_index_ = rpc_info->interceptors_.size() - 1;
}
rpc_info->RunInterceptor(this, current_interceptor_index_);
}
void ProceedClient() {
auto* rpc_info = call_->client_rpc_info();
if (rpc_info->hijacked_ && !reverse_ &&
current_interceptor_index_ == rpc_info->hijacked_interceptor_ &&
!ran_hijacking_interceptor_) {
// We now need to provide hijacked recv ops to this interceptor
ClearHookPoints();
ops_->SetHijackingState();
ran_hijacking_interceptor_ = true;
rpc_info->RunInterceptor(this, current_interceptor_index_);
return;
}
if (!reverse_) {
current_interceptor_index_++;
// We are going down the stack of interceptors
if (current_interceptor_index_ < rpc_info->interceptors_.size()) {
if (rpc_info->hijacked_ &&
current_interceptor_index_ > rpc_info->hijacked_interceptor_) {
// This is a hijacked RPC and we are done with hijacking
ops_->ContinueFillOpsAfterInterception();
} else {
rpc_info->RunInterceptor(this, current_interceptor_index_);
}
} else {
// we are done running all the interceptors without any hijacking
ops_->ContinueFillOpsAfterInterception();
}
} else {
// We are going up the stack of interceptors
if (current_interceptor_index_ > 0) {
// Continue running interceptors
current_interceptor_index_--;
rpc_info->RunInterceptor(this, current_interceptor_index_);
} else {
// we are done running all the interceptors without any hijacking
ops_->ContinueFinalizeResultAfterInterception();
}
}
}
void ProceedServer() {
auto* rpc_info = call_->server_rpc_info();
if (!reverse_) {
current_interceptor_index_++;
if (current_interceptor_index_ < rpc_info->interceptors_.size()) {
return rpc_info->RunInterceptor(this, current_interceptor_index_);
} else if (ops_) {
return ops_->ContinueFillOpsAfterInterception();
}
} else {
// We are going up the stack of interceptors
if (current_interceptor_index_ > 0) {
// Continue running interceptors
current_interceptor_index_--;
return rpc_info->RunInterceptor(this, current_interceptor_index_);
} else if (ops_) {
return ops_->ContinueFinalizeResultAfterInterception();
}
}
GPR_ASSERT(callback_);
callback_();
}
void ClearHookPoints() {
for (auto i = static_cast<experimental::InterceptionHookPoints>(0);
i < experimental::InterceptionHookPoints::NUM_INTERCEPTION_HOOKS;
i = static_cast<experimental::InterceptionHookPoints>(
static_cast<size_t>(i) + 1)) {
hooks_[static_cast<size_t>(i)] = false;
}
}
std::array<bool,
static_cast<size_t>(
experimental::InterceptionHookPoints::NUM_INTERCEPTION_HOOKS)>
hooks_;
size_t current_interceptor_index_ = 0; // Current iterator
bool reverse_ = false;
bool ran_hijacking_interceptor_ = false;
Call* call_ = nullptr; // The Call object is present along with CallOpSet
// object/callback
CallOpSetInterface* ops_ = nullptr;
std::function<void(void)> callback_;
ByteBuffer* send_message_ = nullptr;
bool* fail_send_message_ = nullptr;
const void** orig_send_message_ = nullptr;
std::function<Status(const void*)> serializer_;
std::multimap<std::string, std::string>* send_initial_metadata_;
grpc_status_code* code_ = nullptr;
std::string* error_details_ = nullptr;
std::string* error_message_ = nullptr;
std::multimap<std::string, std::string>* send_trailing_metadata_ = nullptr;
void* recv_message_ = nullptr;
bool* hijacked_recv_message_failed_ = nullptr;
MetadataMap* recv_initial_metadata_ = nullptr;
Status* recv_status_ = nullptr;
MetadataMap* recv_trailing_metadata_ = nullptr;
};
// A special implementation of InterceptorBatchMethods to send a Cancel
// notification down the interceptor stack
class CancelInterceptorBatchMethods
: public experimental::InterceptorBatchMethods {
public:
bool QueryInterceptionHookPoint(
experimental::InterceptionHookPoints type) override {
return type == experimental::InterceptionHookPoints::PRE_SEND_CANCEL;
}
void Proceed() override {
// This is a no-op. For actual continuation of the RPC simply needs to
// return from the Intercept method
}
void Hijack() override {
// Only the client can hijack when sending down initial metadata
GPR_ASSERT(false &&
"It is illegal to call Hijack on a method which has a "
"Cancel notification");
}
ByteBuffer* GetSerializedSendMessage() override {
GPR_ASSERT(false &&
"It is illegal to call GetSendMessage on a method which "
"has a Cancel notification");
return nullptr;
}
bool GetSendMessageStatus() override {
GPR_ASSERT(false &&
"It is illegal to call GetSendMessageStatus on a method which "
"has a Cancel notification");
return false;
}
const void* GetSendMessage() override {
GPR_ASSERT(false &&
"It is illegal to call GetOriginalSendMessage on a method which "
"has a Cancel notification");
return nullptr;
}
void ModifySendMessage(const void* /*message*/) override {
GPR_ASSERT(false &&
"It is illegal to call ModifySendMessage on a method which "
"has a Cancel notification");
}
std::multimap<std::string, std::string>* GetSendInitialMetadata() override {
GPR_ASSERT(false &&
"It is illegal to call GetSendInitialMetadata on a "
"method which has a Cancel notification");
return nullptr;
}
Status GetSendStatus() override {
GPR_ASSERT(false &&
"It is illegal to call GetSendStatus on a method which "
"has a Cancel notification");
return Status();
}
void ModifySendStatus(const Status& /*status*/) override {
GPR_ASSERT(false &&
"It is illegal to call ModifySendStatus on a method "
"which has a Cancel notification");
}
std::multimap<std::string, std::string>* GetSendTrailingMetadata() override {
GPR_ASSERT(false &&
"It is illegal to call GetSendTrailingMetadata on a "
"method which has a Cancel notification");
return nullptr;
}
void* GetRecvMessage() override {
GPR_ASSERT(false &&
"It is illegal to call GetRecvMessage on a method which "
"has a Cancel notification");
return nullptr;
}
std::multimap<grpc::string_ref, grpc::string_ref>* GetRecvInitialMetadata()
override {
GPR_ASSERT(false &&
"It is illegal to call GetRecvInitialMetadata on a "
"method which has a Cancel notification");
return nullptr;
}
Status* GetRecvStatus() override {
GPR_ASSERT(false &&
"It is illegal to call GetRecvStatus on a method which "
"has a Cancel notification");
return nullptr;
}
std::multimap<grpc::string_ref, grpc::string_ref>* GetRecvTrailingMetadata()
override {
GPR_ASSERT(false &&
"It is illegal to call GetRecvTrailingMetadata on a "
"method which has a Cancel notification");
return nullptr;
}
std::unique_ptr<ChannelInterface> GetInterceptedChannel() override {
GPR_ASSERT(false &&
"It is illegal to call GetInterceptedChannel on a "
"method which has a Cancel notification");
return std::unique_ptr<ChannelInterface>(nullptr);
}
void FailHijackedRecvMessage() override {
GPR_ASSERT(false &&
"It is illegal to call FailHijackedRecvMessage on a "
"method which has a Cancel notification");
}
void FailHijackedSendMessage() override {
GPR_ASSERT(false &&
"It is illegal to call FailHijackedSendMessage on a "
"method which has a Cancel notification");
}
};
} // namespace internal
} // namespace grpc
#endif // GRPCPP_IMPL_INTERCEPTOR_COMMON_H

View File

@@ -0,0 +1,104 @@
//
//
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_METADATA_MAP_H
#define GRPCPP_IMPL_METADATA_MAP_H
#include <map>
#include <grpc/grpc.h>
#include <grpc/support/log.h>
#include <grpcpp/support/slice.h>
namespace grpc {
namespace internal {
const char kBinaryErrorDetailsKey[] = "grpc-status-details-bin";
class MetadataMap {
public:
MetadataMap() { Setup(); }
~MetadataMap() { Destroy(); }
std::string GetBinaryErrorDetails() {
// if filled_, extract from the multimap for O(log(n))
if (filled_) {
auto iter = map_.find(kBinaryErrorDetailsKey);
if (iter != map_.end()) {
return std::string(iter->second.begin(), iter->second.length());
}
}
// if not yet filled, take the O(n) lookup to avoid allocating the
// multimap until it is requested.
// TODO(ncteisen): plumb this through core as a first class object, just
// like code and message.
else {
for (size_t i = 0; i < arr_.count; i++) {
if (strncmp(reinterpret_cast<const char*>(
GRPC_SLICE_START_PTR(arr_.metadata[i].key)),
kBinaryErrorDetailsKey,
GRPC_SLICE_LENGTH(arr_.metadata[i].key)) == 0) {
return std::string(reinterpret_cast<const char*>(
GRPC_SLICE_START_PTR(arr_.metadata[i].value)),
GRPC_SLICE_LENGTH(arr_.metadata[i].value));
}
}
}
return std::string();
}
std::multimap<grpc::string_ref, grpc::string_ref>* map() {
FillMap();
return &map_;
}
grpc_metadata_array* arr() { return &arr_; }
void Reset() {
filled_ = false;
map_.clear();
Destroy();
Setup();
}
private:
bool filled_ = false;
grpc_metadata_array arr_;
std::multimap<grpc::string_ref, grpc::string_ref> map_;
void Destroy() { grpc_metadata_array_destroy(&arr_); }
void Setup() { memset(&arr_, 0, sizeof(arr_)); }
void FillMap() {
if (filled_) return;
filled_ = true;
for (size_t i = 0; i < arr_.count; i++) {
// TODO(yangg) handle duplicates?
map_.insert(std::pair<grpc::string_ref, grpc::string_ref>(
StringRefFromSlice(&arr_.metadata[i].key),
StringRefFromSlice(&arr_.metadata[i].value)));
}
}
};
} // namespace internal
} // namespace grpc
#endif // GRPCPP_IMPL_METADATA_MAP_H

View File

@@ -0,0 +1,24 @@
//
//
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_METHOD_HANDLER_IMPL_H
#define GRPCPP_IMPL_METHOD_HANDLER_IMPL_H
#include <grpcpp/support/method_handler.h>
#endif // GRPCPP_IMPL_METHOD_HANDLER_IMPL_H

View File

@@ -0,0 +1,117 @@
//
//
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_PROTO_UTILS_H
#define GRPCPP_IMPL_PROTO_UTILS_H
#include <type_traits>
#include <grpc/byte_buffer_reader.h>
#include <grpc/impl/grpc_types.h>
#include <grpc/slice.h>
#include <grpc/support/log.h>
#include <grpcpp/impl/codegen/config_protobuf.h>
#include <grpcpp/impl/serialization_traits.h>
#include <grpcpp/support/byte_buffer.h>
#include <grpcpp/support/proto_buffer_reader.h>
#include <grpcpp/support/proto_buffer_writer.h>
#include <grpcpp/support/slice.h>
#include <grpcpp/support/status.h>
/// This header provides serialization and deserialization between gRPC
/// messages serialized using protobuf and the C++ objects they represent.
namespace grpc {
// ProtoBufferWriter must be a subclass of ::protobuf::io::ZeroCopyOutputStream.
template <class ProtoBufferWriter, class T>
Status GenericSerialize(const grpc::protobuf::MessageLite& msg, ByteBuffer* bb,
bool* own_buffer) {
static_assert(std::is_base_of<protobuf::io::ZeroCopyOutputStream,
ProtoBufferWriter>::value,
"ProtoBufferWriter must be a subclass of "
"::protobuf::io::ZeroCopyOutputStream");
*own_buffer = true;
int byte_size = static_cast<int>(msg.ByteSizeLong());
if (static_cast<size_t>(byte_size) <= GRPC_SLICE_INLINED_SIZE) {
Slice slice(byte_size);
// We serialize directly into the allocated slices memory
GPR_ASSERT(slice.end() == msg.SerializeWithCachedSizesToArray(
const_cast<uint8_t*>(slice.begin())));
ByteBuffer tmp(&slice, 1);
bb->Swap(&tmp);
return grpc::Status::OK;
}
ProtoBufferWriter writer(bb, kProtoBufferWriterMaxBufferLength, byte_size);
return msg.SerializeToZeroCopyStream(&writer)
? grpc::Status::OK
: Status(StatusCode::INTERNAL, "Failed to serialize message");
}
// BufferReader must be a subclass of ::protobuf::io::ZeroCopyInputStream.
template <class ProtoBufferReader, class T>
Status GenericDeserialize(ByteBuffer* buffer,
grpc::protobuf::MessageLite* msg) {
static_assert(std::is_base_of<protobuf::io::ZeroCopyInputStream,
ProtoBufferReader>::value,
"ProtoBufferReader must be a subclass of "
"::protobuf::io::ZeroCopyInputStream");
if (buffer == nullptr) {
return Status(StatusCode::INTERNAL, "No payload");
}
Status result = grpc::Status::OK;
{
ProtoBufferReader reader(buffer);
if (!reader.status().ok()) {
return reader.status();
}
if (!msg->ParseFromZeroCopyStream(&reader)) {
result = Status(StatusCode::INTERNAL, msg->InitializationErrorString());
}
}
buffer->Clear();
return result;
}
// this is needed so the following class does not conflict with protobuf
// serializers that utilize internal-only tools.
#ifdef GRPC_OPEN_SOURCE_PROTO
// This class provides a protobuf serializer. It translates between protobuf
// objects and grpc_byte_buffers. More information about SerializationTraits can
// be found in include/grpcpp/impl/codegen/serialization_traits.h.
template <class T>
class SerializationTraits<
T, typename std::enable_if<
std::is_base_of<grpc::protobuf::MessageLite, T>::value>::type> {
public:
static Status Serialize(const grpc::protobuf::MessageLite& msg,
ByteBuffer* bb, bool* own_buffer) {
return GenericSerialize<ProtoBufferWriter, T>(msg, bb, own_buffer);
}
static Status Deserialize(ByteBuffer* buffer,
grpc::protobuf::MessageLite* msg) {
return GenericDeserialize<ProtoBufferReader, T>(buffer, msg);
}
};
#endif
} // namespace grpc
#endif // GRPCPP_IMPL_PROTO_UTILS_H

View File

@@ -0,0 +1,80 @@
//
//
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_RPC_METHOD_H
#define GRPCPP_IMPL_RPC_METHOD_H
#include <memory>
#include <grpcpp/impl/codegen/channel_interface.h>
namespace grpc {
namespace internal {
/// Descriptor of an RPC method
class RpcMethod {
public:
enum RpcType {
NORMAL_RPC = 0,
CLIENT_STREAMING, // request streaming
SERVER_STREAMING, // response streaming
BIDI_STREAMING
};
RpcMethod(const char* name, RpcType type)
: name_(name),
suffix_for_stats_(nullptr),
method_type_(type),
channel_tag_(nullptr) {}
RpcMethod(const char* name, const char* suffix_for_stats, RpcType type)
: name_(name),
suffix_for_stats_(suffix_for_stats),
method_type_(type),
channel_tag_(nullptr) {}
RpcMethod(const char* name, RpcType type,
const std::shared_ptr<ChannelInterface>& channel)
: name_(name),
suffix_for_stats_(nullptr),
method_type_(type),
channel_tag_(channel->RegisterMethod(name)) {}
RpcMethod(const char* name, const char* suffix_for_stats, RpcType type,
const std::shared_ptr<ChannelInterface>& channel)
: name_(name),
suffix_for_stats_(suffix_for_stats),
method_type_(type),
channel_tag_(channel->RegisterMethod(name)) {}
const char* name() const { return name_; }
const char* suffix_for_stats() const { return suffix_for_stats_; }
RpcType method_type() const { return method_type_; }
void SetMethodType(RpcType type) { method_type_ = type; }
void* channel_tag() const { return channel_tag_; }
private:
const char* const name_;
const char* const suffix_for_stats_;
RpcType method_type_;
void* const channel_tag_;
};
} // namespace internal
} // namespace grpc
#endif // GRPCPP_IMPL_RPC_METHOD_H

View File

@@ -0,0 +1,153 @@
//
//
// Copyright 2016 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_RPC_SERVICE_METHOD_H
#define GRPCPP_IMPL_RPC_SERVICE_METHOD_H
#include <climits>
#include <functional>
#include <map>
#include <memory>
#include <vector>
#include <grpc/support/log.h>
#include <grpcpp/impl/rpc_method.h>
#include <grpcpp/support/byte_buffer.h>
#include <grpcpp/support/config.h>
#include <grpcpp/support/status.h>
namespace grpc {
class ServerContextBase;
namespace internal {
/// Base class for running an RPC handler.
class MethodHandler {
public:
virtual ~MethodHandler() {}
struct HandlerParameter {
/// Constructor for HandlerParameter
///
/// \param c : the gRPC Call structure for this server call
/// \param context : the ServerContext structure for this server call
/// \param req : the request payload, if appropriate for this RPC
/// \param req_status : the request status after any interceptors have run
/// \param handler_data: internal data for the handler.
/// \param requester : used only by the callback API. It is a function
/// called by the RPC Controller to request another RPC (and also
/// to set up the state required to make that request possible)
HandlerParameter(Call* c, grpc::ServerContextBase* context, void* req,
Status req_status, void* handler_data,
std::function<void()> requester)
: call(c),
server_context(context),
request(req),
status(req_status),
internal_data(handler_data),
call_requester(std::move(requester)) {}
~HandlerParameter() {}
Call* const call;
grpc::ServerContextBase* const server_context;
void* const request;
const Status status;
void* const internal_data;
const std::function<void()> call_requester;
};
virtual void RunHandler(const HandlerParameter& param) = 0;
// Returns a pointer to the deserialized request. \a status reflects the
// result of deserialization. This pointer and the status should be filled in
// a HandlerParameter and passed to RunHandler. It is illegal to access the
// pointer after calling RunHandler. Ownership of the deserialized request is
// retained by the handler. Returns nullptr if deserialization failed.
virtual void* Deserialize(grpc_call* /*call*/, grpc_byte_buffer* req,
Status* /*status*/, void** /*handler_data*/) {
GPR_ASSERT(req == nullptr);
return nullptr;
}
};
/// Server side rpc method class
class RpcServiceMethod : public RpcMethod {
public:
/// Takes ownership of the handler
RpcServiceMethod(const char* name, RpcMethod::RpcType type,
MethodHandler* handler)
: RpcMethod(name, type),
server_tag_(nullptr),
api_type_(ApiType::SYNC),
handler_(handler) {}
enum class ApiType {
SYNC,
ASYNC,
RAW,
CALL_BACK, // not CALLBACK because that is reserved in Windows
RAW_CALL_BACK,
};
void set_server_tag(void* tag) { server_tag_ = tag; }
void* server_tag() const { return server_tag_; }
/// if MethodHandler is nullptr, then this is an async method
MethodHandler* handler() const { return handler_.get(); }
ApiType api_type() const { return api_type_; }
void SetHandler(MethodHandler* handler) { handler_.reset(handler); }
void SetServerApiType(RpcServiceMethod::ApiType type) {
if ((api_type_ == ApiType::SYNC) &&
(type == ApiType::ASYNC || type == ApiType::RAW)) {
// this marks this method as async
handler_.reset();
} else if (api_type_ != ApiType::SYNC) {
// this is not an error condition, as it allows users to declare a server
// like WithRawMethod_foo<AsyncService>. However since it
// overwrites behavior, it should be logged.
gpr_log(
GPR_INFO,
"You are marking method %s as '%s', even though it was "
"previously marked '%s'. This behavior will overwrite the original "
"behavior. If you expected this then ignore this message.",
name(), TypeToString(api_type_), TypeToString(type));
}
api_type_ = type;
}
private:
void* server_tag_;
ApiType api_type_;
std::unique_ptr<MethodHandler> handler_;
const char* TypeToString(RpcServiceMethod::ApiType type) {
switch (type) {
case ApiType::SYNC:
return "sync";
case ApiType::ASYNC:
return "async";
case ApiType::RAW:
return "raw";
case ApiType::CALL_BACK:
return "callback";
case ApiType::RAW_CALL_BACK:
return "raw_callback";
default:
GPR_UNREACHABLE_CODE(return "unknown");
}
}
};
} // namespace internal
} // namespace grpc
#endif // GRPCPP_IMPL_RPC_SERVICE_METHOD_H

View File

@@ -0,0 +1,62 @@
//
//
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_SERIALIZATION_TRAITS_H
#define GRPCPP_IMPL_SERIALIZATION_TRAITS_H
namespace grpc {
/// Defines how to serialize and deserialize some type.
///
/// Used for hooking different message serialization API's into GRPC.
/// Each SerializationTraits<Message> implementation must provide the
/// following functions:
/// 1. static Status Serialize(const Message& msg,
/// ByteBuffer* buffer,
/// bool* own_buffer);
/// OR
/// static Status Serialize(const Message& msg,
/// grpc_byte_buffer** buffer,
/// bool* own_buffer);
/// The former is preferred; the latter is deprecated
///
/// 2. static Status Deserialize(ByteBuffer* buffer,
/// Message* msg);
/// OR
/// static Status Deserialize(grpc_byte_buffer* buffer,
/// Message* msg);
/// The former is preferred; the latter is deprecated
///
/// Serialize is required to convert message to a ByteBuffer, and
/// return that byte buffer through *buffer. *own_buffer should
/// be set to true if the caller owns said byte buffer, or false if
/// ownership is retained elsewhere.
///
/// Deserialize is required to convert buffer into the message stored at
/// msg. max_receive_message_size is passed in as a bound on the maximum
/// number of message bytes Deserialize should accept.
///
/// Both functions return a Status, allowing them to explain what went
/// wrong if required.
template <class Message,
class UnusedButHereForPartialTemplateSpecialization = void>
class SerializationTraits;
} // namespace grpc
#endif // GRPCPP_IMPL_SERIALIZATION_TRAITS_H

View File

@@ -0,0 +1,43 @@
//
//
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_SERVER_BUILDER_OPTION_H
#define GRPCPP_IMPL_SERVER_BUILDER_OPTION_H
#include <map>
#include <memory>
#include <grpcpp/impl/server_builder_plugin.h>
#include <grpcpp/support/channel_arguments.h>
namespace grpc {
/// Interface to pass an option to a \a ServerBuilder.
class ServerBuilderOption {
public:
virtual ~ServerBuilderOption() {}
/// Alter the \a ChannelArguments used to create the gRPC server.
virtual void UpdateArguments(grpc::ChannelArguments* args) = 0;
/// Alter the ServerBuilderPlugin map that will be added into ServerBuilder.
virtual void UpdatePlugins(
std::vector<std::unique_ptr<grpc::ServerBuilderPlugin>>* plugins) = 0;
};
} // namespace grpc
#endif // GRPCPP_IMPL_SERVER_BUILDER_OPTION_H

View File

@@ -0,0 +1,66 @@
//
//
// Copyright 2016 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_SERVER_BUILDER_PLUGIN_H
#define GRPCPP_IMPL_SERVER_BUILDER_PLUGIN_H
#include <memory>
#include <grpcpp/support/channel_arguments.h>
#include <grpcpp/support/config.h>
namespace grpc {
class ServerBuilder;
class ServerInitializer;
/// This interface is meant for internal usage only. Implementations of this
/// interface should add themselves to a \a ServerBuilder instance through the
/// \a InternalAddPluginFactory method.
class ServerBuilderPlugin {
public:
virtual ~ServerBuilderPlugin() {}
virtual std::string name() = 0;
/// UpdateServerBuilder will be called at an early stage in
/// ServerBuilder::BuildAndStart(), right after the ServerBuilderOptions have
/// done their updates.
virtual void UpdateServerBuilder(ServerBuilder* /*builder*/) {}
/// InitServer will be called in ServerBuilder::BuildAndStart(), after the
/// Server instance is created.
virtual void InitServer(ServerInitializer* si) = 0;
/// Finish will be called at the end of ServerBuilder::BuildAndStart().
virtual void Finish(ServerInitializer* si) = 0;
/// ChangeArguments is an interface that can be used in
/// ServerBuilderOption::UpdatePlugins
virtual void ChangeArguments(const std::string& name, void* value) = 0;
/// UpdateChannelArguments will be called in ServerBuilder::BuildAndStart(),
/// before the Server instance is created.
virtual void UpdateChannelArguments(ChannelArguments* /*args*/) {}
virtual bool has_sync_methods() const { return false; }
virtual bool has_async_methods() const { return false; }
};
} // namespace grpc
#endif // GRPCPP_IMPL_SERVER_BUILDER_PLUGIN_H

View File

@@ -0,0 +1,888 @@
//
//
// Copyright 2019 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef GRPCPP_IMPL_SERVER_CALLBACK_HANDLERS_H
#define GRPCPP_IMPL_SERVER_CALLBACK_HANDLERS_H
#include <grpc/grpc.h>
#include <grpc/support/log.h>
#include <grpcpp/impl/rpc_service_method.h>
#include <grpcpp/server_context.h>
#include <grpcpp/support/message_allocator.h>
#include <grpcpp/support/server_callback.h>
#include <grpcpp/support/status.h>
namespace grpc {
namespace internal {
template <class RequestType, class ResponseType>
class CallbackUnaryHandler : public grpc::internal::MethodHandler {
public:
explicit CallbackUnaryHandler(
std::function<ServerUnaryReactor*(grpc::CallbackServerContext*,
const RequestType*, ResponseType*)>
get_reactor)
: get_reactor_(std::move(get_reactor)) {}
void SetMessageAllocator(
MessageAllocator<RequestType, ResponseType>* allocator) {
allocator_ = allocator;
}
void RunHandler(const HandlerParameter& param) final {
// Arena allocate a controller structure (that includes request/response)
grpc_call_ref(param.call->call());
auto* allocator_state =
static_cast<MessageHolder<RequestType, ResponseType>*>(
param.internal_data);
auto* call = new (grpc_call_arena_alloc(param.call->call(),
sizeof(ServerCallbackUnaryImpl)))
ServerCallbackUnaryImpl(
static_cast<grpc::CallbackServerContext*>(param.server_context),
param.call, allocator_state, param.call_requester);
param.server_context->BeginCompletionOp(
param.call, [call](bool) { call->MaybeDone(); }, call);
ServerUnaryReactor* reactor = nullptr;
if (param.status.ok()) {
reactor = grpc::internal::CatchingReactorGetter<ServerUnaryReactor>(
get_reactor_,
static_cast<grpc::CallbackServerContext*>(param.server_context),
call->request(), call->response());
}
if (reactor == nullptr) {
// if deserialization or reactor creator failed, we need to fail the call
reactor = new (grpc_call_arena_alloc(param.call->call(),
sizeof(UnimplementedUnaryReactor)))
UnimplementedUnaryReactor(
grpc::Status(grpc::StatusCode::UNIMPLEMENTED, ""));
}
/// Invoke SetupReactor as the last part of the handler
call->SetupReactor(reactor);
}
void* Deserialize(grpc_call* call, grpc_byte_buffer* req,
grpc::Status* status, void** handler_data) final {
grpc::ByteBuffer buf;
buf.set_buffer(req);
RequestType* request = nullptr;
MessageHolder<RequestType, ResponseType>* allocator_state;
if (allocator_ != nullptr) {
allocator_state = allocator_->AllocateMessages();
} else {
allocator_state = new (grpc_call_arena_alloc(
call, sizeof(DefaultMessageHolder<RequestType, ResponseType>)))
DefaultMessageHolder<RequestType, ResponseType>();
}
*handler_data = allocator_state;
request = allocator_state->request();
*status =
grpc::SerializationTraits<RequestType>::Deserialize(&buf, request);
buf.Release();
if (status->ok()) {
return request;
}
return nullptr;
}
private:
std::function<ServerUnaryReactor*(grpc::CallbackServerContext*,
const RequestType*, ResponseType*)>
get_reactor_;
MessageAllocator<RequestType, ResponseType>* allocator_ = nullptr;
class ServerCallbackUnaryImpl : public ServerCallbackUnary {
public:
void Finish(grpc::Status s) override {
// A callback that only contains a call to MaybeDone can be run as an
// inline callback regardless of whether or not OnDone is inlineable
// because if the actual OnDone callback needs to be scheduled, MaybeDone
// is responsible for dispatching to an executor thread if needed. Thus,
// when setting up the finish_tag_, we can set its own callback to
// inlineable.
finish_tag_.Set(
call_.call(),
[this](bool) {
this->MaybeDone(
reactor_.load(std::memory_order_relaxed)->InternalInlineable());
},
&finish_ops_, /*can_inline=*/true);
finish_ops_.set_core_cq_tag(&finish_tag_);
if (!ctx_->sent_initial_metadata_) {
finish_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
ctx_->initial_metadata_flags());
if (ctx_->compression_level_set()) {
finish_ops_.set_compression_level(ctx_->compression_level());
}
ctx_->sent_initial_metadata_ = true;
}
// The response is dropped if the status is not OK.
if (s.ok()) {
finish_ops_.ServerSendStatus(&ctx_->trailing_metadata_,
finish_ops_.SendMessagePtr(response()));
} else {
finish_ops_.ServerSendStatus(&ctx_->trailing_metadata_, s);
}
finish_ops_.set_core_cq_tag(&finish_tag_);
call_.PerformOps(&finish_ops_);
}
void SendInitialMetadata() override {
GPR_ASSERT(!ctx_->sent_initial_metadata_);
this->Ref();
// The callback for this function should not be marked inline because it
// is directly invoking a user-controlled reaction
// (OnSendInitialMetadataDone). Thus it must be dispatched to an executor
// thread. However, any OnDone needed after that can be inlined because it
// is already running on an executor thread.
meta_tag_.Set(
call_.call(),
[this](bool ok) {
ServerUnaryReactor* reactor =
reactor_.load(std::memory_order_relaxed);
reactor->OnSendInitialMetadataDone(ok);
this->MaybeDone(/*inlineable_ondone=*/true);
},
&meta_ops_, /*can_inline=*/false);
meta_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
ctx_->initial_metadata_flags());
if (ctx_->compression_level_set()) {
meta_ops_.set_compression_level(ctx_->compression_level());
}
ctx_->sent_initial_metadata_ = true;
meta_ops_.set_core_cq_tag(&meta_tag_);
call_.PerformOps(&meta_ops_);
}
private:
friend class CallbackUnaryHandler<RequestType, ResponseType>;
ServerCallbackUnaryImpl(
grpc::CallbackServerContext* ctx, grpc::internal::Call* call,
MessageHolder<RequestType, ResponseType>* allocator_state,
std::function<void()> call_requester)
: ctx_(ctx),
call_(*call),
allocator_state_(allocator_state),
call_requester_(std::move(call_requester)) {
ctx_->set_message_allocator_state(allocator_state);
}
/// SetupReactor binds the reactor (which also releases any queued
/// operations), maybe calls OnCancel if possible/needed, and maybe marks
/// the completion of the RPC. This should be the last component of the
/// handler.
void SetupReactor(ServerUnaryReactor* reactor) {
reactor_.store(reactor, std::memory_order_relaxed);
this->BindReactor(reactor);
this->MaybeCallOnCancel(reactor);
this->MaybeDone(reactor->InternalInlineable());
}
const RequestType* request() { return allocator_state_->request(); }
ResponseType* response() { return allocator_state_->response(); }
void CallOnDone() override {
reactor_.load(std::memory_order_relaxed)->OnDone();
grpc_call* call = call_.call();
auto call_requester = std::move(call_requester_);
allocator_state_->Release();
if (ctx_->context_allocator() != nullptr) {
ctx_->context_allocator()->Release(ctx_);
}
this->~ServerCallbackUnaryImpl(); // explicitly call destructor
grpc_call_unref(call);
call_requester();
}
ServerReactor* reactor() override {
return reactor_.load(std::memory_order_relaxed);
}
grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata>
meta_ops_;
grpc::internal::CallbackWithSuccessTag meta_tag_;
grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata,
grpc::internal::CallOpSendMessage,
grpc::internal::CallOpServerSendStatus>
finish_ops_;
grpc::internal::CallbackWithSuccessTag finish_tag_;
grpc::CallbackServerContext* const ctx_;
grpc::internal::Call call_;
MessageHolder<RequestType, ResponseType>* const allocator_state_;
std::function<void()> call_requester_;
// reactor_ can always be loaded/stored with relaxed memory ordering because
// its value is only set once, independently of other data in the object,
// and the loads that use it will always actually come provably later even
// though they are from different threads since they are triggered by
// actions initiated only by the setting up of the reactor_ variable. In
// a sense, it's a delayed "const": it gets its value from the SetupReactor
// method (not the constructor, so it's not a true const), but it doesn't
// change after that and it only gets used by actions caused, directly or
// indirectly, by that setup. This comment also applies to the reactor_
// variables of the other streaming objects in this file.
std::atomic<ServerUnaryReactor*> reactor_;
// callbacks_outstanding_ follows a refcount pattern
std::atomic<intptr_t> callbacks_outstanding_{
3}; // reserve for start, Finish, and CompletionOp
};
};
template <class RequestType, class ResponseType>
class CallbackClientStreamingHandler : public grpc::internal::MethodHandler {
public:
explicit CallbackClientStreamingHandler(
std::function<ServerReadReactor<RequestType>*(
grpc::CallbackServerContext*, ResponseType*)>
get_reactor)
: get_reactor_(std::move(get_reactor)) {}
void RunHandler(const HandlerParameter& param) final {
// Arena allocate a reader structure (that includes response)
grpc_call_ref(param.call->call());
auto* reader = new (grpc_call_arena_alloc(param.call->call(),
sizeof(ServerCallbackReaderImpl)))
ServerCallbackReaderImpl(
static_cast<grpc::CallbackServerContext*>(param.server_context),
param.call, param.call_requester);
// Inlineable OnDone can be false in the CompletionOp callback because there
// is no read reactor that has an inlineable OnDone; this only applies to
// the DefaultReactor (which is unary).
param.server_context->BeginCompletionOp(
param.call,
[reader](bool) { reader->MaybeDone(/*inlineable_ondone=*/false); },
reader);
ServerReadReactor<RequestType>* reactor = nullptr;
if (param.status.ok()) {
reactor =
grpc::internal::CatchingReactorGetter<ServerReadReactor<RequestType>>(
get_reactor_,
static_cast<grpc::CallbackServerContext*>(param.server_context),
reader->response());
}
if (reactor == nullptr) {
// if deserialization or reactor creator failed, we need to fail the call
reactor = new (grpc_call_arena_alloc(
param.call->call(), sizeof(UnimplementedReadReactor<RequestType>)))
UnimplementedReadReactor<RequestType>(
grpc::Status(grpc::StatusCode::UNIMPLEMENTED, ""));
}
reader->SetupReactor(reactor);
}
private:
std::function<ServerReadReactor<RequestType>*(grpc::CallbackServerContext*,
ResponseType*)>
get_reactor_;
class ServerCallbackReaderImpl : public ServerCallbackReader<RequestType> {
public:
void Finish(grpc::Status s) override {
// A finish tag with only MaybeDone can have its callback inlined
// regardless even if OnDone is not inlineable because this callback just
// checks a ref and then decides whether or not to dispatch OnDone.
finish_tag_.Set(
call_.call(),
[this](bool) {
// Inlineable OnDone can be false here because there is
// no read reactor that has an inlineable OnDone; this
// only applies to the DefaultReactor (which is unary).
this->MaybeDone(/*inlineable_ondone=*/false);
},
&finish_ops_, /*can_inline=*/true);
if (!ctx_->sent_initial_metadata_) {
finish_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
ctx_->initial_metadata_flags());
if (ctx_->compression_level_set()) {
finish_ops_.set_compression_level(ctx_->compression_level());
}
ctx_->sent_initial_metadata_ = true;
}
// The response is dropped if the status is not OK.
if (s.ok()) {
finish_ops_.ServerSendStatus(&ctx_->trailing_metadata_,
finish_ops_.SendMessagePtr(&resp_));
} else {
finish_ops_.ServerSendStatus(&ctx_->trailing_metadata_, s);
}
finish_ops_.set_core_cq_tag(&finish_tag_);
call_.PerformOps(&finish_ops_);
}
void SendInitialMetadata() override {
GPR_ASSERT(!ctx_->sent_initial_metadata_);
this->Ref();
// The callback for this function should not be inlined because it invokes
// a user-controlled reaction, but any resulting OnDone can be inlined in
// the executor to which this callback is dispatched.
meta_tag_.Set(
call_.call(),
[this](bool ok) {
ServerReadReactor<RequestType>* reactor =
reactor_.load(std::memory_order_relaxed);
reactor->OnSendInitialMetadataDone(ok);
this->MaybeDone(/*inlineable_ondone=*/true);
},
&meta_ops_, /*can_inline=*/false);
meta_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
ctx_->initial_metadata_flags());
if (ctx_->compression_level_set()) {
meta_ops_.set_compression_level(ctx_->compression_level());
}
ctx_->sent_initial_metadata_ = true;
meta_ops_.set_core_cq_tag(&meta_tag_);
call_.PerformOps(&meta_ops_);
}
void Read(RequestType* req) override {
this->Ref();
read_ops_.RecvMessage(req);
call_.PerformOps(&read_ops_);
}
private:
friend class CallbackClientStreamingHandler<RequestType, ResponseType>;
ServerCallbackReaderImpl(grpc::CallbackServerContext* ctx,
grpc::internal::Call* call,
std::function<void()> call_requester)
: ctx_(ctx), call_(*call), call_requester_(std::move(call_requester)) {}
void SetupReactor(ServerReadReactor<RequestType>* reactor) {
reactor_.store(reactor, std::memory_order_relaxed);
// The callback for this function should not be inlined because it invokes
// a user-controlled reaction, but any resulting OnDone can be inlined in
// the executor to which this callback is dispatched.
read_tag_.Set(
call_.call(),
[this, reactor](bool ok) {
if (GPR_UNLIKELY(!ok)) {
ctx_->MaybeMarkCancelledOnRead();
}
reactor->OnReadDone(ok);
this->MaybeDone(/*inlineable_ondone=*/true);
},
&read_ops_, /*can_inline=*/false);
read_ops_.set_core_cq_tag(&read_tag_);
this->BindReactor(reactor);
this->MaybeCallOnCancel(reactor);
// Inlineable OnDone can be false here because there is no read
// reactor that has an inlineable OnDone; this only applies to the
// DefaultReactor (which is unary).
this->MaybeDone(/*inlineable_ondone=*/false);
}
~ServerCallbackReaderImpl() {}
ResponseType* response() { return &resp_; }
void CallOnDone() override {
reactor_.load(std::memory_order_relaxed)->OnDone();
grpc_call* call = call_.call();
auto call_requester = std::move(call_requester_);
if (ctx_->context_allocator() != nullptr) {
ctx_->context_allocator()->Release(ctx_);
}
this->~ServerCallbackReaderImpl(); // explicitly call destructor
grpc_call_unref(call);
call_requester();
}
ServerReactor* reactor() override {
return reactor_.load(std::memory_order_relaxed);
}
grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata>
meta_ops_;
grpc::internal::CallbackWithSuccessTag meta_tag_;
grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata,
grpc::internal::CallOpSendMessage,
grpc::internal::CallOpServerSendStatus>
finish_ops_;
grpc::internal::CallbackWithSuccessTag finish_tag_;
grpc::internal::CallOpSet<grpc::internal::CallOpRecvMessage<RequestType>>
read_ops_;
grpc::internal::CallbackWithSuccessTag read_tag_;
grpc::CallbackServerContext* const ctx_;
grpc::internal::Call call_;
ResponseType resp_;
std::function<void()> call_requester_;
// The memory ordering of reactor_ follows ServerCallbackUnaryImpl.
std::atomic<ServerReadReactor<RequestType>*> reactor_;
// callbacks_outstanding_ follows a refcount pattern
std::atomic<intptr_t> callbacks_outstanding_{
3}; // reserve for OnStarted, Finish, and CompletionOp
};
};
template <class RequestType, class ResponseType>
class CallbackServerStreamingHandler : public grpc::internal::MethodHandler {
public:
explicit CallbackServerStreamingHandler(
std::function<ServerWriteReactor<ResponseType>*(
grpc::CallbackServerContext*, const RequestType*)>
get_reactor)
: get_reactor_(std::move(get_reactor)) {}
void RunHandler(const HandlerParameter& param) final {
// Arena allocate a writer structure
grpc_call_ref(param.call->call());
auto* writer = new (grpc_call_arena_alloc(param.call->call(),
sizeof(ServerCallbackWriterImpl)))
ServerCallbackWriterImpl(
static_cast<grpc::CallbackServerContext*>(param.server_context),
param.call, static_cast<RequestType*>(param.request),
param.call_requester);
// Inlineable OnDone can be false in the CompletionOp callback because there
// is no write reactor that has an inlineable OnDone; this only applies to
// the DefaultReactor (which is unary).
param.server_context->BeginCompletionOp(
param.call,
[writer](bool) { writer->MaybeDone(/*inlineable_ondone=*/false); },
writer);
ServerWriteReactor<ResponseType>* reactor = nullptr;
if (param.status.ok()) {
reactor = grpc::internal::CatchingReactorGetter<
ServerWriteReactor<ResponseType>>(
get_reactor_,
static_cast<grpc::CallbackServerContext*>(param.server_context),
writer->request());
}
if (reactor == nullptr) {
// if deserialization or reactor creator failed, we need to fail the call
reactor = new (grpc_call_arena_alloc(
param.call->call(), sizeof(UnimplementedWriteReactor<ResponseType>)))
UnimplementedWriteReactor<ResponseType>(
grpc::Status(grpc::StatusCode::UNIMPLEMENTED, ""));
}
writer->SetupReactor(reactor);
}
void* Deserialize(grpc_call* call, grpc_byte_buffer* req,
grpc::Status* status, void** /*handler_data*/) final {
grpc::ByteBuffer buf;
buf.set_buffer(req);
auto* request =
new (grpc_call_arena_alloc(call, sizeof(RequestType))) RequestType();
*status =
grpc::SerializationTraits<RequestType>::Deserialize(&buf, request);
buf.Release();
if (status->ok()) {
return request;
}
request->~RequestType();
return nullptr;
}
private:
std::function<ServerWriteReactor<ResponseType>*(grpc::CallbackServerContext*,
const RequestType*)>
get_reactor_;
class ServerCallbackWriterImpl : public ServerCallbackWriter<ResponseType> {
public:
void Finish(grpc::Status s) override {
// A finish tag with only MaybeDone can have its callback inlined
// regardless even if OnDone is not inlineable because this callback just
// checks a ref and then decides whether or not to dispatch OnDone.
finish_tag_.Set(
call_.call(),
[this](bool) {
// Inlineable OnDone can be false here because there is
// no write reactor that has an inlineable OnDone; this
// only applies to the DefaultReactor (which is unary).
this->MaybeDone(/*inlineable_ondone=*/false);
},
&finish_ops_, /*can_inline=*/true);
finish_ops_.set_core_cq_tag(&finish_tag_);
if (!ctx_->sent_initial_metadata_) {
finish_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
ctx_->initial_metadata_flags());
if (ctx_->compression_level_set()) {
finish_ops_.set_compression_level(ctx_->compression_level());
}
ctx_->sent_initial_metadata_ = true;
}
finish_ops_.ServerSendStatus(&ctx_->trailing_metadata_, s);
call_.PerformOps(&finish_ops_);
}
void SendInitialMetadata() override {
GPR_ASSERT(!ctx_->sent_initial_metadata_);
this->Ref();
// The callback for this function should not be inlined because it invokes
// a user-controlled reaction, but any resulting OnDone can be inlined in
// the executor to which this callback is dispatched.
meta_tag_.Set(
call_.call(),
[this](bool ok) {
ServerWriteReactor<ResponseType>* reactor =
reactor_.load(std::memory_order_relaxed);
reactor->OnSendInitialMetadataDone(ok);
this->MaybeDone(/*inlineable_ondone=*/true);
},
&meta_ops_, /*can_inline=*/false);
meta_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
ctx_->initial_metadata_flags());
if (ctx_->compression_level_set()) {
meta_ops_.set_compression_level(ctx_->compression_level());
}
ctx_->sent_initial_metadata_ = true;
meta_ops_.set_core_cq_tag(&meta_tag_);
call_.PerformOps(&meta_ops_);
}
void Write(const ResponseType* resp, grpc::WriteOptions options) override {
this->Ref();
if (options.is_last_message()) {
options.set_buffer_hint();
}
if (!ctx_->sent_initial_metadata_) {
write_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
ctx_->initial_metadata_flags());
if (ctx_->compression_level_set()) {
write_ops_.set_compression_level(ctx_->compression_level());
}
ctx_->sent_initial_metadata_ = true;
}
// TODO(vjpai): don't assert
GPR_ASSERT(write_ops_.SendMessagePtr(resp, options).ok());
call_.PerformOps(&write_ops_);
}
void WriteAndFinish(const ResponseType* resp, grpc::WriteOptions options,
grpc::Status s) override {
// This combines the write into the finish callback
// TODO(vjpai): don't assert
GPR_ASSERT(finish_ops_.SendMessagePtr(resp, options).ok());
Finish(std::move(s));
}
private:
friend class CallbackServerStreamingHandler<RequestType, ResponseType>;
ServerCallbackWriterImpl(grpc::CallbackServerContext* ctx,
grpc::internal::Call* call, const RequestType* req,
std::function<void()> call_requester)
: ctx_(ctx),
call_(*call),
req_(req),
call_requester_(std::move(call_requester)) {}
void SetupReactor(ServerWriteReactor<ResponseType>* reactor) {
reactor_.store(reactor, std::memory_order_relaxed);
// The callback for this function should not be inlined because it invokes
// a user-controlled reaction, but any resulting OnDone can be inlined in
// the executor to which this callback is dispatched.
write_tag_.Set(
call_.call(),
[this, reactor](bool ok) {
reactor->OnWriteDone(ok);
this->MaybeDone(/*inlineable_ondone=*/true);
},
&write_ops_, /*can_inline=*/false);
write_ops_.set_core_cq_tag(&write_tag_);
this->BindReactor(reactor);
this->MaybeCallOnCancel(reactor);
// Inlineable OnDone can be false here because there is no write
// reactor that has an inlineable OnDone; this only applies to the
// DefaultReactor (which is unary).
this->MaybeDone(/*inlineable_ondone=*/false);
}
~ServerCallbackWriterImpl() {
if (req_ != nullptr) {
req_->~RequestType();
}
}
const RequestType* request() { return req_; }
void CallOnDone() override {
reactor_.load(std::memory_order_relaxed)->OnDone();
grpc_call* call = call_.call();
auto call_requester = std::move(call_requester_);
if (ctx_->context_allocator() != nullptr) {
ctx_->context_allocator()->Release(ctx_);
}
this->~ServerCallbackWriterImpl(); // explicitly call destructor
grpc_call_unref(call);
call_requester();
}
ServerReactor* reactor() override {
return reactor_.load(std::memory_order_relaxed);
}
grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata>
meta_ops_;
grpc::internal::CallbackWithSuccessTag meta_tag_;
grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata,
grpc::internal::CallOpSendMessage,
grpc::internal::CallOpServerSendStatus>
finish_ops_;
grpc::internal::CallbackWithSuccessTag finish_tag_;
grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata,
grpc::internal::CallOpSendMessage>
write_ops_;
grpc::internal::CallbackWithSuccessTag write_tag_;
grpc::CallbackServerContext* const ctx_;
grpc::internal::Call call_;
const RequestType* req_;
std::function<void()> call_requester_;
// The memory ordering of reactor_ follows ServerCallbackUnaryImpl.
std::atomic<ServerWriteReactor<ResponseType>*> reactor_;
// callbacks_outstanding_ follows a refcount pattern
std::atomic<intptr_t> callbacks_outstanding_{
3}; // reserve for OnStarted, Finish, and CompletionOp
};
};
template <class RequestType, class ResponseType>
class CallbackBidiHandler : public grpc::internal::MethodHandler {
public:
explicit CallbackBidiHandler(
std::function<ServerBidiReactor<RequestType, ResponseType>*(
grpc::CallbackServerContext*)>
get_reactor)
: get_reactor_(std::move(get_reactor)) {}
void RunHandler(const HandlerParameter& param) final {
grpc_call_ref(param.call->call());
auto* stream = new (grpc_call_arena_alloc(
param.call->call(), sizeof(ServerCallbackReaderWriterImpl)))
ServerCallbackReaderWriterImpl(
static_cast<grpc::CallbackServerContext*>(param.server_context),
param.call, param.call_requester);
// Inlineable OnDone can be false in the CompletionOp callback because there
// is no bidi reactor that has an inlineable OnDone; this only applies to
// the DefaultReactor (which is unary).
param.server_context->BeginCompletionOp(
param.call,
[stream](bool) { stream->MaybeDone(/*inlineable_ondone=*/false); },
stream);
ServerBidiReactor<RequestType, ResponseType>* reactor = nullptr;
if (param.status.ok()) {
reactor = grpc::internal::CatchingReactorGetter<
ServerBidiReactor<RequestType, ResponseType>>(
get_reactor_,
static_cast<grpc::CallbackServerContext*>(param.server_context));
}
if (reactor == nullptr) {
// if deserialization or reactor creator failed, we need to fail the call
reactor = new (grpc_call_arena_alloc(
param.call->call(),
sizeof(UnimplementedBidiReactor<RequestType, ResponseType>)))
UnimplementedBidiReactor<RequestType, ResponseType>(
grpc::Status(grpc::StatusCode::UNIMPLEMENTED, ""));
}
stream->SetupReactor(reactor);
}
private:
std::function<ServerBidiReactor<RequestType, ResponseType>*(
grpc::CallbackServerContext*)>
get_reactor_;
class ServerCallbackReaderWriterImpl
: public ServerCallbackReaderWriter<RequestType, ResponseType> {
public:
void Finish(grpc::Status s) override {
// A finish tag with only MaybeDone can have its callback inlined
// regardless even if OnDone is not inlineable because this callback just
// checks a ref and then decides whether or not to dispatch OnDone.
finish_tag_.Set(
call_.call(),
[this](bool) {
// Inlineable OnDone can be false here because there is
// no bidi reactor that has an inlineable OnDone; this
// only applies to the DefaultReactor (which is unary).
this->MaybeDone(/*inlineable_ondone=*/false);
},
&finish_ops_, /*can_inline=*/true);
finish_ops_.set_core_cq_tag(&finish_tag_);
if (!ctx_->sent_initial_metadata_) {
finish_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
ctx_->initial_metadata_flags());
if (ctx_->compression_level_set()) {
finish_ops_.set_compression_level(ctx_->compression_level());
}
ctx_->sent_initial_metadata_ = true;
}
finish_ops_.ServerSendStatus(&ctx_->trailing_metadata_, s);
call_.PerformOps(&finish_ops_);
}
void SendInitialMetadata() override {
GPR_ASSERT(!ctx_->sent_initial_metadata_);
this->Ref();
// The callback for this function should not be inlined because it invokes
// a user-controlled reaction, but any resulting OnDone can be inlined in
// the executor to which this callback is dispatched.
meta_tag_.Set(
call_.call(),
[this](bool ok) {
ServerBidiReactor<RequestType, ResponseType>* reactor =
reactor_.load(std::memory_order_relaxed);
reactor->OnSendInitialMetadataDone(ok);
this->MaybeDone(/*inlineable_ondone=*/true);
},
&meta_ops_, /*can_inline=*/false);
meta_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
ctx_->initial_metadata_flags());
if (ctx_->compression_level_set()) {
meta_ops_.set_compression_level(ctx_->compression_level());
}
ctx_->sent_initial_metadata_ = true;
meta_ops_.set_core_cq_tag(&meta_tag_);
call_.PerformOps(&meta_ops_);
}
void Write(const ResponseType* resp, grpc::WriteOptions options) override {
this->Ref();
if (options.is_last_message()) {
options.set_buffer_hint();
}
if (!ctx_->sent_initial_metadata_) {
write_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
ctx_->initial_metadata_flags());
if (ctx_->compression_level_set()) {
write_ops_.set_compression_level(ctx_->compression_level());
}
ctx_->sent_initial_metadata_ = true;
}
// TODO(vjpai): don't assert
GPR_ASSERT(write_ops_.SendMessagePtr(resp, options).ok());
call_.PerformOps(&write_ops_);
}
void WriteAndFinish(const ResponseType* resp, grpc::WriteOptions options,
grpc::Status s) override {
// TODO(vjpai): don't assert
GPR_ASSERT(finish_ops_.SendMessagePtr(resp, options).ok());
Finish(std::move(s));
}
void Read(RequestType* req) override {
this->Ref();
read_ops_.RecvMessage(req);
call_.PerformOps(&read_ops_);
}
private:
friend class CallbackBidiHandler<RequestType, ResponseType>;
ServerCallbackReaderWriterImpl(grpc::CallbackServerContext* ctx,
grpc::internal::Call* call,
std::function<void()> call_requester)
: ctx_(ctx), call_(*call), call_requester_(std::move(call_requester)) {}
void SetupReactor(ServerBidiReactor<RequestType, ResponseType>* reactor) {
reactor_.store(reactor, std::memory_order_relaxed);
// The callbacks for these functions should not be inlined because they
// invoke user-controlled reactions, but any resulting OnDones can be
// inlined in the executor to which a callback is dispatched.
write_tag_.Set(
call_.call(),
[this, reactor](bool ok) {
reactor->OnWriteDone(ok);
this->MaybeDone(/*inlineable_ondone=*/true);
},
&write_ops_, /*can_inline=*/false);
write_ops_.set_core_cq_tag(&write_tag_);
read_tag_.Set(
call_.call(),
[this, reactor](bool ok) {
if (GPR_UNLIKELY(!ok)) {
ctx_->MaybeMarkCancelledOnRead();
}
reactor->OnReadDone(ok);
this->MaybeDone(/*inlineable_ondone=*/true);
},
&read_ops_, /*can_inline=*/false);
read_ops_.set_core_cq_tag(&read_tag_);
this->BindReactor(reactor);
this->MaybeCallOnCancel(reactor);
// Inlineable OnDone can be false here because there is no bidi
// reactor that has an inlineable OnDone; this only applies to the
// DefaultReactor (which is unary).
this->MaybeDone(/*inlineable_ondone=*/false);
}
void CallOnDone() override {
reactor_.load(std::memory_order_relaxed)->OnDone();
grpc_call* call = call_.call();
auto call_requester = std::move(call_requester_);
if (ctx_->context_allocator() != nullptr) {
ctx_->context_allocator()->Release(ctx_);
}
this->~ServerCallbackReaderWriterImpl(); // explicitly call destructor
grpc_call_unref(call);
call_requester();
}
ServerReactor* reactor() override {
return reactor_.load(std::memory_order_relaxed);
}
grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata>
meta_ops_;
grpc::internal::CallbackWithSuccessTag meta_tag_;
grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata,
grpc::internal::CallOpSendMessage,
grpc::internal::CallOpServerSendStatus>
finish_ops_;
grpc::internal::CallbackWithSuccessTag finish_tag_;
grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata,
grpc::internal::CallOpSendMessage>
write_ops_;
grpc::internal::CallbackWithSuccessTag write_tag_;
grpc::internal::CallOpSet<grpc::internal::CallOpRecvMessage<RequestType>>
read_ops_;
grpc::internal::CallbackWithSuccessTag read_tag_;
grpc::CallbackServerContext* const ctx_;
grpc::internal::Call call_;
std::function<void()> call_requester_;
// The memory ordering of reactor_ follows ServerCallbackUnaryImpl.
std::atomic<ServerBidiReactor<RequestType, ResponseType>*> reactor_;
// callbacks_outstanding_ follows a refcount pattern
std::atomic<intptr_t> callbacks_outstanding_{
3}; // reserve for OnStarted, Finish, and CompletionOp
};
};
} // namespace internal
} // namespace grpc
#endif // GRPCPP_IMPL_SERVER_CALLBACK_HANDLERS_H

View File

@@ -0,0 +1,54 @@
//
//
// Copyright 2016 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_SERVER_INITIALIZER_H
#define GRPCPP_IMPL_SERVER_INITIALIZER_H
#include <memory>
#include <vector>
#include <grpcpp/server.h>
namespace grpc {
class Server;
class Service;
class ServerInitializer {
public:
explicit ServerInitializer(grpc::Server* server) : server_(server) {}
bool RegisterService(std::shared_ptr<grpc::Service> service) {
if (!server_->RegisterService(nullptr, service.get())) {
return false;
}
default_services_.push_back(service);
return true;
}
const std::vector<std::string>* GetServiceList() {
return &server_->services_;
}
private:
grpc::Server* server_;
std::vector<std::shared_ptr<grpc::Service> > default_services_;
};
} // namespace grpc
#endif // GRPCPP_IMPL_SERVER_INITIALIZER_H

View File

@@ -0,0 +1,235 @@
//
//
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_SERVICE_TYPE_H
#define GRPCPP_IMPL_SERVICE_TYPE_H
#include <grpc/support/log.h>
#include <grpcpp/impl/rpc_service_method.h>
#include <grpcpp/impl/serialization_traits.h>
#include <grpcpp/server_interface.h>
#include <grpcpp/support/config.h>
#include <grpcpp/support/status.h>
namespace grpc {
class CompletionQueue;
class ServerContext;
class ServerInterface;
namespace internal {
class Call;
class ServerAsyncStreamingInterface {
public:
virtual ~ServerAsyncStreamingInterface() {}
/// Request notification of the sending of initial metadata to the client.
/// Completion will be notified by \a tag on the associated completion
/// queue. This call is optional, but if it is used, it cannot be used
/// concurrently with or after the \a Finish method.
///
/// \param[in] tag Tag identifying this request.
virtual void SendInitialMetadata(void* tag) = 0;
private:
friend class grpc::ServerInterface;
virtual void BindCall(Call* call) = 0;
};
} // namespace internal
/// Descriptor of an RPC service and its various RPC methods
class Service {
public:
Service() : server_(nullptr) {}
virtual ~Service() {}
bool has_async_methods() const {
for (const auto& method : methods_) {
if (method && method->handler() == nullptr) {
return true;
}
}
return false;
}
bool has_synchronous_methods() const {
for (const auto& method : methods_) {
if (method &&
method->api_type() == internal::RpcServiceMethod::ApiType::SYNC) {
return true;
}
}
return false;
}
bool has_callback_methods() const {
for (const auto& method : methods_) {
if (method && (method->api_type() ==
internal::RpcServiceMethod::ApiType::CALL_BACK ||
method->api_type() ==
internal::RpcServiceMethod::ApiType::RAW_CALL_BACK)) {
return true;
}
}
return false;
}
bool has_generic_methods() const {
for (const auto& method : methods_) {
if (method == nullptr) {
return true;
}
}
return false;
}
protected:
template <class Message>
void RequestAsyncUnary(int index, grpc::ServerContext* context,
Message* request,
internal::ServerAsyncStreamingInterface* stream,
grpc::CompletionQueue* call_cq,
grpc::ServerCompletionQueue* notification_cq,
void* tag) {
// Typecast the index to size_t for indexing into a vector
// while preserving the API that existed before a compiler
// warning was first seen (grpc/grpc#11664)
size_t idx = static_cast<size_t>(index);
server_->RequestAsyncCall(methods_[idx].get(), context, stream, call_cq,
notification_cq, tag, request);
}
void RequestAsyncClientStreaming(
int index, grpc::ServerContext* context,
internal::ServerAsyncStreamingInterface* stream,
grpc::CompletionQueue* call_cq,
grpc::ServerCompletionQueue* notification_cq, void* tag) {
size_t idx = static_cast<size_t>(index);
server_->RequestAsyncCall(methods_[idx].get(), context, stream, call_cq,
notification_cq, tag);
}
template <class Message>
void RequestAsyncServerStreaming(
int index, grpc::ServerContext* context, Message* request,
internal::ServerAsyncStreamingInterface* stream,
grpc::CompletionQueue* call_cq,
grpc::ServerCompletionQueue* notification_cq, void* tag) {
size_t idx = static_cast<size_t>(index);
server_->RequestAsyncCall(methods_[idx].get(), context, stream, call_cq,
notification_cq, tag, request);
}
void RequestAsyncBidiStreaming(
int index, grpc::ServerContext* context,
internal::ServerAsyncStreamingInterface* stream,
grpc::CompletionQueue* call_cq,
grpc::ServerCompletionQueue* notification_cq, void* tag) {
size_t idx = static_cast<size_t>(index);
server_->RequestAsyncCall(methods_[idx].get(), context, stream, call_cq,
notification_cq, tag);
}
void AddMethod(internal::RpcServiceMethod* method) {
methods_.emplace_back(method);
}
void MarkMethodAsync(int index) {
// This does not have to be a hard error, however no one has approached us
// with a use case yet. Please file an issue if you believe you have one.
size_t idx = static_cast<size_t>(index);
GPR_ASSERT(methods_[idx].get() != nullptr &&
"Cannot mark the method as 'async' because it has already been "
"marked as 'generic'.");
methods_[idx]->SetServerApiType(internal::RpcServiceMethod::ApiType::ASYNC);
}
void MarkMethodRaw(int index) {
// This does not have to be a hard error, however no one has approached us
// with a use case yet. Please file an issue if you believe you have one.
size_t idx = static_cast<size_t>(index);
GPR_ASSERT(methods_[idx].get() != nullptr &&
"Cannot mark the method as 'raw' because it has already "
"been marked as 'generic'.");
methods_[idx]->SetServerApiType(internal::RpcServiceMethod::ApiType::RAW);
}
void MarkMethodGeneric(int index) {
// This does not have to be a hard error, however no one has approached us
// with a use case yet. Please file an issue if you believe you have one.
size_t idx = static_cast<size_t>(index);
GPR_ASSERT(
methods_[idx]->handler() != nullptr &&
"Cannot mark the method as 'generic' because it has already been "
"marked as 'async' or 'raw'.");
methods_[idx].reset();
}
void MarkMethodStreamed(int index, internal::MethodHandler* streamed_method) {
// This does not have to be a hard error, however no one has approached us
// with a use case yet. Please file an issue if you believe you have one.
size_t idx = static_cast<size_t>(index);
GPR_ASSERT(methods_[idx] && methods_[idx]->handler() &&
"Cannot mark an async or generic method Streamed");
methods_[idx]->SetHandler(streamed_method);
// From the server's point of view, streamed unary is a special
// case of BIDI_STREAMING that has 1 read and 1 write, in that order,
// and split server-side streaming is BIDI_STREAMING with 1 read and
// any number of writes, in that order.
methods_[idx]->SetMethodType(internal::RpcMethod::BIDI_STREAMING);
}
void MarkMethodCallback(int index, internal::MethodHandler* handler) {
// This does not have to be a hard error, however no one has approached us
// with a use case yet. Please file an issue if you believe you have one.
size_t idx = static_cast<size_t>(index);
GPR_ASSERT(
methods_[idx].get() != nullptr &&
"Cannot mark the method as 'callback' because it has already been "
"marked as 'generic'.");
methods_[idx]->SetHandler(handler);
methods_[idx]->SetServerApiType(
internal::RpcServiceMethod::ApiType::CALL_BACK);
}
void MarkMethodRawCallback(int index, internal::MethodHandler* handler) {
// This does not have to be a hard error, however no one has approached us
// with a use case yet. Please file an issue if you believe you have one.
size_t idx = static_cast<size_t>(index);
GPR_ASSERT(
methods_[idx].get() != nullptr &&
"Cannot mark the method as 'raw callback' because it has already "
"been marked as 'generic'.");
methods_[idx]->SetHandler(handler);
methods_[idx]->SetServerApiType(
internal::RpcServiceMethod::ApiType::RAW_CALL_BACK);
}
internal::MethodHandler* GetHandler(int index) {
size_t idx = static_cast<size_t>(index);
return methods_[idx]->handler();
}
private:
friend class Server;
friend class ServerInterface;
ServerInterface* server_;
std::vector<std::unique_ptr<internal::RpcServiceMethod>> methods_;
};
} // namespace grpc
#endif // GRPCPP_IMPL_SERVICE_TYPE_H

141
Pods/gRPC-C++/include/grpcpp/impl/status.h generated Normal file
View File

@@ -0,0 +1,141 @@
//
//
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_STATUS_H
#define GRPCPP_IMPL_STATUS_H
// IWYU pragma: private, include <grpcpp/support/status.h>
#include <grpc/support/port_platform.h>
#include <grpc/status.h>
#include <grpcpp/support/config.h>
#include <grpcpp/support/status_code_enum.h>
namespace grpc {
/// Did it work? If it didn't, why?
///
/// See \a grpc::StatusCode for details on the available code and their meaning.
class GRPC_MUST_USE_RESULT_WHEN_USE_STRICT_WARNING GRPCXX_DLL Status {
public:
/// Construct an OK instance.
Status() : code_(StatusCode::OK) {
// Static assertions to make sure that the C++ API value correctly
// maps to the core surface API value
static_assert(StatusCode::OK == static_cast<StatusCode>(GRPC_STATUS_OK),
"Mismatched status code");
static_assert(
StatusCode::CANCELLED == static_cast<StatusCode>(GRPC_STATUS_CANCELLED),
"Mismatched status code");
static_assert(
StatusCode::UNKNOWN == static_cast<StatusCode>(GRPC_STATUS_UNKNOWN),
"Mismatched status code");
static_assert(StatusCode::INVALID_ARGUMENT ==
static_cast<StatusCode>(GRPC_STATUS_INVALID_ARGUMENT),
"Mismatched status code");
static_assert(StatusCode::DEADLINE_EXCEEDED ==
static_cast<StatusCode>(GRPC_STATUS_DEADLINE_EXCEEDED),
"Mismatched status code");
static_assert(
StatusCode::NOT_FOUND == static_cast<StatusCode>(GRPC_STATUS_NOT_FOUND),
"Mismatched status code");
static_assert(StatusCode::ALREADY_EXISTS ==
static_cast<StatusCode>(GRPC_STATUS_ALREADY_EXISTS),
"Mismatched status code");
static_assert(StatusCode::PERMISSION_DENIED ==
static_cast<StatusCode>(GRPC_STATUS_PERMISSION_DENIED),
"Mismatched status code");
static_assert(StatusCode::UNAUTHENTICATED ==
static_cast<StatusCode>(GRPC_STATUS_UNAUTHENTICATED),
"Mismatched status code");
static_assert(StatusCode::RESOURCE_EXHAUSTED ==
static_cast<StatusCode>(GRPC_STATUS_RESOURCE_EXHAUSTED),
"Mismatched status code");
static_assert(StatusCode::FAILED_PRECONDITION ==
static_cast<StatusCode>(GRPC_STATUS_FAILED_PRECONDITION),
"Mismatched status code");
static_assert(
StatusCode::ABORTED == static_cast<StatusCode>(GRPC_STATUS_ABORTED),
"Mismatched status code");
static_assert(StatusCode::OUT_OF_RANGE ==
static_cast<StatusCode>(GRPC_STATUS_OUT_OF_RANGE),
"Mismatched status code");
static_assert(StatusCode::UNIMPLEMENTED ==
static_cast<StatusCode>(GRPC_STATUS_UNIMPLEMENTED),
"Mismatched status code");
static_assert(
StatusCode::INTERNAL == static_cast<StatusCode>(GRPC_STATUS_INTERNAL),
"Mismatched status code");
static_assert(StatusCode::UNAVAILABLE ==
static_cast<StatusCode>(GRPC_STATUS_UNAVAILABLE),
"Mismatched status code");
static_assert(
StatusCode::DATA_LOSS == static_cast<StatusCode>(GRPC_STATUS_DATA_LOSS),
"Mismatched status code");
}
/// Construct an instance with associated \a code and \a error_message.
/// It is an error to construct an OK status with non-empty \a error_message.
/// Note that \a message is intentionally accepted as a const reference
/// instead of a value (which results in a copy instead of a move) to allow
/// for easy transition to absl::Status in the future which accepts an
/// absl::string_view as a parameter.
Status(StatusCode code, const std::string& error_message)
: code_(code), error_message_(error_message) {}
/// Construct an instance with \a code, \a error_message and
/// \a error_details. It is an error to construct an OK status with non-empty
/// \a error_message and/or \a error_details.
Status(StatusCode code, const std::string& error_message,
const std::string& error_details)
: code_(code),
error_message_(error_message),
binary_error_details_(error_details) {}
// Pre-defined special status objects.
/// An OK pre-defined instance.
static const Status& OK;
/// A CANCELLED pre-defined instance.
static const Status& CANCELLED;
/// Return the instance's error code.
StatusCode error_code() const { return code_; }
/// Return the instance's error message.
std::string error_message() const { return error_message_; }
/// Return the (binary) error details.
// Usually it contains a serialized google.rpc.Status proto.
std::string error_details() const { return binary_error_details_; }
/// Is the status OK?
bool ok() const { return code_ == StatusCode::OK; }
// Ignores any errors. This method does nothing except potentially suppress
// complaints from any tools that are checking that errors are not dropped on
// the floor.
void IgnoreError() const {}
private:
StatusCode code_;
std::string error_message_;
std::string binary_error_details_;
};
} // namespace grpc
#endif // GRPCPP_IMPL_STATUS_H

150
Pods/gRPC-C++/include/grpcpp/impl/sync.h generated Normal file
View File

@@ -0,0 +1,150 @@
//
//
// Copyright 2019 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#ifndef GRPCPP_IMPL_SYNC_H
#define GRPCPP_IMPL_SYNC_H
#include <grpc/support/port_platform.h>
#ifdef GPR_HAS_PTHREAD_H
#include <pthread.h>
#endif
#include <mutex>
#include "absl/synchronization/mutex.h"
#include <grpc/support/log.h>
#include <grpc/support/sync.h>
#include <grpc/support/time.h>
// The core library is not accessible in C++ codegen headers, and vice versa.
// Thus, we need to have duplicate headers with similar functionality.
// Make sure any change to this file is also reflected in
// src/core/lib/gprpp/sync.h too.
//
// Whenever possible, prefer "src/core/lib/gprpp/sync.h" over this file,
// since in core we do not rely on g_core_codegen_interface and hence do not
// pay the costs of virtual function calls.
namespace grpc {
namespace internal {
#ifdef GPR_ABSEIL_SYNC
using Mutex = absl::Mutex;
using MutexLock = absl::MutexLock;
using ReleasableMutexLock = absl::ReleasableMutexLock;
using CondVar = absl::CondVar;
#else
class ABSL_LOCKABLE Mutex {
public:
Mutex() { gpr_mu_init(&mu_); }
~Mutex() { gpr_mu_destroy(&mu_); }
Mutex(const Mutex&) = delete;
Mutex& operator=(const Mutex&) = delete;
void Lock() ABSL_EXCLUSIVE_LOCK_FUNCTION() { gpr_mu_lock(&mu_); }
void Unlock() ABSL_UNLOCK_FUNCTION() { gpr_mu_unlock(&mu_); }
private:
union {
gpr_mu mu_;
std::mutex do_not_use_sth_;
#ifdef GPR_HAS_PTHREAD_H
pthread_mutex_t do_not_use_pth_;
#endif
};
friend class CondVar;
};
class ABSL_SCOPED_LOCKABLE MutexLock {
public:
explicit MutexLock(Mutex* mu) ABSL_EXCLUSIVE_LOCK_FUNCTION(mu) : mu_(mu) {
mu_->Lock();
}
~MutexLock() ABSL_UNLOCK_FUNCTION() { mu_->Unlock(); }
MutexLock(const MutexLock&) = delete;
MutexLock& operator=(const MutexLock&) = delete;
private:
Mutex* const mu_;
};
class ABSL_SCOPED_LOCKABLE ReleasableMutexLock {
public:
explicit ReleasableMutexLock(Mutex* mu) ABSL_EXCLUSIVE_LOCK_FUNCTION(mu)
: mu_(mu) {
mu_->Lock();
}
~ReleasableMutexLock() ABSL_UNLOCK_FUNCTION() {
if (!released_) mu_->Unlock();
}
ReleasableMutexLock(const ReleasableMutexLock&) = delete;
ReleasableMutexLock& operator=(const ReleasableMutexLock&) = delete;
void Release() ABSL_UNLOCK_FUNCTION() {
GPR_DEBUG_ASSERT(!released_);
released_ = true;
mu_->Unlock();
}
private:
Mutex* const mu_;
bool released_ = false;
};
class CondVar {
public:
CondVar() { gpr_cv_init(&cv_); }
~CondVar() { gpr_cv_destroy(&cv_); }
CondVar(const CondVar&) = delete;
CondVar& operator=(const CondVar&) = delete;
void Signal() { gpr_cv_signal(&cv_); }
void SignalAll() { gpr_cv_broadcast(&cv_); }
void Wait(Mutex* mu) {
gpr_cv_wait(&cv_, &mu->mu_, gpr_inf_future(GPR_CLOCK_REALTIME));
}
private:
gpr_cv cv_;
};
#endif // GPR_ABSEIL_SYNC
template <typename Predicate>
GRPC_DEPRECATED("incompatible with thread safety analysis")
static void WaitUntil(CondVar* cv, Mutex* mu, Predicate pred) {
while (!pred()) {
cv->Wait(mu);
}
}
} // namespace internal
} // namespace grpc
#endif // GRPCPP_IMPL_SYNC_H