| 1 |
/* |
| 2 |
* |
| 3 |
* Copyright 2015 gRPC authors. |
| 4 |
* |
| 5 |
* Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 |
* you may not use this file except in compliance with the License. |
| 7 |
* You may obtain a copy of the License at |
| 8 |
* |
| 9 |
* http://www.apache.org/licenses/LICENSE-2.0 |
| 10 |
* |
| 11 |
* Unless required by applicable law or agreed to in writing, software |
| 12 |
* distributed under the License is distributed on an "AS IS" BASIS, |
| 13 |
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 |
* See the License for the specific language governing permissions and |
| 15 |
* limitations under the License. |
| 16 |
* |
| 17 |
*/ |
| 18 |
|
| 19 |
#include <grpc/support/port_platform.h> |
| 20 |
|
| 21 |
#include "src/core/lib/surface/call.h" |
| 22 |
|
| 23 |
#include <inttypes.h> |
| 24 |
#include <limits.h> |
| 25 |
#include <stdlib.h> |
| 26 |
|
| 27 |
#include <algorithm> |
| 28 |
#include <atomic> |
| 29 |
#include <memory> |
| 30 |
#include <new> |
| 31 |
#include <string> |
| 32 |
#include <utility> |
| 33 |
#include <vector> |
| 34 |
|
| 35 |
#include "absl/base/thread_annotations.h" |
| 36 |
#include "absl/cleanup/cleanup.h" |
| 37 |
#include "absl/meta/type_traits.h" |
| 38 |
#include "absl/status/status.h" |
| 39 |
#include "absl/strings/str_cat.h" |
| 40 |
#include "absl/strings/str_format.h" |
| 41 |
#include "absl/strings/str_join.h" |
| 42 |
#include "absl/strings/string_view.h" |
| 43 |
#include "absl/types/variant.h" |
| 44 |
|
| 45 |
#include <grpc/byte_buffer.h> |
| 46 |
#include <grpc/compression.h> |
| 47 |
#include <grpc/event_engine/event_engine.h> |
| 48 |
#include <grpc/grpc.h> |
| 49 |
#include <grpc/impl/codegen/gpr_types.h> |
| 50 |
#include <grpc/impl/codegen/propagation_bits.h> |
| 51 |
#include <grpc/slice.h> |
| 52 |
#include <grpc/slice_buffer.h> |
| 53 |
#include <grpc/status.h> |
| 54 |
#include <grpc/support/alloc.h> |
| 55 |
#include <grpc/support/atm.h> |
| 56 |
#include <grpc/support/log.h> |
| 57 |
#include <grpc/support/string_util.h> |
| 58 |
|
| 59 |
#include "src/core/lib/channel/call_finalization.h" |
| 60 |
#include "src/core/lib/channel/channel_stack.h" |
| 61 |
#include "src/core/lib/channel/channelz.h" |
| 62 |
#include "src/core/lib/channel/context.h" |
| 63 |
#include "src/core/lib/channel/status_util.h" |
| 64 |
#include "src/core/lib/compression/compression_internal.h" |
| 65 |
#include "src/core/lib/debug/stats.h" |
| 66 |
#include "src/core/lib/debug/stats_data.h" |
| 67 |
#include "src/core/lib/experiments/experiments.h" |
| 68 |
#include "src/core/lib/gpr/alloc.h" |
| 69 |
#include "src/core/lib/gpr/time_precise.h" |
| 70 |
#include "src/core/lib/gpr/useful.h" |
| 71 |
#include "src/core/lib/gprpp/bitset.h" |
| 72 |
#include "src/core/lib/gprpp/cpp_impl_of.h" |
| 73 |
#include "src/core/lib/gprpp/debug_location.h" |
| 74 |
#include "src/core/lib/gprpp/ref_counted.h" |
| 75 |
#include "src/core/lib/gprpp/ref_counted_ptr.h" |
| 76 |
#include "src/core/lib/gprpp/status_helper.h" |
| 77 |
#include "src/core/lib/gprpp/sync.h" |
| 78 |
#include "src/core/lib/iomgr/call_combiner.h" |
| 79 |
#include "src/core/lib/iomgr/exec_ctx.h" |
| 80 |
#include "src/core/lib/iomgr/polling_entity.h" |
| 81 |
#include "src/core/lib/promise/activity.h" |
| 82 |
#include "src/core/lib/promise/arena_promise.h" |
| 83 |
#include "src/core/lib/promise/context.h" |
| 84 |
#include "src/core/lib/promise/latch.h" |
| 85 |
#include "src/core/lib/promise/pipe.h" |
| 86 |
#include "src/core/lib/promise/poll.h" |
| 87 |
#include "src/core/lib/resource_quota/arena.h" |
| 88 |
#include "src/core/lib/slice/slice_buffer.h" |
| 89 |
#include "src/core/lib/slice/slice_internal.h" |
| 90 |
#include "src/core/lib/surface/api_trace.h" |
| 91 |
#include "src/core/lib/surface/call_test_only.h" |
| 92 |
#include "src/core/lib/surface/channel.h" |
| 93 |
#include "src/core/lib/surface/completion_queue.h" |
| 94 |
#include "src/core/lib/surface/server.h" |
| 95 |
#include "src/core/lib/surface/validate_metadata.h" |
| 96 |
#include "src/core/lib/transport/error_utils.h" |
| 97 |
#include "src/core/lib/transport/metadata_batch.h" |
| 98 |
#include "src/core/lib/transport/transport.h" |
| 99 |
|
| 100 |
grpc_core::TraceFlag grpc_call_error_trace(false, "call_error"); |
| 101 |
grpc_core::TraceFlag grpc_compression_trace(false, "compression"); |
| 102 |
grpc_core::TraceFlag grpc_call_trace(false, "call"); |
| 103 |
grpc_core::TraceFlag grpc_call_refcount_trace(false, "call_refcount"); |
| 104 |
|
| 105 |
namespace grpc_core { |
| 106 |
|
| 107 |
/////////////////////////////////////////////////////////////////////////////// |
| 108 |
// Call |
| 109 |
|
| 110 |
class Call : public CppImplOf<Call, grpc_call> { |
| 111 |
public: |
| 112 |
Arena* arena() { return arena_; } |
| 113 |
bool is_client() const { return is_client_; } |
| 114 |
|
| 115 |
virtual void ContextSet(grpc_context_index elem, void* value, |
| 116 |
void (*destroy)(void* value)) = 0; |
| 117 |
virtual void* ContextGet(grpc_context_index elem) const = 0; |
| 118 |
virtual bool Completed() = 0; |
| 119 |
void CancelWithStatus(grpc_status_code status, const char* description); |
| 120 |
virtual void CancelWithError(grpc_error_handle error) = 0; |
| 121 |
virtual void SetCompletionQueue(grpc_completion_queue* cq) = 0; |
| 122 |
char* GetPeer(); |
| 123 |
virtual grpc_call_error StartBatch(const grpc_op* ops, size_t nops, |
| 124 |
void* notify_tag, |
| 125 |
bool is_notify_tag_closure) = 0; |
| 126 |
virtual bool failed_before_recv_message() const = 0; |
| 127 |
virtual bool is_trailers_only() const = 0; |
| 128 |
virtual absl::string_view GetServerAuthority() const = 0; |
| 129 |
virtual void ExternalRef() = 0; |
| 130 |
virtual void ExternalUnref() = 0; |
| 131 |
virtual void InternalRef(const char* reason) = 0; |
| 132 |
virtual void InternalUnref(const char* reason) = 0; |
| 133 |
|
| 134 |
virtual grpc_compression_algorithm test_only_compression_algorithm() = 0; |
| 135 |
virtual uint32_t test_only_message_flags() = 0; |
| 136 |
virtual uint32_t test_only_encodings_accepted_by_peer() = 0; |
| 137 |
virtual grpc_compression_algorithm compression_for_level( |
| 138 |
grpc_compression_level level) = 0; |
| 139 |
|
| 140 |
// This should return nullptr for the promise stack (and alternative means |
| 141 |
// for that functionality be invented) |
| 142 |
virtual grpc_call_stack* call_stack() = 0; |
| 143 |
|
| 144 |
gpr_atm* peer_string_atm_ptr() { return &peer_string_; } |
| 145 |
|
| 146 |
protected: |
| 147 |
// The maximum number of concurrent batches possible. |
| 148 |
// Based upon the maximum number of individually queueable ops in the batch |
| 149 |
// api: |
| 150 |
// - initial metadata send |
| 151 |
// - message send |
| 152 |
// - status/close send (depending on client/server) |
| 153 |
// - initial metadata recv |
| 154 |
// - message recv |
| 155 |
// - status/close recv (depending on client/server) |
| 156 |
static constexpr size_t kMaxConcurrentBatches = 6; |
| 157 |
|
| 158 |
struct ParentCall { |
| 159 |
Mutex child_list_mu; |
| 160 |
Call* first_child ABSL_GUARDED_BY(child_list_mu) = nullptr; |
| 161 |
}; |
| 162 |
|
| 163 |
struct ChildCall { |
| 164 |
explicit ChildCall(Call* parent) : parent(parent) {} |
| 165 |
Call* parent; |
| 166 |
/** siblings: children of the same parent form a list, and this list is |
| 167 |
protected under |
| 168 |
parent->mu */ |
| 169 |
Call* sibling_next = nullptr; |
| 170 |
Call* sibling_prev = nullptr; |
| 171 |
}; |
| 172 |
|
| 173 |
Call(Arena* arena, bool is_client, Timestamp send_deadline, |
| 174 |
RefCountedPtr<Channel> channel) |
| 175 |
: channel_(std::move(channel)), |
| 176 |
arena_(arena), |
| 177 |
send_deadline_(send_deadline), |
| 178 |
is_client_(is_client) { |
| 179 |
GPR_DEBUG_ASSERT(arena_ != nullptr); |
| 180 |
GPR_DEBUG_ASSERT(channel_ != nullptr); |
| 181 |
} |
| 182 |
virtual ~Call() = default; |
| 183 |
|
| 184 |
void DeleteThis(); |
| 185 |
|
| 186 |
ParentCall* GetOrCreateParentCall(); |
| 187 |
ParentCall* parent_call(); |
| 188 |
Channel* channel() { |
| 189 |
GPR_DEBUG_ASSERT(channel_ != nullptr); |
| 190 |
return channel_.get(); |
| 191 |
} |
| 192 |
|
| 193 |
absl::Status InitParent(Call* parent, uint32_t propagation_mask); |
| 194 |
void PublishToParent(Call* parent); |
| 195 |
void MaybeUnpublishFromParent(); |
| 196 |
void PropagateCancellationToChildren(); |
| 197 |
|
| 198 |
Timestamp send_deadline() const { return send_deadline_; } |
| 199 |
void set_send_deadline(Timestamp send_deadline) { |
| 200 |
send_deadline_ = send_deadline; |
| 201 |
} |
| 202 |
|
| 203 |
void ClearPeerString() { gpr_atm_rel_store(&peer_string_, 0); } |
| 204 |
|
| 205 |
private: |
| 206 |
RefCountedPtr<Channel> channel_; |
| 207 |
Arena* const arena_; |
| 208 |
std::atomic<ParentCall*> parent_call_{nullptr}; |
| 209 |
ChildCall* child_ = nullptr; |
| 210 |
Timestamp send_deadline_; |
| 211 |
const bool is_client_; |
| 212 |
// flag indicating that cancellation is inherited |
| 213 |
bool cancellation_is_inherited_ = false; |
| 214 |
// A char* indicating the peer name. |
| 215 |
gpr_atm peer_string_ = 0; |
| 216 |
}; |
| 217 |
|
| 218 |
Call::ParentCall* Call::GetOrCreateParentCall() { |
| 219 |
ParentCall* p = parent_call_.load(std::memory_order_acquire); |
| 220 |
if (p == nullptr) { |
| 221 |
p = arena_->New<ParentCall>(); |
| 222 |
ParentCall* expected = nullptr; |
| 223 |
if (!parent_call_.compare_exchange_strong(expected, p, |
| 224 |
std::memory_order_release, |
| 225 |
std::memory_order_relaxed)) { |
| 226 |
p->~ParentCall(); |
| 227 |
p = expected; |
| 228 |
} |
| 229 |
} |
| 230 |
return p; |
| 231 |
} |
| 232 |
|
| 233 |
Call::ParentCall* Call::parent_call() { |
| 234 |
return parent_call_.load(std::memory_order_acquire); |
| 235 |
} |
| 236 |
|
| 237 |
absl::Status Call::InitParent(Call* parent, uint32_t propagation_mask) { |
| 238 |
child_ = arena()->New<ChildCall>(parent); |
| 239 |
|
| 240 |
parent->InternalRef("child"); |
| 241 |
GPR_ASSERT(is_client_); |
| 242 |
GPR_ASSERT(!parent->is_client_); |
| 243 |
|
| 244 |
if (propagation_mask & GRPC_PROPAGATE_DEADLINE) { |
| 245 |
send_deadline_ = std::min(send_deadline_, parent->send_deadline_); |
| 246 |
} |
| 247 |
/* for now GRPC_PROPAGATE_TRACING_CONTEXT *MUST* be passed with |
| 248 |
* GRPC_PROPAGATE_STATS_CONTEXT */ |
| 249 |
/* TODO(ctiller): This should change to use the appropriate census start_op |
| 250 |
* call. */ |
| 251 |
if (propagation_mask & GRPC_PROPAGATE_CENSUS_TRACING_CONTEXT) { |
| 252 |
if (0 == (propagation_mask & GRPC_PROPAGATE_CENSUS_STATS_CONTEXT)) { |
| 253 |
return absl::UnknownError( |
| 254 |
"Census tracing propagation requested without Census context " |
| 255 |
"propagation"); |
| 256 |
} |
| 257 |
ContextSet(GRPC_CONTEXT_TRACING, parent->ContextGet(GRPC_CONTEXT_TRACING), |
| 258 |
nullptr); |
| 259 |
} else if (propagation_mask & GRPC_PROPAGATE_CENSUS_STATS_CONTEXT) { |
| 260 |
return absl::UnknownError( |
| 261 |
"Census context propagation requested without Census tracing " |
| 262 |
"propagation"); |
| 263 |
} |
| 264 |
if (propagation_mask & GRPC_PROPAGATE_CANCELLATION) { |
| 265 |
cancellation_is_inherited_ = true; |
| 266 |
} |
| 267 |
return absl::OkStatus(); |
| 268 |
} |
| 269 |
|
| 270 |
void Call::PublishToParent(Call* parent) { |
| 271 |
ChildCall* cc = child_; |
| 272 |
ParentCall* pc = parent->GetOrCreateParentCall(); |
| 273 |
MutexLock lock(&pc->child_list_mu); |
| 274 |
if (pc->first_child == nullptr) { |
| 275 |
pc->first_child = this; |
| 276 |
cc->sibling_next = cc->sibling_prev = this; |
| 277 |
} else { |
| 278 |
cc->sibling_next = pc->first_child; |
| 279 |
cc->sibling_prev = pc->first_child->child_->sibling_prev; |
| 280 |
cc->sibling_next->child_->sibling_prev = |
| 281 |
cc->sibling_prev->child_->sibling_next = this; |
| 282 |
} |
| 283 |
if (parent->Completed()) { |
| 284 |
CancelWithError(absl::CancelledError()); |
| 285 |
} |
| 286 |
} |
| 287 |
|
| 288 |
void Call::MaybeUnpublishFromParent() { |
| 289 |
ChildCall* cc = child_; |
| 290 |
if (cc == nullptr) return; |
| 291 |
|
| 292 |
ParentCall* pc = cc->parent->parent_call(); |
| 293 |
{ |
| 294 |
MutexLock lock(&pc->child_list_mu); |
| 295 |
if (this == pc->first_child) { |
| 296 |
pc->first_child = cc->sibling_next; |
| 297 |
if (this == pc->first_child) { |
| 298 |
pc->first_child = nullptr; |
| 299 |
} |
| 300 |
} |
| 301 |
cc->sibling_prev->child_->sibling_next = cc->sibling_next; |
| 302 |
cc->sibling_next->child_->sibling_prev = cc->sibling_prev; |
| 303 |
} |
| 304 |
cc->parent->InternalUnref("child"); |
| 305 |
} |
| 306 |
|
| 307 |
void Call::CancelWithStatus(grpc_status_code status, const char* description) { |
| 308 |
// copying 'description' is needed to ensure the grpc_call_cancel_with_status |
| 309 |
// guarantee that can be short-lived. |
| 310 |
CancelWithError(grpc_error_set_int( |
| 311 |
grpc_error_set_str(GRPC_ERROR_CREATE(description), |
| 312 |
StatusStrProperty::kGrpcMessage, description), |
| 313 |
StatusIntProperty::kRpcStatus, status)); |
| 314 |
} |
| 315 |
|
| 316 |
void Call::PropagateCancellationToChildren() { |
| 317 |
ParentCall* pc = parent_call(); |
| 318 |
if (pc != nullptr) { |
| 319 |
Call* child; |
| 320 |
MutexLock lock(&pc->child_list_mu); |
| 321 |
child = pc->first_child; |
| 322 |
if (child != nullptr) { |
| 323 |
do { |
| 324 |
Call* next_child_call = child->child_->sibling_next; |
| 325 |
if (child->cancellation_is_inherited_) { |
| 326 |
child->InternalRef("propagate_cancel"); |
| 327 |
child->CancelWithError(absl::CancelledError()); |
| 328 |
child->InternalUnref("propagate_cancel"); |
| 329 |
} |
| 330 |
child = next_child_call; |
| 331 |
} while (child != pc->first_child); |
| 332 |
} |
| 333 |
} |
| 334 |
} |
| 335 |
|
| 336 |
char* Call::GetPeer() { |
| 337 |
char* peer_string = reinterpret_cast<char*>(gpr_atm_acq_load(&peer_string_)); |
| 338 |
if (peer_string != nullptr) return gpr_strdup(peer_string); |
| 339 |
peer_string = grpc_channel_get_target(channel_->c_ptr()); |
| 340 |
if (peer_string != nullptr) return peer_string; |
| 341 |
return gpr_strdup("unknown"); |
| 342 |
} |
| 343 |
|
| 344 |
void Call::DeleteThis() { |
| 345 |
RefCountedPtr<Channel> channel = std::move(channel_); |
| 346 |
Arena* arena = arena_; |
| 347 |
this->~Call(); |
| 348 |
channel->UpdateCallSizeEstimate(arena->Destroy()); |
| 349 |
} |
| 350 |
|
| 351 |
/////////////////////////////////////////////////////////////////////////////// |
| 352 |
// FilterStackCall |
| 353 |
// To be removed once promise conversion is complete |
| 354 |
|
| 355 |
class FilterStackCall final : public Call { |
| 356 |
public: |
| 357 |
~FilterStackCall() override { |
| 358 |
for (int i = 0; i < GRPC_CONTEXT_COUNT; ++i) { |
| 359 |
if (context_[i].destroy) { |
| 360 |
context_[i].destroy(context_[i].value); |
| 361 |
} |
| 362 |
} |
| 363 |
gpr_free(static_cast<void*>(const_cast<char*>(final_info_.error_string))); |
| 364 |
} |
| 365 |
|
| 366 |
bool Completed() override { |
| 367 |
return gpr_atm_acq_load(&received_final_op_atm_) != 0; |
| 368 |
} |
| 369 |
|
| 370 |
// TODO(ctiller): return absl::StatusOr<SomeSmartPointer<Call>>? |
| 371 |
static grpc_error_handle Create(grpc_call_create_args* args, |
| 372 |
grpc_call** out_call); |
| 373 |
|
| 374 |
static Call* FromTopElem(grpc_call_element* elem) { |
| 375 |
return FromCallStack(grpc_call_stack_from_top_element(elem)); |
| 376 |
} |
| 377 |
|
| 378 |
grpc_call_stack* call_stack() override { |
| 379 |
return reinterpret_cast<grpc_call_stack*>( |
| 380 |
reinterpret_cast<char*>(this) + |
| 381 |
GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(*this))); |
| 382 |
} |
| 383 |
|
| 384 |
grpc_call_element* call_elem(size_t idx) { |
| 385 |
return grpc_call_stack_element(call_stack(), idx); |
| 386 |
} |
| 387 |
|
| 388 |
CallCombiner* call_combiner() { return &call_combiner_; } |
| 389 |
|
| 390 |
void CancelWithError(grpc_error_handle error) override; |
| 391 |
void SetCompletionQueue(grpc_completion_queue* cq) override; |
| 392 |
grpc_call_error StartBatch(const grpc_op* ops, size_t nops, void* notify_tag, |
| 393 |
bool is_notify_tag_closure) override; |
| 394 |
void ExternalRef() override { ext_ref_.Ref(); } |
| 395 |
void ExternalUnref() override; |
| 396 |
void InternalRef(const char* reason) override { |
| 397 |
GRPC_CALL_STACK_REF(call_stack(), reason); |
| 398 |
} |
| 399 |
void InternalUnref(const char* reason) override { |
| 400 |
GRPC_CALL_STACK_UNREF(call_stack(), reason); |
| 401 |
} |
| 402 |
|
| 403 |
void ContextSet(grpc_context_index elem, void* value, |
| 404 |
void (*destroy)(void* value)) override; |
| 405 |
void* ContextGet(grpc_context_index elem) const override { |
| 406 |
return context_[elem].value; |
| 407 |
} |
| 408 |
|
| 409 |
grpc_compression_algorithm compression_for_level( |
| 410 |
grpc_compression_level level) override { |
| 411 |
return encodings_accepted_by_peer_.CompressionAlgorithmForLevel(level); |
| 412 |
} |
| 413 |
|
| 414 |
bool is_trailers_only() const override { |
| 415 |
bool result = is_trailers_only_; |
| 416 |
GPR_DEBUG_ASSERT(!result || recv_initial_metadata_.TransportSize() == 0); |
| 417 |
return result; |
| 418 |
} |
| 419 |
|
| 420 |
bool failed_before_recv_message() const override { |
| 421 |
return call_failed_before_recv_message_; |
| 422 |
} |
| 423 |
|
| 424 |
absl::string_view GetServerAuthority() const override { |
| 425 |
const Slice* authority_metadata = |
| 426 |
recv_initial_metadata_.get_pointer(HttpAuthorityMetadata()); |
| 427 |
if (authority_metadata == nullptr) return ""; |
| 428 |
return authority_metadata->as_string_view(); |
| 429 |
} |
| 430 |
|
| 431 |
grpc_compression_algorithm test_only_compression_algorithm() override { |
| 432 |
return incoming_compression_algorithm_; |
| 433 |
} |
| 434 |
|
| 435 |
uint32_t test_only_message_flags() override { |
| 436 |
return test_only_last_message_flags_; |
| 437 |
} |
| 438 |
|
| 439 |
uint32_t test_only_encodings_accepted_by_peer() override { |
| 440 |
return encodings_accepted_by_peer_.ToLegacyBitmask(); |
| 441 |
} |
| 442 |
|
| 443 |
static size_t InitialSizeEstimate() { |
| 444 |
return sizeof(FilterStackCall) + |
| 445 |
sizeof(BatchControl) * kMaxConcurrentBatches; |
| 446 |
} |
| 447 |
|
| 448 |
private: |
| 449 |
static constexpr gpr_atm kRecvNone = 0; |
| 450 |
static constexpr gpr_atm kRecvInitialMetadataFirst = 1; |
| 451 |
|
| 452 |
struct BatchControl { |
| 453 |
FilterStackCall* call_ = nullptr; |
| 454 |
grpc_transport_stream_op_batch op_; |
| 455 |
/* Share memory for cq_completion and notify_tag as they are never needed |
| 456 |
simultaneously. Each byte used in this data structure count as six bytes |
| 457 |
per call, so any savings we can make are worthwhile, |
| 458 |
|
| 459 |
We use notify_tag to determine whether or not to send notification to the |
| 460 |
completion queue. Once we've made that determination, we can reuse the |
| 461 |
memory for cq_completion. */ |
| 462 |
union { |
| 463 |
grpc_cq_completion cq_completion; |
| 464 |
struct { |
| 465 |
/* Any given op indicates completion by either (a) calling a closure or |
| 466 |
(b) sending a notification on the call's completion queue. If |
| 467 |
\a is_closure is true, \a tag indicates a closure to be invoked; |
| 468 |
otherwise, \a tag indicates the tag to be used in the notification to |
| 469 |
be sent to the completion queue. */ |
| 470 |
void* tag; |
| 471 |
bool is_closure; |
| 472 |
} notify_tag; |
| 473 |
} completion_data_; |
| 474 |
grpc_closure start_batch_; |
| 475 |
grpc_closure finish_batch_; |
| 476 |
std::atomic<intptr_t> steps_to_complete_{0}; |
| 477 |
AtomicError batch_error_; |
| 478 |
void set_num_steps_to_complete(uintptr_t steps) { |
| 479 |
steps_to_complete_.store(steps, std::memory_order_release); |
| 480 |
} |
| 481 |
bool completed_batch_step() { |
| 482 |
return steps_to_complete_.fetch_sub(1, std::memory_order_acq_rel) == 1; |
| 483 |
} |
| 484 |
|
| 485 |
void PostCompletion(); |
| 486 |
void FinishStep(); |
| 487 |
void ProcessDataAfterMetadata(); |
| 488 |
void ReceivingStreamReady(grpc_error_handle error); |
| 489 |
void ValidateFilteredMetadata(); |
| 490 |
void ReceivingInitialMetadataReady(grpc_error_handle error); |
| 491 |
void ReceivingTrailingMetadataReady(grpc_error_handle error); |
| 492 |
void FinishBatch(grpc_error_handle error); |
| 493 |
}; |
| 494 |
|
| 495 |
FilterStackCall(Arena* arena, const grpc_call_create_args& args) |
| 496 |
: Call(arena, args.server_transport_data == nullptr, args.send_deadline, |
| 497 |
args.channel->Ref()), |
| 498 |
cq_(args.cq), |
| 499 |
stream_op_payload_(context_) {} |
| 500 |
|
| 501 |
static void ReleaseCall(void* call, grpc_error_handle); |
| 502 |
static void DestroyCall(void* call, grpc_error_handle); |
| 503 |
|
| 504 |
static FilterStackCall* FromCallStack(grpc_call_stack* call_stack) { |
| 505 |
return reinterpret_cast<FilterStackCall*>( |
| 506 |
reinterpret_cast<char*>(call_stack) - |
| 507 |
GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(FilterStackCall))); |
| 508 |
} |
| 509 |
|
| 510 |
void ExecuteBatch(grpc_transport_stream_op_batch* batch, |
| 511 |
grpc_closure* start_batch_closure); |
| 512 |
void SetFinalStatus(grpc_error_handle error); |
| 513 |
BatchControl* ReuseOrAllocateBatchControl(const grpc_op* ops); |
| 514 |
void HandleCompressionAlgorithmDisabled( |
| 515 |
grpc_compression_algorithm compression_algorithm) GPR_ATTRIBUTE_NOINLINE; |
| 516 |
void HandleCompressionAlgorithmNotAccepted( |
| 517 |
grpc_compression_algorithm compression_algorithm) GPR_ATTRIBUTE_NOINLINE; |
| 518 |
bool PrepareApplicationMetadata(size_t count, grpc_metadata* metadata, |
| 519 |
bool is_trailing); |
| 520 |
void PublishAppMetadata(grpc_metadata_batch* b, bool is_trailing); |
| 521 |
void RecvInitialFilter(grpc_metadata_batch* b); |
| 522 |
void RecvTrailingFilter(grpc_metadata_batch* b, |
| 523 |
grpc_error_handle batch_error); |
| 524 |
|
| 525 |
RefCount ext_ref_; |
| 526 |
CallCombiner call_combiner_; |
| 527 |
grpc_completion_queue* cq_; |
| 528 |
grpc_polling_entity pollent_; |
| 529 |
gpr_cycle_counter start_time_ = gpr_get_cycle_counter(); |
| 530 |
|
| 531 |
/** has grpc_call_unref been called */ |
| 532 |
bool destroy_called_ = false; |
| 533 |
// Trailers-only response status |
| 534 |
bool is_trailers_only_ = false; |
| 535 |
/** which ops are in-flight */ |
| 536 |
bool sent_initial_metadata_ = false; |
| 537 |
bool sending_message_ = false; |
| 538 |
bool sent_final_op_ = false; |
| 539 |
bool received_initial_metadata_ = false; |
| 540 |
bool receiving_message_ = false; |
| 541 |
bool requested_final_op_ = false; |
| 542 |
gpr_atm received_final_op_atm_ = 0; |
| 543 |
|
| 544 |
BatchControl* active_batches_[kMaxConcurrentBatches] = {}; |
| 545 |
grpc_transport_stream_op_batch_payload stream_op_payload_; |
| 546 |
|
| 547 |
/* first idx: is_receiving, second idx: is_trailing */ |
| 548 |
grpc_metadata_batch send_initial_metadata_{arena()}; |
| 549 |
grpc_metadata_batch send_trailing_metadata_{arena()}; |
| 550 |
grpc_metadata_batch recv_initial_metadata_{arena()}; |
| 551 |
grpc_metadata_batch recv_trailing_metadata_{arena()}; |
| 552 |
|
| 553 |
/* Buffered read metadata waiting to be returned to the application. |
| 554 |
Element 0 is initial metadata, element 1 is trailing metadata. */ |
| 555 |
grpc_metadata_array* buffered_metadata_[2] = {}; |
| 556 |
|
| 557 |
/* Call data useful used for reporting. Only valid after the call has |
| 558 |
* completed */ |
| 559 |
grpc_call_final_info final_info_; |
| 560 |
|
| 561 |
/* Compression algorithm for *incoming* data */ |
| 562 |
grpc_compression_algorithm incoming_compression_algorithm_ = |
| 563 |
GRPC_COMPRESS_NONE; |
| 564 |
/* Supported encodings (compression algorithms), a bitset. |
| 565 |
* Always support no compression. */ |
| 566 |
CompressionAlgorithmSet encodings_accepted_by_peer_{GRPC_COMPRESS_NONE}; |
| 567 |
|
| 568 |
/* Contexts for various subsystems (security, tracing, ...). */ |
| 569 |
grpc_call_context_element context_[GRPC_CONTEXT_COUNT] = {}; |
| 570 |
|
| 571 |
SliceBuffer send_slice_buffer_; |
| 572 |
absl::optional<SliceBuffer> receiving_slice_buffer_; |
| 573 |
uint32_t receiving_stream_flags_; |
| 574 |
|
| 575 |
bool call_failed_before_recv_message_ = false; |
| 576 |
grpc_byte_buffer** receiving_buffer_ = nullptr; |
| 577 |
grpc_slice receiving_slice_ = grpc_empty_slice(); |
| 578 |
grpc_closure receiving_stream_ready_; |
| 579 |
grpc_closure receiving_initial_metadata_ready_; |
| 580 |
grpc_closure receiving_trailing_metadata_ready_; |
| 581 |
uint32_t test_only_last_message_flags_ = 0; |
| 582 |
// Status about operation of call |
| 583 |
bool sent_server_trailing_metadata_ = false; |
| 584 |
gpr_atm cancelled_with_error_ = 0; |
| 585 |
|
| 586 |
grpc_closure release_call_; |
| 587 |
|
| 588 |
union { |
| 589 |
struct { |
| 590 |
grpc_status_code* status; |
| 591 |
grpc_slice* status_details; |
| 592 |
const char** error_string; |
| 593 |
} client; |
| 594 |
struct { |
| 595 |
int* cancelled; |
| 596 |
// backpointer to owning server if this is a server side call. |
| 597 |
Server* core_server; |
| 598 |
} server; |
| 599 |
} final_op_; |
| 600 |
AtomicError status_error_; |
| 601 |
|
| 602 |
/* recv_state can contain one of the following values: |
| 603 |
RECV_NONE : : no initial metadata and messages received |
| 604 |
RECV_INITIAL_METADATA_FIRST : received initial metadata first |
| 605 |
a batch_control* : received messages first |
| 606 |
|
| 607 |
+------1------RECV_NONE------3-----+ |
| 608 |
| | |
| 609 |
| | |
| 610 |
v v |
| 611 |
RECV_INITIAL_METADATA_FIRST receiving_stream_ready_bctlp |
| 612 |
| ^ | ^ |
| 613 |
| | | | |
| 614 |
+-----2-----+ +-----4-----+ |
| 615 |
|
| 616 |
For 1, 4: See receiving_initial_metadata_ready() function |
| 617 |
For 2, 3: See receiving_stream_ready() function */ |
| 618 |
gpr_atm recv_state_ = 0; |
| 619 |
}; |
| 620 |
|
| 621 |
grpc_error_handle FilterStackCall::Create(grpc_call_create_args* args, |
| 622 |
grpc_call** out_call) { |
| 623 |
Channel* channel = args->channel.get(); |
| 624 |
|
| 625 |
auto add_init_error = [](grpc_error_handle* composite, |
| 626 |
grpc_error_handle new_err) { |
| 627 |
if (new_err.ok()) return; |
| 628 |
if (composite->ok()) { |
| 629 |
*composite = GRPC_ERROR_CREATE("Call creation failed"); |
| 630 |
} |
| 631 |
*composite = grpc_error_add_child(*composite, new_err); |
| 632 |
}; |
| 633 |
|
| 634 |
Arena* arena; |
| 635 |
FilterStackCall* call; |
| 636 |
grpc_error_handle error; |
| 637 |
grpc_channel_stack* channel_stack = channel->channel_stack(); |
| 638 |
size_t initial_size = channel->CallSizeEstimate(); |
| 639 |
global_stats().IncrementCallInitialSize(initial_size); |
| 640 |
size_t call_alloc_size = |
| 641 |
GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(FilterStackCall)) + |
| 642 |
channel_stack->call_stack_size; |
| 643 |
|
| 644 |
std::pair<Arena*, void*> arena_with_call = Arena::CreateWithAlloc( |
| 645 |
initial_size, call_alloc_size, channel->allocator()); |
| 646 |
arena = arena_with_call.first; |
| 647 |
call = new (arena_with_call.second) FilterStackCall(arena, *args); |
| 648 |
GPR_DEBUG_ASSERT(FromC(call->c_ptr()) == call); |
| 649 |
GPR_DEBUG_ASSERT(FromCallStack(call->call_stack()) == call); |
| 650 |
*out_call = call->c_ptr(); |
| 651 |
grpc_slice path = grpc_empty_slice(); |
| 652 |
if (call->is_client()) { |
| 653 |
call->final_op_.client.status_details = nullptr; |
| 654 |
call->final_op_.client.status = nullptr; |
| 655 |
call->final_op_.client.error_string = nullptr; |
| 656 |
global_stats().IncrementClientCallsCreated(); |
| 657 |
path = CSliceRef(args->path->c_slice()); |
| 658 |
call->send_initial_metadata_.Set(HttpPathMetadata(), |
| 659 |
std::move(*args->path)); |
| 660 |
if (args->authority.has_value()) { |
| 661 |
call->send_initial_metadata_.Set(HttpAuthorityMetadata(), |
| 662 |
std::move(*args->authority)); |
| 663 |
} |
| 664 |
} else { |
| 665 |
global_stats().IncrementServerCallsCreated(); |
| 666 |
call->final_op_.server.cancelled = nullptr; |
| 667 |
call->final_op_.server.core_server = args->server; |
| 668 |
} |
| 669 |
|
| 670 |
Call* parent = Call::FromC(args->parent); |
| 671 |
if (parent != nullptr) { |
| 672 |
add_init_error(&error, absl_status_to_grpc_error(call->InitParent( |
| 673 |
parent, args->propagation_mask))); |
| 674 |
} |
| 675 |
/* initial refcount dropped by grpc_call_unref */ |
| 676 |
grpc_call_element_args call_args = { |
| 677 |
call->call_stack(), args->server_transport_data, |
| 678 |
call->context_, path, |
| 679 |
call->start_time_, call->send_deadline(), |
| 680 |
call->arena(), &call->call_combiner_}; |
| 681 |
add_init_error(&error, grpc_call_stack_init(channel_stack, 1, DestroyCall, |
| 682 |
call, &call_args)); |
| 683 |
// Publish this call to parent only after the call stack has been initialized. |
| 684 |
if (parent != nullptr) { |
| 685 |
call->PublishToParent(parent); |
| 686 |
} |
| 687 |
|
| 688 |
if (!error.ok()) { |
| 689 |
call->CancelWithError(error); |
| 690 |
} |
| 691 |
if (args->cq != nullptr) { |
| 692 |
GPR_ASSERT(args->pollset_set_alternative == nullptr && |
| 693 |
"Only one of 'cq' and 'pollset_set_alternative' should be " |
| 694 |
"non-nullptr."); |
| 695 |
GRPC_CQ_INTERNAL_REF(args->cq, "bind"); |
| 696 |
call->pollent_ = |
| 697 |
grpc_polling_entity_create_from_pollset(grpc_cq_pollset(args->cq)); |
| 698 |
} |
| 699 |
if (args->pollset_set_alternative != nullptr) { |
| 700 |
call->pollent_ = grpc_polling_entity_create_from_pollset_set( |
| 701 |
args->pollset_set_alternative); |
| 702 |
} |
| 703 |
if (!grpc_polling_entity_is_empty(&call->pollent_)) { |
| 704 |
grpc_call_stack_set_pollset_or_pollset_set(call->call_stack(), |
| 705 |
&call->pollent_); |
| 706 |
} |
| 707 |
|
| 708 |
if (call->is_client()) { |
| 709 |
channelz::ChannelNode* channelz_channel = channel->channelz_node(); |
| 710 |
if (channelz_channel != nullptr) { |
| 711 |
channelz_channel->RecordCallStarted(); |
| 712 |
} |
| 713 |
} else if (call->final_op_.server.core_server != nullptr) { |
| 714 |
channelz::ServerNode* channelz_node = |
| 715 |
call->final_op_.server.core_server->channelz_node(); |
| 716 |
if (channelz_node != nullptr) { |
| 717 |
channelz_node->RecordCallStarted(); |
| 718 |
} |
| 719 |
} |
| 720 |
|
| 721 |
CSliceUnref(path); |
| 722 |
|
| 723 |
return error; |
| 724 |
} |
| 725 |
|
| 726 |
void FilterStackCall::SetCompletionQueue(grpc_completion_queue* cq) { |
| 727 |
GPR_ASSERT(cq); |
| 728 |
|
| 729 |
if (grpc_polling_entity_pollset_set(&pollent_) != nullptr) { |
| 730 |
gpr_log(GPR_ERROR, "A pollset_set is already registered for this call."); |
| 731 |
abort(); |
| 732 |
} |
| 733 |
cq_ = cq; |
| 734 |
GRPC_CQ_INTERNAL_REF(cq, "bind"); |
| 735 |
pollent_ = grpc_polling_entity_create_from_pollset(grpc_cq_pollset(cq)); |
| 736 |
grpc_call_stack_set_pollset_or_pollset_set(call_stack(), &pollent_); |
| 737 |
} |
| 738 |
|
| 739 |
void FilterStackCall::ReleaseCall(void* call, grpc_error_handle /*error*/) { |
| 740 |
static_cast<FilterStackCall*>(call)->DeleteThis(); |
| 741 |
} |
| 742 |
|
| 743 |
void FilterStackCall::DestroyCall(void* call, grpc_error_handle /*error*/) { |
| 744 |
auto* c = static_cast<FilterStackCall*>(call); |
| 745 |
c->recv_initial_metadata_.Clear(); |
| 746 |
c->recv_trailing_metadata_.Clear(); |
| 747 |
c->receiving_slice_buffer_.reset(); |
| 748 |
ParentCall* pc = c->parent_call(); |
| 749 |
if (pc != nullptr) { |
| 750 |
pc->~ParentCall(); |
| 751 |
} |
| 752 |
if (c->cq_) { |
| 753 |
GRPC_CQ_INTERNAL_UNREF(c->cq_, "bind"); |
| 754 |
} |
| 755 |
|
| 756 |
grpc_error_handle status_error = c->status_error_.get(); |
| 757 |
grpc_error_get_status(status_error, c->send_deadline(), |
| 758 |
&c->final_info_.final_status, nullptr, nullptr, |
| 759 |
&(c->final_info_.error_string)); |
| 760 |
c->status_error_.set(absl::OkStatus()); |
| 761 |
c->final_info_.stats.latency = |
| 762 |
gpr_cycle_counter_sub(gpr_get_cycle_counter(), c->start_time_); |
| 763 |
grpc_call_stack_destroy(c->call_stack(), &c->final_info_, |
| 764 |
GRPC_CLOSURE_INIT(&c->release_call_, ReleaseCall, c, |
| 765 |
grpc_schedule_on_exec_ctx)); |
| 766 |
} |
| 767 |
|
| 768 |
void FilterStackCall::ExternalUnref() { |
| 769 |
if (GPR_LIKELY(!ext_ref_.Unref())) return; |
| 770 |
|
| 771 |
ApplicationCallbackExecCtx callback_exec_ctx; |
| 772 |
ExecCtx exec_ctx; |
| 773 |
|
| 774 |
GRPC_API_TRACE("grpc_call_unref(c=%p)", 1, (this)); |
| 775 |
|
| 776 |
MaybeUnpublishFromParent(); |
| 777 |
|
| 778 |
GPR_ASSERT(!destroy_called_); |
| 779 |
destroy_called_ = true; |
| 780 |
bool cancel = gpr_atm_acq_load(&received_final_op_atm_) == 0; |
| 781 |
if (cancel) { |
| 782 |
CancelWithError(absl::CancelledError()); |
| 783 |
} else { |
| 784 |
// Unset the call combiner cancellation closure. This has the |
| 785 |
// effect of scheduling the previously set cancellation closure, if |
| 786 |
// any, so that it can release any internal references it may be |
| 787 |
// holding to the call stack. |
| 788 |
call_combiner_.SetNotifyOnCancel(nullptr); |
| 789 |
} |
| 790 |
InternalUnref("destroy"); |
| 791 |
} |
| 792 |
|
| 793 |
// start_batch_closure points to a caller-allocated closure to be used |
| 794 |
// for entering the call combiner. |
| 795 |
void FilterStackCall::ExecuteBatch(grpc_transport_stream_op_batch* batch, |
| 796 |
grpc_closure* start_batch_closure) { |
| 797 |
// This is called via the call combiner to start sending a batch down |
| 798 |
// the filter stack. |
| 799 |
auto execute_batch_in_call_combiner = [](void* arg, grpc_error_handle) { |
| 800 |
grpc_transport_stream_op_batch* batch = |
| 801 |
static_cast<grpc_transport_stream_op_batch*>(arg); |
| 802 |
auto* call = |
| 803 |
static_cast<FilterStackCall*>(batch->handler_private.extra_arg); |
| 804 |
grpc_call_element* elem = call->call_elem(0); |
| 805 |
GRPC_CALL_LOG_OP(GPR_INFO, elem, batch); |
| 806 |
elem->filter->start_transport_stream_op_batch(elem, batch); |
| 807 |
}; |
| 808 |
batch->handler_private.extra_arg = this; |
| 809 |
GRPC_CLOSURE_INIT(start_batch_closure, execute_batch_in_call_combiner, batch, |
| 810 |
grpc_schedule_on_exec_ctx); |
| 811 |
GRPC_CALL_COMBINER_START(call_combiner(), start_batch_closure, |
| 812 |
absl::OkStatus(), "executing batch"); |
| 813 |
} |
| 814 |
|
| 815 |
namespace { |
| 816 |
struct CancelState { |
| 817 |
FilterStackCall* call; |
| 818 |
grpc_closure start_batch; |
| 819 |
grpc_closure finish_batch; |
| 820 |
}; |
| 821 |
} // namespace |
| 822 |
|
| 823 |
// The on_complete callback used when sending a cancel_stream batch down |
| 824 |
// the filter stack. Yields the call combiner when the batch is done. |
| 825 |
static void done_termination(void* arg, grpc_error_handle /*error*/) { |
| 826 |
CancelState* state = static_cast<CancelState*>(arg); |
| 827 |
GRPC_CALL_COMBINER_STOP(state->call->call_combiner(), |
| 828 |
"on_complete for cancel_stream op"); |
| 829 |
state->call->InternalUnref("termination"); |
| 830 |
delete state; |
| 831 |
} |
| 832 |
|
| 833 |
void FilterStackCall::CancelWithError(grpc_error_handle error) { |
| 834 |
if (!gpr_atm_rel_cas(&cancelled_with_error_, 0, 1)) { |
| 835 |
return; |
| 836 |
} |
| 837 |
ClearPeerString(); |
| 838 |
InternalRef("termination"); |
| 839 |
// Inform the call combiner of the cancellation, so that it can cancel |
| 840 |
// any in-flight asynchronous actions that may be holding the call |
| 841 |
// combiner. This ensures that the cancel_stream batch can be sent |
| 842 |
// down the filter stack in a timely manner. |
| 843 |
call_combiner_.Cancel(error); |
| 844 |
CancelState* state = new CancelState; |
| 845 |
state->call = this; |
| 846 |
GRPC_CLOSURE_INIT(&state->finish_batch, done_termination, state, |
| 847 |
grpc_schedule_on_exec_ctx); |
| 848 |
grpc_transport_stream_op_batch* op = |
| 849 |
grpc_make_transport_stream_op(&state->finish_batch); |
| 850 |
op->cancel_stream = true; |
| 851 |
op->payload->cancel_stream.cancel_error = error; |
| 852 |
ExecuteBatch(op, &state->start_batch); |
| 853 |
} |
| 854 |
|
| 855 |
void FilterStackCall::SetFinalStatus(grpc_error_handle error) { |
| 856 |
if (GRPC_TRACE_FLAG_ENABLED(grpc_call_error_trace)) { |
| 857 |
gpr_log(GPR_DEBUG, "set_final_status %s", is_client() ? "CLI" : "SVR"); |
| 858 |
gpr_log(GPR_DEBUG, "%s", StatusToString(error).c_str()); |
| 859 |
} |
| 860 |
if (is_client()) { |
| 861 |
std::string status_details; |
| 862 |
grpc_error_get_status(error, send_deadline(), final_op_.client.status, |
| 863 |
&status_details, nullptr, |
| 864 |
final_op_.client.error_string); |
| 865 |
*final_op_.client.status_details = |
| 866 |
grpc_slice_from_cpp_string(std::move(status_details)); |
| 867 |
status_error_.set(error); |
| 868 |
channelz::ChannelNode* channelz_channel = channel()->channelz_node(); |
| 869 |
if (channelz_channel != nullptr) { |
| 870 |
if (*final_op_.client.status != GRPC_STATUS_OK) { |
| 871 |
channelz_channel->RecordCallFailed(); |
| 872 |
} else { |
| 873 |
channelz_channel->RecordCallSucceeded(); |
| 874 |
} |
| 875 |
} |
| 876 |
} else { |
| 877 |
*final_op_.server.cancelled = |
| 878 |
!error.ok() || !sent_server_trailing_metadata_; |
| 879 |
channelz::ServerNode* channelz_node = |
| 880 |
final_op_.server.core_server->channelz_node(); |
| 881 |
if (channelz_node != nullptr) { |
| 882 |
if (*final_op_.server.cancelled || !status_error_.ok()) { |
| 883 |
channelz_node->RecordCallFailed(); |
| 884 |
} else { |
| 885 |
channelz_node->RecordCallSucceeded(); |
| 886 |
} |
| 887 |
} |
| 888 |
} |
| 889 |
} |
| 890 |
|
| 891 |
bool FilterStackCall::PrepareApplicationMetadata(size_t count, |
| 892 |
grpc_metadata* metadata, |
| 893 |
bool is_trailing) { |
| 894 |
grpc_metadata_batch* batch = |
| 895 |
is_trailing ? &send_trailing_metadata_ : &send_initial_metadata_; |
| 896 |
for (size_t i = 0; i < count; i++) { |
| 897 |
grpc_metadata* md = &metadata[i]; |
| 898 |
if (!GRPC_LOG_IF_ERROR("validate_metadata", |
| 899 |
grpc_validate_header_key_is_legal(md->key))) { |
| 900 |
return false; |
| 901 |
} else if (!grpc_is_binary_header_internal(md->key) && |
| 902 |
!GRPC_LOG_IF_ERROR( |
| 903 |
"validate_metadata", |
| 904 |
grpc_validate_header_nonbin_value_is_legal(md->value))) { |
| 905 |
return false; |
| 906 |
} else if (GRPC_SLICE_LENGTH(md->value) >= UINT32_MAX) { |
| 907 |
// HTTP2 hpack encoding has a maximum limit. |
| 908 |
return false; |
| 909 |
} else if (grpc_slice_str_cmp(md->key, "content-length") == 0) { |
| 910 |
// Filter "content-length metadata" |
| 911 |
continue; |
| 912 |
} |
| 913 |
batch->Append(StringViewFromSlice(md->key), Slice(CSliceRef(md->value)), |
| 914 |
[md](absl::string_view error, const Slice& value) { |
| 915 |
gpr_log(GPR_DEBUG, "Append error: %s", |
| 916 |
absl::StrCat("key=", StringViewFromSlice(md->key), |
| 917 |
" error=", error, |
| 918 |
" value=", value.as_string_view()) |
| 919 |
.c_str()); |
| 920 |
}); |
| 921 |
} |
| 922 |
|
| 923 |
return true; |
| 924 |
} |
| 925 |
|
| 926 |
namespace { |
| 927 |
class PublishToAppEncoder { |
| 928 |
public: |
| 929 |
explicit PublishToAppEncoder(grpc_metadata_array* dest) : dest_(dest) {} |
| 930 |
|
| 931 |
void Encode(const Slice& key, const Slice& value) { |
| 932 |
Append(key.c_slice(), value.c_slice()); |
| 933 |
} |
| 934 |
|
| 935 |
// Catch anything that is not explicitly handled, and do not publish it to the |
| 936 |
// application. If new metadata is added to a batch that needs to be |
| 937 |
// published, it should be called out here. |
| 938 |
template <typename Which> |
| 939 |
void Encode(Which, const typename Which::ValueType&) {} |
| 940 |
|
| 941 |
void Encode(UserAgentMetadata, const Slice& slice) { |
| 942 |
Append(UserAgentMetadata::key(), slice); |
| 943 |
} |
| 944 |
|
| 945 |
void Encode(HostMetadata, const Slice& slice) { |
| 946 |
Append(HostMetadata::key(), slice); |
| 947 |
} |
| 948 |
|
| 949 |
void Encode(GrpcPreviousRpcAttemptsMetadata, uint32_t count) { |
| 950 |
Append(GrpcPreviousRpcAttemptsMetadata::key(), count); |
| 951 |
} |
| 952 |
|
| 953 |
void Encode(GrpcRetryPushbackMsMetadata, Duration count) { |
| 954 |
Append(GrpcRetryPushbackMsMetadata::key(), count.millis()); |
| 955 |
} |
| 956 |
|
| 957 |
void Encode(LbTokenMetadata, const Slice& slice) { |
| 958 |
Append(LbTokenMetadata::key(), slice); |
| 959 |
} |
| 960 |
|
| 961 |
private: |
| 962 |
void Append(absl::string_view key, int64_t value) { |
| 963 |
Append(StaticSlice::FromStaticString(key).c_slice(), |
| 964 |
Slice::FromInt64(value).c_slice()); |
| 965 |
} |
| 966 |
|
| 967 |
void Append(absl::string_view key, const Slice& value) { |
| 968 |
Append(StaticSlice::FromStaticString(key).c_slice(), value.c_slice()); |
| 969 |
} |
| 970 |
|
| 971 |
void Append(grpc_slice key, grpc_slice value) { |
| 972 |
auto* mdusr = &dest_->metadata[dest_->count++]; |
| 973 |
mdusr->key = key; |
| 974 |
mdusr->value = value; |
| 975 |
} |
| 976 |
|
| 977 |
grpc_metadata_array* const dest_; |
| 978 |
}; |
| 979 |
} // namespace |
| 980 |
|
| 981 |
void FilterStackCall::PublishAppMetadata(grpc_metadata_batch* b, |
| 982 |
bool is_trailing) { |
| 983 |
if (b->count() == 0) return; |
| 984 |
if (!is_client() && is_trailing) return; |
| 985 |
if (is_trailing && buffered_metadata_[1] == nullptr) return; |
| 986 |
grpc_metadata_array* dest; |
| 987 |
dest = buffered_metadata_[is_trailing]; |
| 988 |
if (dest->count + b->count() > dest->capacity) { |
| 989 |
dest->capacity = |
| 990 |
std::max(dest->capacity + b->count(), dest->capacity * 3 / 2); |
| 991 |
dest->metadata = static_cast<grpc_metadata*>( |
| 992 |
gpr_realloc(dest->metadata, sizeof(grpc_metadata) * dest->capacity)); |
| 993 |
} |
| 994 |
PublishToAppEncoder encoder(dest); |
| 995 |
b->Encode(&encoder); |
| 996 |
} |
| 997 |
|
| 998 |
void FilterStackCall::RecvInitialFilter(grpc_metadata_batch* b) { |
| 999 |
incoming_compression_algorithm_ = |
| 1000 |
b->Take(GrpcEncodingMetadata()).value_or(GRPC_COMPRESS_NONE); |
| 1001 |
encodings_accepted_by_peer_ = |
| 1002 |
b->Take(GrpcAcceptEncodingMetadata()) |
| 1003 |
.value_or(CompressionAlgorithmSet{GRPC_COMPRESS_NONE}); |
| 1004 |
PublishAppMetadata(b, false); |
| 1005 |
} |
| 1006 |
|
| 1007 |
void FilterStackCall::RecvTrailingFilter(grpc_metadata_batch* b, |
| 1008 |
grpc_error_handle batch_error) { |
| 1009 |
if (!batch_error.ok()) { |
| 1010 |
SetFinalStatus(batch_error); |
| 1011 |
} else { |
| 1012 |
absl::optional<grpc_status_code> grpc_status = |
| 1013 |
b->Take(GrpcStatusMetadata()); |
| 1014 |
if (grpc_status.has_value()) { |
| 1015 |
grpc_status_code status_code = *grpc_status; |
| 1016 |
grpc_error_handle error; |
| 1017 |
if (status_code != GRPC_STATUS_OK) { |
| 1018 |
char* peer = GetPeer(); |
| 1019 |
error = grpc_error_set_int( |
| 1020 |
GRPC_ERROR_CREATE(absl::StrCat("Error received from peer ", peer)), |
| 1021 |
StatusIntProperty::kRpcStatus, static_cast<intptr_t>(status_code)); |
| 1022 |
gpr_free(peer); |
| 1023 |
} |
| 1024 |
auto grpc_message = b->Take(GrpcMessageMetadata()); |
| 1025 |
if (grpc_message.has_value()) { |
| 1026 |
error = grpc_error_set_str(error, StatusStrProperty::kGrpcMessage, |
| 1027 |
grpc_message->as_string_view()); |
| 1028 |
} else if (!error.ok()) { |
| 1029 |
error = grpc_error_set_str(error, StatusStrProperty::kGrpcMessage, ""); |
| 1030 |
} |
| 1031 |
SetFinalStatus(error); |
| 1032 |
} else if (!is_client()) { |
| 1033 |
SetFinalStatus(absl::OkStatus()); |
| 1034 |
} else { |
| 1035 |
gpr_log(GPR_DEBUG, |
| 1036 |
"Received trailing metadata with no error and no status"); |
| 1037 |
SetFinalStatus(grpc_error_set_int(GRPC_ERROR_CREATE("No status received"), |
| 1038 |
StatusIntProperty::kRpcStatus, |
| 1039 |
GRPC_STATUS_UNKNOWN)); |
| 1040 |
} |
| 1041 |
} |
| 1042 |
PublishAppMetadata(b, true); |
| 1043 |
} |
| 1044 |
|
| 1045 |
namespace { |
| 1046 |
bool AreWriteFlagsValid(uint32_t flags) { |
| 1047 |
/* check that only bits in GRPC_WRITE_(INTERNAL?)_USED_MASK are set */ |
| 1048 |
const uint32_t allowed_write_positions = |
| 1049 |
(GRPC_WRITE_USED_MASK | GRPC_WRITE_INTERNAL_USED_MASK); |
| 1050 |
const uint32_t invalid_positions = ~allowed_write_positions; |
| 1051 |
return !(flags & invalid_positions); |
| 1052 |
} |
| 1053 |
|
| 1054 |
bool AreInitialMetadataFlagsValid(uint32_t flags) { |
| 1055 |
/* check that only bits in GRPC_WRITE_(INTERNAL?)_USED_MASK are set */ |
| 1056 |
uint32_t invalid_positions = ~GRPC_INITIAL_METADATA_USED_MASK; |
| 1057 |
return !(flags & invalid_positions); |
| 1058 |
} |
| 1059 |
|
| 1060 |
size_t BatchSlotForOp(grpc_op_type type) { |
| 1061 |
switch (type) { |
| 1062 |
case GRPC_OP_SEND_INITIAL_METADATA: |
| 1063 |
return 0; |
| 1064 |
case GRPC_OP_SEND_MESSAGE: |
| 1065 |
return 1; |
| 1066 |
case GRPC_OP_SEND_CLOSE_FROM_CLIENT: |
| 1067 |
case GRPC_OP_SEND_STATUS_FROM_SERVER: |
| 1068 |
return 2; |
| 1069 |
case GRPC_OP_RECV_INITIAL_METADATA: |
| 1070 |
return 3; |
| 1071 |
case GRPC_OP_RECV_MESSAGE: |
| 1072 |
return 4; |
| 1073 |
case GRPC_OP_RECV_CLOSE_ON_SERVER: |
| 1074 |
case GRPC_OP_RECV_STATUS_ON_CLIENT: |
| 1075 |
return 5; |
| 1076 |
} |
| 1077 |
GPR_UNREACHABLE_CODE(return 123456789); |
| 1078 |
} |
| 1079 |
} // namespace |
| 1080 |
|
| 1081 |
FilterStackCall::BatchControl* FilterStackCall::ReuseOrAllocateBatchControl( |
| 1082 |
const grpc_op* ops) { |
| 1083 |
size_t slot_idx = BatchSlotForOp(ops[0].op); |
| 1084 |
BatchControl** pslot = &active_batches_[slot_idx]; |
| 1085 |
BatchControl* bctl; |
| 1086 |
if (*pslot != nullptr) { |
| 1087 |
bctl = *pslot; |
| 1088 |
if (bctl->call_ != nullptr) { |
| 1089 |
return nullptr; |
| 1090 |
} |
| 1091 |
bctl->~BatchControl(); |
| 1092 |
bctl->op_ = {}; |
| 1093 |
new (&bctl->batch_error_) AtomicError(); |
| 1094 |
} else { |
| 1095 |
bctl = arena()->New<BatchControl>(); |
| 1096 |
*pslot = bctl; |
| 1097 |
} |
| 1098 |
bctl->call_ = this; |
| 1099 |
bctl->op_.payload = &stream_op_payload_; |
| 1100 |
return bctl; |
| 1101 |
} |
| 1102 |
|
| 1103 |
void FilterStackCall::BatchControl::PostCompletion() { |
| 1104 |
FilterStackCall* call = call_; |
| 1105 |
grpc_error_handle error = batch_error_.get(); |
| 1106 |
|
| 1107 |
if (op_.send_initial_metadata) { |
| 1108 |
call->send_initial_metadata_.Clear(); |
| 1109 |
} |
| 1110 |
if (op_.send_message) { |
| 1111 |
if (op_.payload->send_message.stream_write_closed && error.ok()) { |
| 1112 |
error = grpc_error_add_child( |
| 1113 |
error, GRPC_ERROR_CREATE( |
| 1114 |
"Attempt to send message after stream was closed.")); |
| 1115 |
} |
| 1116 |
call->sending_message_ = false; |
| 1117 |
call->send_slice_buffer_.Clear(); |
| 1118 |
} |
| 1119 |
if (op_.send_trailing_metadata) { |
| 1120 |
call->send_trailing_metadata_.Clear(); |
| 1121 |
} |
| 1122 |
if (op_.recv_trailing_metadata) { |
| 1123 |
/* propagate cancellation to any interested children */ |
| 1124 |
gpr_atm_rel_store(&call->received_final_op_atm_, 1); |
| 1125 |
call->PropagateCancellationToChildren(); |
| 1126 |
error = absl::OkStatus(); |
| 1127 |
} |
| 1128 |
if (!error.ok() && op_.recv_message && *call->receiving_buffer_ != nullptr) { |
| 1129 |
grpc_byte_buffer_destroy(*call->receiving_buffer_); |
| 1130 |
*call->receiving_buffer_ = nullptr; |
| 1131 |
} |
| 1132 |
batch_error_.set(absl::OkStatus()); |
| 1133 |
|
| 1134 |
if (completion_data_.notify_tag.is_closure) { |
| 1135 |
/* unrefs error */ |
| 1136 |
call_ = nullptr; |
| 1137 |
Closure::Run(DEBUG_LOCATION, |
| 1138 |
static_cast<grpc_closure*>(completion_data_.notify_tag.tag), |
| 1139 |
error); |
| 1140 |
call->InternalUnref("completion"); |
| 1141 |
} else { |
| 1142 |
/* unrefs error */ |
| 1143 |
grpc_cq_end_op( |
| 1144 |
call->cq_, completion_data_.notify_tag.tag, error, |
| 1145 |
[](void* user_data, grpc_cq_completion* /*storage*/) { |
| 1146 |
BatchControl* bctl = static_cast<BatchControl*>(user_data); |
| 1147 |
Call* call = bctl->call_; |
| 1148 |
bctl->call_ = nullptr; |
| 1149 |
call->InternalUnref("completion"); |
| 1150 |
}, |
| 1151 |
this, &completion_data_.cq_completion); |
| 1152 |
} |
| 1153 |
} |
| 1154 |
|
| 1155 |
void FilterStackCall::BatchControl::FinishStep() { |
| 1156 |
if (GPR_UNLIKELY(completed_batch_step())) { |
| 1157 |
PostCompletion(); |
| 1158 |
} |
| 1159 |
} |
| 1160 |
|
| 1161 |
void FilterStackCall::BatchControl::ProcessDataAfterMetadata() { |
| 1162 |
FilterStackCall* call = call_; |
| 1163 |
if (!call->receiving_slice_buffer_.has_value()) { |
| 1164 |
*call->receiving_buffer_ = nullptr; |
| 1165 |
call->receiving_message_ = false; |
| 1166 |
FinishStep(); |
| 1167 |
} else { |
| 1168 |
call->test_only_last_message_flags_ = call->receiving_stream_flags_; |
| 1169 |
if ((call->receiving_stream_flags_ & GRPC_WRITE_INTERNAL_COMPRESS) && |
| 1170 |
(call->incoming_compression_algorithm_ != GRPC_COMPRESS_NONE)) { |
| 1171 |
*call->receiving_buffer_ = grpc_raw_compressed_byte_buffer_create( |
| 1172 |
nullptr, 0, call->incoming_compression_algorithm_); |
| 1173 |
} else { |
| 1174 |
*call->receiving_buffer_ = grpc_raw_byte_buffer_create(nullptr, 0); |
| 1175 |
} |
| 1176 |
grpc_slice_buffer_move_into( |
| 1177 |
call->receiving_slice_buffer_->c_slice_buffer(), |
| 1178 |
&(*call->receiving_buffer_)->data.raw.slice_buffer); |
| 1179 |
call->receiving_message_ = false; |
| 1180 |
call->receiving_slice_buffer_.reset(); |
| 1181 |
FinishStep(); |
| 1182 |
} |
| 1183 |
} |
| 1184 |
|
| 1185 |
void FilterStackCall::BatchControl::ReceivingStreamReady( |
| 1186 |
grpc_error_handle error) { |
| 1187 |
FilterStackCall* call = call_; |
| 1188 |
if (!error.ok()) { |
| 1189 |
call->receiving_slice_buffer_.reset(); |
| 1190 |
if (batch_error_.ok()) { |
| 1191 |
batch_error_.set(error); |
| 1192 |
} |
| 1193 |
call->CancelWithError(error); |
| 1194 |
} |
| 1195 |
/* If recv_state is kRecvNone, we will save the batch_control |
| 1196 |
* object with rel_cas, and will not use it after the cas. Its corresponding |
| 1197 |
* acq_load is in receiving_initial_metadata_ready() */ |
| 1198 |
if (!error.ok() || !call->receiving_slice_buffer_.has_value() || |
| 1199 |
!gpr_atm_rel_cas(&call->recv_state_, kRecvNone, |
| 1200 |
reinterpret_cast<gpr_atm>(this))) { |
| 1201 |
ProcessDataAfterMetadata(); |
| 1202 |
} |
| 1203 |
} |
| 1204 |
|
| 1205 |
void FilterStackCall::HandleCompressionAlgorithmDisabled( |
| 1206 |
grpc_compression_algorithm compression_algorithm) { |
| 1207 |
const char* algo_name = nullptr; |
| 1208 |
grpc_compression_algorithm_name(compression_algorithm, &algo_name); |
| 1209 |
std::string error_msg = |
| 1210 |
absl::StrFormat("Compression algorithm '%s' is disabled.", algo_name); |
| 1211 |
gpr_log(GPR_ERROR, "%s", error_msg.c_str()); |
| 1212 |
CancelWithStatus(GRPC_STATUS_UNIMPLEMENTED, error_msg.c_str()); |
| 1213 |
} |
| 1214 |
|
| 1215 |
void FilterStackCall::HandleCompressionAlgorithmNotAccepted( |
| 1216 |
grpc_compression_algorithm compression_algorithm) { |
| 1217 |
const char* algo_name = nullptr; |
| 1218 |
grpc_compression_algorithm_name(compression_algorithm, &algo_name); |
| 1219 |
gpr_log(GPR_ERROR, |
| 1220 |
"Compression algorithm ('%s') not present in the " |
| 1221 |
"accepted encodings (%s)", |
| 1222 |
algo_name, |
| 1223 |
std::string(encodings_accepted_by_peer_.ToString()).c_str()); |
| 1224 |
} |
| 1225 |
|
| 1226 |
void FilterStackCall::BatchControl::ValidateFilteredMetadata() { |
| 1227 |
FilterStackCall* call = call_; |
| 1228 |
|
| 1229 |
const grpc_compression_options compression_options = |
| 1230 |
call->channel()->compression_options(); |
| 1231 |
const grpc_compression_algorithm compression_algorithm = |
| 1232 |
call->incoming_compression_algorithm_; |
| 1233 |
if (GPR_UNLIKELY(!CompressionAlgorithmSet::FromUint32( |
| 1234 |
compression_options.enabled_algorithms_bitset) |
| 1235 |
.IsSet(compression_algorithm))) { |
| 1236 |
/* check if algorithm is supported by current channel config */ |
| 1237 |
call->HandleCompressionAlgorithmDisabled(compression_algorithm); |
| 1238 |
} |
| 1239 |
/* GRPC_COMPRESS_NONE is always set. */ |
| 1240 |
GPR_DEBUG_ASSERT(call->encodings_accepted_by_peer_.IsSet(GRPC_COMPRESS_NONE)); |
| 1241 |
if (GPR_UNLIKELY( |
| 1242 |
!call->encodings_accepted_by_peer_.IsSet(compression_algorithm))) { |
| 1243 |
if (GRPC_TRACE_FLAG_ENABLED(grpc_compression_trace)) { |
| 1244 |
call->HandleCompressionAlgorithmNotAccepted(compression_algorithm); |
| 1245 |
} |
| 1246 |
} |
| 1247 |
} |
| 1248 |
|
| 1249 |
void FilterStackCall::BatchControl::ReceivingInitialMetadataReady( |
| 1250 |
grpc_error_handle error) { |
| 1251 |
FilterStackCall* call = call_; |
| 1252 |
|
| 1253 |
GRPC_CALL_COMBINER_STOP(call->call_combiner(), "recv_initial_metadata_ready"); |
| 1254 |
|
| 1255 |
if (error.ok()) { |
| 1256 |
grpc_metadata_batch* md = &call->recv_initial_metadata_; |
| 1257 |
call->RecvInitialFilter(md); |
| 1258 |
|
| 1259 |
/* TODO(ctiller): this could be moved into recv_initial_filter now */ |
| 1260 |
ValidateFilteredMetadata(); |
| 1261 |
|
| 1262 |
absl::optional<Timestamp> deadline = md->get(GrpcTimeoutMetadata()); |
| 1263 |
if (deadline.has_value() && !call->is_client()) { |
| 1264 |
call_->set_send_deadline(*deadline); |
| 1265 |
} |
| 1266 |
} else { |
| 1267 |
if (batch_error_.ok()) { |
| 1268 |
batch_error_.set(error); |
| 1269 |
} |
| 1270 |
call->CancelWithError(error); |
| 1271 |
} |
| 1272 |
|
| 1273 |
grpc_closure* saved_rsr_closure = nullptr; |
| 1274 |
while (true) { |
| 1275 |
gpr_atm rsr_bctlp = gpr_atm_acq_load(&call->recv_state_); |
| 1276 |
/* Should only receive initial metadata once */ |
| 1277 |
GPR_ASSERT(rsr_bctlp != 1); |
| 1278 |
if (rsr_bctlp == 0) { |
| 1279 |
/* We haven't seen initial metadata and messages before, thus initial |
| 1280 |
* metadata is received first. |
| 1281 |
* no_barrier_cas is used, as this function won't access the batch_control |
| 1282 |
* object saved by receiving_stream_ready() if the initial metadata is |
| 1283 |
* received first. */ |
| 1284 |
if (gpr_atm_no_barrier_cas(&call->recv_state_, kRecvNone, |
| 1285 |
kRecvInitialMetadataFirst)) { |
| 1286 |
break; |
| 1287 |
} |
| 1288 |
} else { |
| 1289 |
/* Already received messages */ |
| 1290 |
saved_rsr_closure = GRPC_CLOSURE_CREATE( |
| 1291 |
[](void* bctl, grpc_error_handle error) { |
| 1292 |
static_cast<BatchControl*>(bctl)->ReceivingStreamReady(error); |
| 1293 |
}, |
| 1294 |
reinterpret_cast<BatchControl*>(rsr_bctlp), |
| 1295 |
grpc_schedule_on_exec_ctx); |
| 1296 |
/* No need to modify recv_state */ |
| 1297 |
break; |
| 1298 |
} |
| 1299 |
} |
| 1300 |
if (saved_rsr_closure != nullptr) { |
| 1301 |
Closure::Run(DEBUG_LOCATION, saved_rsr_closure, error); |
| 1302 |
} |
| 1303 |
|
| 1304 |
FinishStep(); |
| 1305 |
} |
| 1306 |
|
| 1307 |
void FilterStackCall::BatchControl::ReceivingTrailingMetadataReady( |
| 1308 |
grpc_error_handle error) { |
| 1309 |
GRPC_CALL_COMBINER_STOP(call_->call_combiner(), |
| 1310 |
"recv_trailing_metadata_ready"); |
| 1311 |
grpc_metadata_batch* md = &call_->recv_trailing_metadata_; |
| 1312 |
call_->RecvTrailingFilter(md, error); |
| 1313 |
FinishStep(); |
| 1314 |
} |
| 1315 |
|
| 1316 |
void FilterStackCall::BatchControl::FinishBatch(grpc_error_handle error) { |
| 1317 |
GRPC_CALL_COMBINER_STOP(call_->call_combiner(), "on_complete"); |
| 1318 |
if (batch_error_.ok()) { |
| 1319 |
batch_error_.set(error); |
| 1320 |
} |
| 1321 |
if (!error.ok()) { |
| 1322 |
call_->CancelWithError(error); |
| 1323 |
} |
| 1324 |
FinishStep(); |
| 1325 |
} |
| 1326 |
|
| 1327 |
namespace { |
| 1328 |
void EndOpImmediately(grpc_completion_queue* cq, void* notify_tag, |
| 1329 |
bool is_notify_tag_closure) { |
| 1330 |
if (!is_notify_tag_closure) { |
| 1331 |
GPR_ASSERT(grpc_cq_begin_op(cq, notify_tag)); |
| 1332 |
grpc_cq_end_op( |
| 1333 |
cq, notify_tag, absl::OkStatus(), |
| 1334 |
[](void*, grpc_cq_completion* completion) { gpr_free(completion); }, |
| 1335 |
nullptr, |
| 1336 |
static_cast<grpc_cq_completion*>( |
| 1337 |
gpr_malloc(sizeof(grpc_cq_completion)))); |
| 1338 |
} else { |
| 1339 |
Closure::Run(DEBUG_LOCATION, static_cast<grpc_closure*>(notify_tag), |
| 1340 |
absl::OkStatus()); |
| 1341 |
} |
| 1342 |
} |
| 1343 |
} // namespace |
| 1344 |
|
| 1345 |
grpc_call_error FilterStackCall::StartBatch(const grpc_op* ops, size_t nops, |
| 1346 |
void* notify_tag, |
| 1347 |
bool is_notify_tag_closure) { |
| 1348 |
size_t i; |
| 1349 |
const grpc_op* op; |
| 1350 |
BatchControl* bctl; |
| 1351 |
bool has_send_ops = false; |
| 1352 |
int num_recv_ops = 0; |
| 1353 |
grpc_call_error error = GRPC_CALL_OK; |
| 1354 |
grpc_transport_stream_op_batch* stream_op; |
| 1355 |
grpc_transport_stream_op_batch_payload* stream_op_payload; |
| 1356 |
uint32_t seen_ops = 0; |
| 1357 |
|
| 1358 |
for (i = 0; i < nops; i++) { |
| 1359 |
if (seen_ops & (1u << ops[i].op)) { |
| 1360 |
return GRPC_CALL_ERROR_TOO_MANY_OPERATIONS; |
| 1361 |
} |
| 1362 |
seen_ops |= (1u << ops[i].op); |
| 1363 |
} |
| 1364 |
|
| 1365 |
GRPC_CALL_LOG_BATCH(GPR_INFO, ops, nops); |
| 1366 |
|
| 1367 |
if (nops == 0) { |
| 1368 |
EndOpImmediately(cq_, notify_tag, is_notify_tag_closure); |
| 1369 |
error = GRPC_CALL_OK; |
| 1370 |
goto done; |
| 1371 |
} |
| 1372 |
|
| 1373 |
bctl = ReuseOrAllocateBatchControl(ops); |
| 1374 |
if (bctl == nullptr) { |
| 1375 |
return GRPC_CALL_ERROR_TOO_MANY_OPERATIONS; |
| 1376 |
} |
| 1377 |
bctl->completion_data_.notify_tag.tag = notify_tag; |
| 1378 |
bctl->completion_data_.notify_tag.is_closure = |
| 1379 |
static_cast<uint8_t>(is_notify_tag_closure != 0); |
| 1380 |
|
| 1381 |
stream_op = &bctl->op_; |
| 1382 |
stream_op_payload = &stream_op_payload_; |
| 1383 |
|
| 1384 |
/* rewrite batch ops into a transport op */ |
| 1385 |
for (i = 0; i < nops; i++) { |
| 1386 |
op = &ops[i]; |
| 1387 |
if (op->reserved != nullptr) { |
| 1388 |
error = GRPC_CALL_ERROR; |
| 1389 |
goto done_with_error; |
| 1390 |
} |
| 1391 |
switch (op->op) { |
| 1392 |
case GRPC_OP_SEND_INITIAL_METADATA: { |
| 1393 |
/* Flag validation: currently allow no flags */ |
| 1394 |
if (!AreInitialMetadataFlagsValid(op->flags)) { |
| 1395 |
error = GRPC_CALL_ERROR_INVALID_FLAGS; |
| 1396 |
goto done_with_error; |
| 1397 |
} |
| 1398 |
if (sent_initial_metadata_) { |
| 1399 |
error = GRPC_CALL_ERROR_TOO_MANY_OPERATIONS; |
| 1400 |
goto done_with_error; |
| 1401 |
} |
| 1402 |
// TODO(juanlishen): If the user has already specified a compression |
| 1403 |
// algorithm by setting the initial metadata with key of |
| 1404 |
// GRPC_COMPRESSION_REQUEST_ALGORITHM_MD_KEY, we shouldn't override that |
| 1405 |
// with the compression algorithm mapped from compression level. |
| 1406 |
/* process compression level */ |
| 1407 |
grpc_compression_level effective_compression_level = |
| 1408 |
GRPC_COMPRESS_LEVEL_NONE; |
| 1409 |
bool level_set = false; |
| 1410 |
if (op->data.send_initial_metadata.maybe_compression_level.is_set) { |
| 1411 |
effective_compression_level = |
| 1412 |
op->data.send_initial_metadata.maybe_compression_level.level; |
| 1413 |
level_set = true; |
| 1414 |
} else { |
| 1415 |
const grpc_compression_options copts = |
| 1416 |
channel()->compression_options(); |
| 1417 |
if (copts.default_level.is_set) { |
| 1418 |
level_set = true; |
| 1419 |
effective_compression_level = copts.default_level.level; |
| 1420 |
} |
| 1421 |
} |
| 1422 |
// Currently, only server side supports compression level setting. |
| 1423 |
if (level_set && !is_client()) { |
| 1424 |
const grpc_compression_algorithm calgo = |
| 1425 |
encodings_accepted_by_peer_.CompressionAlgorithmForLevel( |
| 1426 |
effective_compression_level); |
| 1427 |
// The following metadata will be checked and removed by the message |
| 1428 |
// compression filter. It will be used as the call's compression |
| 1429 |
// algorithm. |
| 1430 |
send_initial_metadata_.Set(GrpcInternalEncodingRequest(), calgo); |
| 1431 |
} |
| 1432 |
if (op->data.send_initial_metadata.count > INT_MAX) { |
| 1433 |
error = GRPC_CALL_ERROR_INVALID_METADATA; |
| 1434 |
goto done_with_error; |
| 1435 |
} |
| 1436 |
stream_op->send_initial_metadata = true; |
| 1437 |
sent_initial_metadata_ = true; |
| 1438 |
if (!PrepareApplicationMetadata(op->data.send_initial_metadata.count, |
| 1439 |
op->data.send_initial_metadata.metadata, |
| 1440 |
false)) { |
| 1441 |
error = GRPC_CALL_ERROR_INVALID_METADATA; |
| 1442 |
goto done_with_error; |
| 1443 |
} |
| 1444 |
// Ignore any te metadata key value pairs specified. |
| 1445 |
send_initial_metadata_.Remove(TeMetadata()); |
| 1446 |
/* TODO(ctiller): just make these the same variable? */ |
| 1447 |
if (is_client() && send_deadline() != Timestamp::InfFuture()) { |
| 1448 |
send_initial_metadata_.Set(GrpcTimeoutMetadata(), send_deadline()); |
| 1449 |
} |
| 1450 |
if (is_client()) { |
| 1451 |
send_initial_metadata_.Set( |
| 1452 |
WaitForReady(), |
| 1453 |
WaitForReady::ValueType{ |
| 1454 |
(op->flags & GRPC_INITIAL_METADATA_WAIT_FOR_READY) != 0, |
| 1455 |
(op->flags & |
| 1456 |
GRPC_INITIAL_METADATA_WAIT_FOR_READY_EXPLICITLY_SET) != 0}); |
| 1457 |
} |
| 1458 |
stream_op_payload->send_initial_metadata.send_initial_metadata = |
| 1459 |
&send_initial_metadata_; |
| 1460 |
if (is_client()) { |
| 1461 |
stream_op_payload->send_initial_metadata.peer_string = |
| 1462 |
peer_string_atm_ptr(); |
| 1463 |
} |
| 1464 |
has_send_ops = true; |
| 1465 |
break; |
| 1466 |
} |
| 1467 |
case GRPC_OP_SEND_MESSAGE: { |
| 1468 |
if (!AreWriteFlagsValid(op->flags)) { |
| 1469 |
error = GRPC_CALL_ERROR_INVALID_FLAGS; |
| 1470 |
goto done_with_error; |
| 1471 |
} |
| 1472 |
if (op->data.send_message.send_message == nullptr) { |
| 1473 |
error = GRPC_CALL_ERROR_INVALID_MESSAGE; |
| 1474 |
goto done_with_error; |
| 1475 |
} |
| 1476 |
if (sending_message_) { |
| 1477 |
error = GRPC_CALL_ERROR_TOO_MANY_OPERATIONS; |
| 1478 |
goto done_with_error; |
| 1479 |
} |
| 1480 |
uint32_t flags = op->flags; |
| 1481 |
/* If the outgoing buffer is already compressed, mark it as so in the |
| 1482 |
flags. These will be picked up by the compression filter and further |
| 1483 |
(wasteful) attempts at compression skipped. */ |
| 1484 |
if (op->data.send_message.send_message->data.raw.compression > |
| 1485 |
GRPC_COMPRESS_NONE) { |
| 1486 |
flags |= GRPC_WRITE_INTERNAL_COMPRESS; |
| 1487 |
} |
| 1488 |
stream_op->send_message = true; |
| 1489 |
sending_message_ = true; |
| 1490 |
send_slice_buffer_.Clear(); |
| 1491 |
grpc_slice_buffer_move_into( |
| 1492 |
&op->data.send_message.send_message->data.raw.slice_buffer, |
| 1493 |
send_slice_buffer_.c_slice_buffer()); |
| 1494 |
stream_op_payload->send_message.flags = flags; |
| 1495 |
stream_op_payload->send_message.send_message = &send_slice_buffer_; |
| 1496 |
has_send_ops = true; |
| 1497 |
break; |
| 1498 |
} |
| 1499 |
case GRPC_OP_SEND_CLOSE_FROM_CLIENT: { |
| 1500 |
/* Flag validation: currently allow no flags */ |
| 1501 |
if (op->flags != 0) { |
| 1502 |
error = GRPC_CALL_ERROR_INVALID_FLAGS; |
| 1503 |
goto done_with_error; |
| 1504 |
} |
| 1505 |
if (!is_client()) { |
| 1506 |
error = GRPC_CALL_ERROR_NOT_ON_SERVER; |
| 1507 |
goto done_with_error; |
| 1508 |
} |
| 1509 |
if (sent_final_op_) { |
| 1510 |
error = GRPC_CALL_ERROR_TOO_MANY_OPERATIONS; |
| 1511 |
goto done_with_error; |
| 1512 |
} |
| 1513 |
stream_op->send_trailing_metadata = true; |
| 1514 |
sent_final_op_ = true; |
| 1515 |
stream_op_payload->send_trailing_metadata.send_trailing_metadata = |
| 1516 |
&send_trailing_metadata_; |
| 1517 |
has_send_ops = true; |
| 1518 |
break; |
| 1519 |
} |
| 1520 |
case GRPC_OP_SEND_STATUS_FROM_SERVER: { |
| 1521 |
/* Flag validation: currently allow no flags */ |
| 1522 |
if (op->flags != 0) { |
| 1523 |
error = GRPC_CALL_ERROR_INVALID_FLAGS; |
| 1524 |
goto done_with_error; |
| 1525 |
} |
| 1526 |
if (is_client()) { |
| 1527 |
error = GRPC_CALL_ERROR_NOT_ON_CLIENT; |
| 1528 |
goto done_with_error; |
| 1529 |
} |
| 1530 |
if (sent_final_op_) { |
| 1531 |
error = GRPC_CALL_ERROR_TOO_MANY_OPERATIONS; |
| 1532 |
goto done_with_error; |
| 1533 |
} |
| 1534 |
if (op->data.send_status_from_server.trailing_metadata_count > |
| 1535 |
INT_MAX) { |
| 1536 |
error = GRPC_CALL_ERROR_INVALID_METADATA; |
| 1537 |
goto done_with_error; |
| 1538 |
} |
| 1539 |
stream_op->send_trailing_metadata = true; |
| 1540 |
sent_final_op_ = true; |
| 1541 |
|
| 1542 |
if (!PrepareApplicationMetadata( |
| 1543 |
op->data.send_status_from_server.trailing_metadata_count, |
| 1544 |
op->data.send_status_from_server.trailing_metadata, true)) { |
| 1545 |
error = GRPC_CALL_ERROR_INVALID_METADATA; |
| 1546 |
goto done_with_error; |
| 1547 |
} |
| 1548 |
|
| 1549 |
grpc_error_handle status_error = |
| 1550 |
op->data.send_status_from_server.status == GRPC_STATUS_OK |
| 1551 |
? absl::OkStatus() |
| 1552 |
: grpc_error_set_int( |
| 1553 |
GRPC_ERROR_CREATE("Server returned error"), |
| 1554 |
StatusIntProperty::kRpcStatus, |
| 1555 |
static_cast<intptr_t>( |
| 1556 |
op->data.send_status_from_server.status)); |
| 1557 |
if (op->data.send_status_from_server.status_details != nullptr) { |
| 1558 |
send_trailing_metadata_.Set( |
| 1559 |
GrpcMessageMetadata(), |
| 1560 |
Slice(grpc_slice_copy( |
| 1561 |
*op->data.send_status_from_server.status_details))); |
| 1562 |
if (!status_error.ok()) { |
| 1563 |
status_error = grpc_error_set_str( |
| 1564 |
status_error, StatusStrProperty::kGrpcMessage, |
| 1565 |
StringViewFromSlice( |
| 1566 |
*op->data.send_status_from_server.status_details)); |
| 1567 |
} |
| 1568 |
} |
| 1569 |
|
| 1570 |
status_error_.set(status_error); |
| 1571 |
|
| 1572 |
send_trailing_metadata_.Set(GrpcStatusMetadata(), |
| 1573 |
op->data.send_status_from_server.status); |
| 1574 |
|
| 1575 |
// Ignore any te metadata key value pairs specified. |
| 1576 |
send_trailing_metadata_.Remove(TeMetadata()); |
| 1577 |
stream_op_payload->send_trailing_metadata.send_trailing_metadata = |
| 1578 |
&send_trailing_metadata_; |
| 1579 |
stream_op_payload->send_trailing_metadata.sent = |
| 1580 |
&sent_server_trailing_metadata_; |
| 1581 |
has_send_ops = true; |
| 1582 |
break; |
| 1583 |
} |
| 1584 |
case GRPC_OP_RECV_INITIAL_METADATA: { |
| 1585 |
/* Flag validation: currently allow no flags */ |
| 1586 |
if (op->flags != 0) { |
| 1587 |
error = GRPC_CALL_ERROR_INVALID_FLAGS; |
| 1588 |
goto done_with_error; |
| 1589 |
} |
| 1590 |
if (received_initial_metadata_) { |
| 1591 |
error = GRPC_CALL_ERROR_TOO_MANY_OPERATIONS; |
| 1592 |
goto done_with_error; |
| 1593 |
} |
| 1594 |
received_initial_metadata_ = true; |
| 1595 |
buffered_metadata_[0] = |
| 1596 |
op->data.recv_initial_metadata.recv_initial_metadata; |
| 1597 |
GRPC_CLOSURE_INIT( |
| 1598 |
&receiving_initial_metadata_ready_, |
| 1599 |
[](void* bctl, grpc_error_handle error) { |
| 1600 |
static_cast<BatchControl*>(bctl)->ReceivingInitialMetadataReady( |
| 1601 |
error); |
| 1602 |
}, |
| 1603 |
bctl, grpc_schedule_on_exec_ctx); |
| 1604 |
stream_op->recv_initial_metadata = true; |
| 1605 |
stream_op_payload->recv_initial_metadata.recv_initial_metadata = |
| 1606 |
&recv_initial_metadata_; |
| 1607 |
stream_op_payload->recv_initial_metadata.recv_initial_metadata_ready = |
| 1608 |
&receiving_initial_metadata_ready_; |
| 1609 |
if (is_client()) { |
| 1610 |
stream_op_payload->recv_initial_metadata.trailing_metadata_available = |
| 1611 |
&is_trailers_only_; |
| 1612 |
} else { |
| 1613 |
stream_op_payload->recv_initial_metadata.peer_string = |
| 1614 |
peer_string_atm_ptr(); |
| 1615 |
} |
| 1616 |
++num_recv_ops; |
| 1617 |
break; |
| 1618 |
} |
| 1619 |
case GRPC_OP_RECV_MESSAGE: { |
| 1620 |
/* Flag validation: currently allow no flags */ |
| 1621 |
if (op->flags != 0) { |
| 1622 |
error = GRPC_CALL_ERROR_INVALID_FLAGS; |
| 1623 |
goto done_with_error; |
| 1624 |
} |
| 1625 |
if (receiving_message_) { |
| 1626 |
error = GRPC_CALL_ERROR_TOO_MANY_OPERATIONS; |
| 1627 |
goto done_with_error; |
| 1628 |
} |
| 1629 |
receiving_message_ = true; |
| 1630 |
stream_op->recv_message = true; |
| 1631 |
receiving_slice_buffer_.reset(); |
| 1632 |
receiving_buffer_ = op->data.recv_message.recv_message; |
| 1633 |
stream_op_payload->recv_message.recv_message = &receiving_slice_buffer_; |
| 1634 |
receiving_stream_flags_ = 0; |
| 1635 |
stream_op_payload->recv_message.flags = &receiving_stream_flags_; |
| 1636 |
stream_op_payload->recv_message.call_failed_before_recv_message = |
| 1637 |
&call_failed_before_recv_message_; |
| 1638 |
GRPC_CLOSURE_INIT( |
| 1639 |
&receiving_stream_ready_, |
| 1640 |
[](void* bctlp, grpc_error_handle error) { |
| 1641 |
auto* bctl = static_cast<BatchControl*>(bctlp); |
| 1642 |
auto* call = bctl->call_; |
| 1643 |
// Yields the call combiner before processing the received |
| 1644 |
// message. |
| 1645 |
GRPC_CALL_COMBINER_STOP(call->call_combiner(), |
| 1646 |
"recv_message_ready"); |
| 1647 |
bctl->ReceivingStreamReady(error); |
| 1648 |
}, |
| 1649 |
bctl, grpc_schedule_on_exec_ctx); |
| 1650 |
stream_op_payload->recv_message.recv_message_ready = |
| 1651 |
&receiving_stream_ready_; |
| 1652 |
++num_recv_ops; |
| 1653 |
break; |
| 1654 |
} |
| 1655 |
case GRPC_OP_RECV_STATUS_ON_CLIENT: { |
| 1656 |
/* Flag validation: currently allow no flags */ |
| 1657 |
if (op->flags != 0) { |
| 1658 |
error = GRPC_CALL_ERROR_INVALID_FLAGS; |
| 1659 |
goto done_with_error; |
| 1660 |
} |
| 1661 |
if (!is_client()) { |
| 1662 |
error = GRPC_CALL_ERROR_NOT_ON_SERVER; |
| 1663 |
goto done_with_error; |
| 1664 |
} |
| 1665 |
if (requested_final_op_) { |
| 1666 |
error = GRPC_CALL_ERROR_TOO_MANY_OPERATIONS; |
| 1667 |
goto done_with_error; |
| 1668 |
} |
| 1669 |
requested_final_op_ = true; |
| 1670 |
buffered_metadata_[1] = |
| 1671 |
op->data.recv_status_on_client.trailing_metadata; |
| 1672 |
final_op_.client.status = op->data.recv_status_on_client.status; |
| 1673 |
final_op_.client.status_details = |
| 1674 |
op->data.recv_status_on_client.status_details; |
| 1675 |
final_op_.client.error_string = |
| 1676 |
op->data.recv_status_on_client.error_string; |
| 1677 |
stream_op->recv_trailing_metadata = true; |
| 1678 |
stream_op_payload->recv_trailing_metadata.recv_trailing_metadata = |
| 1679 |
&recv_trailing_metadata_; |
| 1680 |
stream_op_payload->recv_trailing_metadata.collect_stats = |
| 1681 |
&final_info_.stats.transport_stream_stats; |
| 1682 |
GRPC_CLOSURE_INIT( |
| 1683 |
&receiving_trailing_metadata_ready_, |
| 1684 |
[](void* bctl, grpc_error_handle error) { |
| 1685 |
static_cast<BatchControl*>(bctl)->ReceivingTrailingMetadataReady( |
| 1686 |
error); |
| 1687 |
}, |
| 1688 |
bctl, grpc_schedule_on_exec_ctx); |
| 1689 |
stream_op_payload->recv_trailing_metadata.recv_trailing_metadata_ready = |
| 1690 |
&receiving_trailing_metadata_ready_; |
| 1691 |
++num_recv_ops; |
| 1692 |
break; |
| 1693 |
} |
| 1694 |
case GRPC_OP_RECV_CLOSE_ON_SERVER: { |
| 1695 |
/* Flag validation: currently allow no flags */ |
| 1696 |
if (op->flags != 0) { |
| 1697 |
error = GRPC_CALL_ERROR_INVALID_FLAGS; |
| 1698 |
goto done_with_error; |
| 1699 |
} |
| 1700 |
if (is_client()) { |
| 1701 |
error = GRPC_CALL_ERROR_NOT_ON_CLIENT; |
| 1702 |
goto done_with_error; |
| 1703 |
} |
| 1704 |
if (requested_final_op_) { |
| 1705 |
error = GRPC_CALL_ERROR_TOO_MANY_OPERATIONS; |
| 1706 |
goto done_with_error; |
| 1707 |
} |
| 1708 |
requested_final_op_ = true; |
| 1709 |
final_op_.server.cancelled = op->data.recv_close_on_server.cancelled; |
| 1710 |
stream_op->recv_trailing_metadata = true; |
| 1711 |
stream_op_payload->recv_trailing_metadata.recv_trailing_metadata = |
| 1712 |
&recv_trailing_metadata_; |
| 1713 |
stream_op_payload->recv_trailing_metadata.collect_stats = |
| 1714 |
&final_info_.stats.transport_stream_stats; |
| 1715 |
GRPC_CLOSURE_INIT( |
| 1716 |
&receiving_trailing_metadata_ready_, |
| 1717 |
[](void* bctl, grpc_error_handle error) { |
| 1718 |
static_cast<BatchControl*>(bctl)->ReceivingTrailingMetadataReady( |
| 1719 |
error); |
| 1720 |
}, |
| 1721 |
bctl, grpc_schedule_on_exec_ctx); |
| 1722 |
stream_op_payload->recv_trailing_metadata.recv_trailing_metadata_ready = |
| 1723 |
&receiving_trailing_metadata_ready_; |
| 1724 |
++num_recv_ops; |
| 1725 |
break; |
| 1726 |
} |
| 1727 |
} |
| 1728 |
} |
| 1729 |
|
| 1730 |
InternalRef("completion"); |
| 1731 |
if (!is_notify_tag_closure) { |
| 1732 |
GPR_ASSERT(grpc_cq_begin_op(cq_, notify_tag)); |
| 1733 |
} |
| 1734 |
bctl->set_num_steps_to_complete((has_send_ops ? 1 : 0) + num_recv_ops); |
| 1735 |
|
| 1736 |
if (has_send_ops) { |
| 1737 |
GRPC_CLOSURE_INIT( |
| 1738 |
&bctl->finish_batch_, |
| 1739 |
[](void* bctl, grpc_error_handle error) { |
| 1740 |
static_cast<BatchControl*>(bctl)->FinishBatch(error); |
| 1741 |
}, |
| 1742 |
bctl, grpc_schedule_on_exec_ctx); |
| 1743 |
stream_op->on_complete = &bctl->finish_batch_; |
| 1744 |
} |
| 1745 |
|
| 1746 |
ExecuteBatch(stream_op, &bctl->start_batch_); |
| 1747 |
|
| 1748 |
done: |
| 1749 |
return error; |
| 1750 |
|
| 1751 |
done_with_error: |
| 1752 |
/* reverse any mutations that occurred */ |
| 1753 |
if (stream_op->send_initial_metadata) { |
| 1754 |
sent_initial_metadata_ = false; |
| 1755 |
send_initial_metadata_.Clear(); |
| 1756 |
} |
| 1757 |
if (stream_op->send_message) { |
| 1758 |
sending_message_ = false; |
| 1759 |
} |
| 1760 |
if (stream_op->send_trailing_metadata) { |
| 1761 |
sent_final_op_ = false; |
| 1762 |
send_trailing_metadata_.Clear(); |
| 1763 |
} |
| 1764 |
if (stream_op->recv_initial_metadata) { |
| 1765 |
received_initial_metadata_ = false; |
| 1766 |
} |
| 1767 |
if (stream_op->recv_message) { |
| 1768 |
receiving_message_ = false; |
| 1769 |
} |
| 1770 |
if (stream_op->recv_trailing_metadata) { |
| 1771 |
requested_final_op_ = false; |
| 1772 |
} |
| 1773 |
goto done; |
| 1774 |
} |
| 1775 |
|
| 1776 |
void FilterStackCall::ContextSet(grpc_context_index elem, void* value, |
| 1777 |
void (*destroy)(void*)) { |
| 1778 |
if (context_[elem].destroy) { |
| 1779 |
context_[elem].destroy(context_[elem].value); |
| 1780 |
} |
| 1781 |
context_[elem].value = value; |
| 1782 |
context_[elem].destroy = destroy; |
| 1783 |
} |
| 1784 |
|
| 1785 |
/////////////////////////////////////////////////////////////////////////////// |
| 1786 |
// Metadata validation helpers |
| 1787 |
|
| 1788 |
namespace { |
| 1789 |
bool ValidateMetadata(size_t count, grpc_metadata* metadata) { |
| 1790 |
for (size_t i = 0; i < count; i++) { |
| 1791 |
grpc_metadata* md = &metadata[i]; |
| 1792 |
if (!GRPC_LOG_IF_ERROR("validate_metadata", |
| 1793 |
grpc_validate_header_key_is_legal(md->key))) { |
| 1794 |
return false; |
| 1795 |
} else if (!grpc_is_binary_header_internal(md->key) && |
| 1796 |
!GRPC_LOG_IF_ERROR( |
| 1797 |
"validate_metadata", |
| 1798 |
grpc_validate_header_nonbin_value_is_legal(md->value))) { |
| 1799 |
return false; |
| 1800 |
} else if (GRPC_SLICE_LENGTH(md->value) >= UINT32_MAX) { |
| 1801 |
// HTTP2 hpack encoding has a maximum limit. |
| 1802 |
return false; |
| 1803 |
} |
| 1804 |
} |
| 1805 |
return true; |
| 1806 |
} |
| 1807 |
} // namespace |
| 1808 |
|
| 1809 |
/////////////////////////////////////////////////////////////////////////////// |
| 1810 |
// PromiseBasedCall |
| 1811 |
// Will be folded into Call once the promise conversion is done |
| 1812 |
|
| 1813 |
class PromiseBasedCall : public Call, public Activity, public Wakeable { |
| 1814 |
public: |
| 1815 |
PromiseBasedCall(Arena* arena, const grpc_call_create_args& args); |
| 1816 |
|
| 1817 |
void ContextSet(grpc_context_index elem, void* value, |
| 1818 |
void (*destroy)(void* value)) override; |
| 1819 |
void* ContextGet(grpc_context_index elem) const override; |
| 1820 |
void SetCompletionQueue(grpc_completion_queue* cq) override; |
| 1821 |
|
| 1822 |
// Implementation of call refcounting: move this to DualRefCounted once we |
| 1823 |
// don't need to maintain FilterStackCall compatibility |
| 1824 |
void ExternalRef() final { |
| 1825 |
refs_.fetch_add(MakeRefPair(1, 0), std::memory_order_relaxed); |
| 1826 |
} |
| 1827 |
void ExternalUnref() final { |
| 1828 |
const uint64_t prev_ref_pair = |
| 1829 |
refs_.fetch_add(MakeRefPair(-1, 1), std::memory_order_acq_rel); |
| 1830 |
const uint32_t strong_refs = GetStrongRefs(prev_ref_pair); |
| 1831 |
if (GPR_UNLIKELY(strong_refs == 1)) { |
| 1832 |
Orphan(); |
| 1833 |
} |
| 1834 |
// Now drop the weak ref. |
| 1835 |
InternalUnref("external_ref"); |
| 1836 |
} |
| 1837 |
void InternalRef(const char*) final { |
| 1838 |
refs_.fetch_add(MakeRefPair(0, 1), std::memory_order_relaxed); |
| 1839 |
} |
| 1840 |
void InternalUnref(const char*) final { |
| 1841 |
const uint64_t prev_ref_pair = |
| 1842 |
refs_.fetch_sub(MakeRefPair(0, 1), std::memory_order_acq_rel); |
| 1843 |
if (GPR_UNLIKELY(prev_ref_pair == MakeRefPair(0, 1))) { |
| 1844 |
DeleteThis(); |
| 1845 |
} |
| 1846 |
} |
| 1847 |
|
| 1848 |
// Activity methods |
| 1849 |
void ForceImmediateRepoll() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_) override; |
| 1850 |
Waker MakeOwningWaker() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_) override { |
| 1851 |
InternalRef("wakeup"); |
| 1852 |
// If ASAN is defined, we leverage it to detect dropped Waker objects. |
| 1853 |
// Usually Waker must be destroyed or woken up, but (especially with arenas) |
| 1854 |
// it's not uncommon to create a Waker and then do neither. In that case it's |
| 1855 |
// incredibly fraught to diagnose where the dropped reference to this object was |
| 1856 |
// created. Instead, leverage ASAN and create a new object per expected wakeup. |
| 1857 |
// Now when we drop such an object ASAN will fail and we'll get a callstack to |
| 1858 |
// the creation of the waker in question. |
| 1859 |
#if defined(__has_feature) |
| 1860 |
#if __has_feature(address_sanitizer) |
| 1861 |
#define GRPC_CALL_USES_ASAN_WAKER |
| 1862 |
class AsanWaker final : public Wakeable { |
| 1863 |
public: |
| 1864 |
explicit AsanWaker(PromiseBasedCall* call) : call_(call) {} |
| 1865 |
|
| 1866 |
void Wakeup() override { |
| 1867 |
call_->Wakeup(); |
| 1868 |
delete this; |
| 1869 |
} |
| 1870 |
|
| 1871 |
void Drop() override { |
| 1872 |
call_->Drop(); |
| 1873 |
delete this; |
| 1874 |
} |
| 1875 |
|
| 1876 |
std::string ActivityDebugTag() const override { |
| 1877 |
return call_->DebugTag(); |
| 1878 |
} |
| 1879 |
|
| 1880 |
private: |
| 1881 |
PromiseBasedCall* call_; |
| 1882 |
}; |
| 1883 |
return Waker(new AsanWaker(this)); |
| 1884 |
#endif |
| 1885 |
#endif |
| 1886 |
#ifndef GRPC_CALL_USES_ASAN_WAKER |
| 1887 |
return Waker(this); |
| 1888 |
#endif |
| 1889 |
} |
| 1890 |
Waker MakeNonOwningWaker() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_) override; |
| 1891 |
|
| 1892 |
// Wakeable methods |
| 1893 |
void Wakeup() override { |
| 1894 |
channel()->event_engine()->Run([this] { |
| 1895 |
ApplicationCallbackExecCtx app_exec_ctx; |
| 1896 |
ExecCtx exec_ctx; |
| 1897 |
{ |
| 1898 |
ScopedContext activity_context(this); |
| 1899 |
MutexLock lock(&mu_); |
| 1900 |
Update(); |
| 1901 |
} |
| 1902 |
InternalUnref("wakeup"); |
| 1903 |
}); |
| 1904 |
} |
| 1905 |
void Drop() override { InternalUnref("wakeup"); } |
| 1906 |
|
| 1907 |
void RunInContext(absl::AnyInvocable<void()> fn) { |
| 1908 |
if (Activity::current() == this) { |
| 1909 |
fn(); |
| 1910 |
} else { |
| 1911 |
InternalRef("in_context"); |
| 1912 |
channel()->event_engine()->Run([this, fn = std::move(fn)]() mutable { |
| 1913 |
ApplicationCallbackExecCtx app_exec_ctx; |
| 1914 |
ExecCtx exec_ctx; |
| 1915 |
{ |
| 1916 |
ScopedContext activity_context(this); |
| 1917 |
MutexLock lock(&mu_); |
| 1918 |
fn(); |
| 1919 |
Update(); |
| 1920 |
} |
| 1921 |
InternalUnref("in_context"); |
| 1922 |
}); |
| 1923 |
} |
| 1924 |
} |
| 1925 |
|
| 1926 |
grpc_compression_algorithm test_only_compression_algorithm() override { |
| 1927 |
abort(); |
| 1928 |
} |
| 1929 |
uint32_t test_only_message_flags() override { abort(); } |
| 1930 |
uint32_t test_only_encodings_accepted_by_peer() override { abort(); } |
| 1931 |
grpc_compression_algorithm compression_for_level( |
| 1932 |
grpc_compression_level) override { |
| 1933 |
abort(); |
| 1934 |
} |
| 1935 |
|
| 1936 |
// This should return nullptr for the promise stack (and alternative means |
| 1937 |
// for that functionality be invented) |
| 1938 |
grpc_call_stack* call_stack() override { return nullptr; } |
| 1939 |
|
| 1940 |
protected: |
| 1941 |
class ScopedContext |
| 1942 |
: public ScopedActivity, |
| 1943 |
public promise_detail::Context<Arena>, |
| 1944 |
public promise_detail::Context<grpc_call_context_element>, |
| 1945 |
public promise_detail::Context<CallContext>, |
| 1946 |
public promise_detail::Context<CallFinalization> { |
| 1947 |
public: |
| 1948 |
explicit ScopedContext(PromiseBasedCall* call) |
| 1949 |
: ScopedActivity(call), |
| 1950 |
promise_detail::Context<Arena>(call->arena()), |
| 1951 |
promise_detail::Context<grpc_call_context_element>(call->context_), |
| 1952 |
promise_detail::Context<CallContext>(&call->call_context_), |
| 1953 |
promise_detail::Context<CallFinalization>(&call->finalization_) {} |
| 1954 |
}; |
| 1955 |
|
| 1956 |
class Completion { |
| 1957 |
public: |
| 1958 |
Completion() : index_(kNullIndex) {} |
| 1959 |
~Completion() { GPR_ASSERT(index_ == kNullIndex); } |
| 1960 |
explicit Completion(uint8_t index) : index_(index) {} |
| 1961 |
Completion(const Completion& other) = delete; |
| 1962 |
Completion& operator=(const Completion& other) = delete; |
| 1963 |
Completion(Completion&& other) noexcept : index_(other.index_) { |
| 1964 |
other.index_ = kNullIndex; |
| 1965 |
} |
| 1966 |
Completion& operator=(Completion&& other) noexcept { |
| 1967 |
GPR_ASSERT(index_ == kNullIndex); |
| 1968 |
index_ = other.index_; |
| 1969 |
other.index_ = kNullIndex; |
| 1970 |
return *this; |
| 1971 |
} |
| 1972 |
|
| 1973 |
uint8_t index() const { return index_; } |
| 1974 |
uint8_t TakeIndex() { return std::exchange(index_, kNullIndex); } |
| 1975 |
bool has_value() const { return index_ != kNullIndex; } |
| 1976 |
|
| 1977 |
std::string ToString() const { |
| 1978 |
return index_ == kNullIndex ? "null" |
| 1979 |
: std::to_string(static_cast<int>(index_)); |
| 1980 |
} |
| 1981 |
|
| 1982 |
private: |
| 1983 |
enum : uint8_t { kNullIndex = 0xff }; |
| 1984 |
uint8_t index_; |
| 1985 |
}; |
| 1986 |
|
| 1987 |
~PromiseBasedCall() override { |
| 1988 |
if (non_owning_wakeable_) non_owning_wakeable_->DropActivity(); |
| 1989 |
if (cq_) GRPC_CQ_INTERNAL_UNREF(cq_, "bind"); |
| 1990 |
} |
| 1991 |
|
| 1992 |
// Enumerates why a Completion is still pending |
| 1993 |
enum class PendingOp { |
| 1994 |
// We're in the midst of starting a batch of operations |
| 1995 |
kStartingBatch = 0, |
| 1996 |
// The following correspond with the batch operations from above |
| 1997 |
kReceiveInitialMetadata, |
| 1998 |
kReceiveStatusOnClient, |
| 1999 |
kSendMessage, |
| 2000 |
kReceiveMessage, |
| 2001 |
}; |
| 2002 |
|
| 2003 |
static constexpr const char* PendingOpString(PendingOp reason) { |
| 2004 |
switch (reason) { |
| 2005 |
case PendingOp::kStartingBatch: |
| 2006 |
return "StartingBatch"; |
| 2007 |
case PendingOp::kReceiveInitialMetadata: |
| 2008 |
return "ReceiveInitialMetadata"; |
| 2009 |
case PendingOp::kReceiveStatusOnClient: |
| 2010 |
return "ReceiveStatusOnClient"; |
| 2011 |
case PendingOp::kSendMessage: |
| 2012 |
return "SendMessage"; |
| 2013 |
case PendingOp::kReceiveMessage: |
| 2014 |
return "ReceiveMessage"; |
| 2015 |
} |
| 2016 |
return "Unknown"; |
| 2017 |
} |
| 2018 |
|
| 2019 |
static constexpr uint8_t PendingOpBit(PendingOp reason) { |
| 2020 |
return 1 << static_cast<int>(reason); |
| 2021 |
} |
| 2022 |
|
| 2023 |
Mutex* mu() const ABSL_LOCK_RETURNED(mu_) { return &mu_; } |
| 2024 |
|
| 2025 |
// Begin work on a completion, recording the tag/closure to notify. |
| 2026 |
// Use the op selected in \a ops to determine the index to allocate into. |
| 2027 |
// Starts the "StartingBatch" PendingOp immediately. |
| 2028 |
// Assumes at least one operation in \a ops. |
| 2029 |
Completion StartCompletion(void* tag, bool is_closure, const grpc_op* ops) |
| 2030 |
ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_); |
| 2031 |
// Add one pending op to the completion, and return it. |
| 2032 |
Completion AddOpToCompletion(const Completion& completion, PendingOp reason) |
| 2033 |
ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_); |
| 2034 |
// Finish one op on the completion. Must have been previously been added. |
| 2035 |
// The completion as a whole finishes when all pending ops finish. |
| 2036 |
void FinishOpOnCompletion(Completion* completion, PendingOp reason) |
| 2037 |
ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_); |
| 2038 |
// Mark the completion as failed. Does not finish it. |
| 2039 |
void FailCompletion(const Completion& completion); |
| 2040 |
// Run the promise polling loop until it stalls. |
| 2041 |
void Update() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_); |
| 2042 |
// Update the promise state once. |
| 2043 |
virtual void UpdateOnce() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_) = 0; |
| 2044 |
// Accept the stats from the context (call once we have proof the transport is |
| 2045 |
// done with them). |
| 2046 |
// Right now this means that promise based calls do not record correct stats |
| 2047 |
// with census if they are cancelled. |
| 2048 |
// TODO(ctiller): this should be remedied before promise based calls are |
| 2049 |
// dexperimentalized. |
| 2050 |
void AcceptTransportStatsFromContext() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_) { |
| 2051 |
final_stats_ = *call_context_.call_stats(); |
| 2052 |
} |
| 2053 |
|
| 2054 |
grpc_completion_queue* cq() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_) { return cq_; } |
| 2055 |
|
| 2056 |
void CToMetadata(grpc_metadata* metadata, size_t count, |
| 2057 |
grpc_metadata_batch* batch); |
| 2058 |
|
| 2059 |
std::string ActivityDebugTag() const override { return DebugTag(); } |
| 2060 |
|
| 2061 |
// At the end of the call run any finalization actions. |
| 2062 |
void RunFinalization(grpc_status_code status, const char* status_details) { |
| 2063 |
grpc_call_final_info final_info; |
| 2064 |
final_info.stats = final_stats_; |
| 2065 |
final_info.final_status = status; |
| 2066 |
final_info.error_string = status_details; |
| 2067 |
finalization_.Run(&final_info); |
| 2068 |
} |
| 2069 |
|
| 2070 |
private: |
| 2071 |
union CompletionInfo { |
| 2072 |
struct Pending { |
| 2073 |
// Bitmask of PendingOps |
| 2074 |
uint8_t pending_op_bits; |
| 2075 |
bool is_closure; |
| 2076 |
bool success; |
| 2077 |
void* tag; |
| 2078 |
} pending; |
| 2079 |
grpc_cq_completion completion; |
| 2080 |
}; |
| 2081 |
|
| 2082 |
class NonOwningWakable final : public Wakeable { |
| 2083 |
public: |
| 2084 |
explicit NonOwningWakable(PromiseBasedCall* call) : call_(call) {} |
| 2085 |
|
| 2086 |
// Ref the Handle (not the activity). |
| 2087 |
void Ref() { refs_.fetch_add(1, std::memory_order_relaxed); } |
| 2088 |
|
| 2089 |
// Activity is going away... drop its reference and sever the connection |
| 2090 |
// back. |
| 2091 |
void DropActivity() ABSL_LOCKS_EXCLUDED(mu_) { |
| 2092 |
auto unref = absl::MakeCleanup([this]() { Unref(); }); |
| 2093 |
MutexLock lock(&mu_); |
| 2094 |
GPR_ASSERT(call_ != nullptr); |
| 2095 |
call_ = nullptr; |
| 2096 |
} |
| 2097 |
|
| 2098 |
// Activity needs to wake up (if it still exists!) - wake it up, and drop |
| 2099 |
// the ref that was kept for this handle. |
| 2100 |
void Wakeup() override ABSL_LOCKS_EXCLUDED(mu_) { |
| 2101 |
// Drop the ref to the handle at end of scope (we have one ref = one |
| 2102 |
// wakeup semantics). |
| 2103 |
auto unref = absl::MakeCleanup([this]() { Unref(); }); |
| 2104 |
ReleasableMutexLock lock(&mu_); |
| 2105 |
// Note that activity refcount can drop to zero, but we could win the lock |
| 2106 |
// against DropActivity, so we need to only increase activities refcount |
| 2107 |
// if it is non-zero. |
| 2108 |
if (call_ != nullptr && call_->RefIfNonZero()) { |
| 2109 |
PromiseBasedCall* call = call_; |
| 2110 |
lock.Release(); |
| 2111 |
// Activity still exists and we have a reference: wake it up, which will |
| 2112 |
// drop the ref. |
| 2113 |
call->Wakeup(); |
| 2114 |
} |
| 2115 |
} |
| 2116 |
|
| 2117 |
std::string ActivityDebugTag() const override { |
| 2118 |
MutexLock lock(&mu_); |
| 2119 |
return call_ == nullptr ? "<unknown>" : call_->DebugTag(); |
| 2120 |
} |
| 2121 |
|
| 2122 |
void Drop() override { Unref(); } |
| 2123 |
|
| 2124 |
private: |
| 2125 |
// Unref the Handle (not the activity). |
| 2126 |
void Unref() { |
| 2127 |
if (1 == refs_.fetch_sub(1, std::memory_order_acq_rel)) { |
| 2128 |
delete this; |
| 2129 |
} |
| 2130 |
} |
| 2131 |
|
| 2132 |
mutable Mutex mu_; |
| 2133 |
// We have two initial refs: one for the wakeup that this is created for, |
| 2134 |
// and will be dropped by Wakeup, and the other for the activity which is |
| 2135 |
// dropped by DropActivity. |
| 2136 |
std::atomic<size_t> refs_{2}; |
| 2137 |
PromiseBasedCall* call_ ABSL_GUARDED_BY(mu_); |
| 2138 |
}; |
| 2139 |
|
| 2140 |
static void OnDestroy(void* arg, grpc_error_handle) { |
| 2141 |
auto* call = static_cast<PromiseBasedCall*>(arg); |
| 2142 |
ScopedContext context(call); |
| 2143 |
call->DeleteThis(); |
| 2144 |
} |
| 2145 |
|
| 2146 |
// First 32 bits are strong refs, next 32 bits are weak refs. |
| 2147 |
static uint64_t MakeRefPair(uint32_t strong, uint32_t weak) { |
| 2148 |
return (static_cast<uint64_t>(strong) << 32) + static_cast<int64_t>(weak); |
| 2149 |
} |
| 2150 |
static uint32_t GetStrongRefs(uint64_t ref_pair) { |
| 2151 |
return static_cast<uint32_t>(ref_pair >> 32); |
| 2152 |
} |
| 2153 |
static uint32_t GetWeakRefs(uint64_t ref_pair) { |
| 2154 |
return static_cast<uint32_t>(ref_pair & 0xffffffffu); |
| 2155 |
} |
| 2156 |
|
| 2157 |
bool RefIfNonZero() { |
| 2158 |
uint64_t prev_ref_pair = refs_.load(std::memory_order_acquire); |
| 2159 |
do { |
| 2160 |
const uint32_t strong_refs = GetStrongRefs(prev_ref_pair); |
| 2161 |
if (strong_refs == 0) return false; |
| 2162 |
} while (!refs_.compare_exchange_weak( |
| 2163 |
prev_ref_pair, prev_ref_pair + MakeRefPair(1, 0), |
| 2164 |
std::memory_order_acq_rel, std::memory_order_acquire)); |
| 2165 |
return true; |
| 2166 |
} |
| 2167 |
|
| 2168 |
mutable Mutex mu_; |
| 2169 |
std::atomic<uint64_t> refs_{MakeRefPair(1, 0)}; |
| 2170 |
CallContext call_context_{this}; |
| 2171 |
bool keep_polling_ ABSL_GUARDED_BY(mu()) = false; |
| 2172 |
|
| 2173 |
/* Contexts for various subsystems (security, tracing, ...). */ |
| 2174 |
grpc_call_context_element context_[GRPC_CONTEXT_COUNT] = {}; |
| 2175 |
grpc_completion_queue* cq_ ABSL_GUARDED_BY(mu_); |
| 2176 |
NonOwningWakable* non_owning_wakeable_ ABSL_GUARDED_BY(mu_) = nullptr; |
| 2177 |
CompletionInfo completion_info_[6]; |
| 2178 |
grpc_call_stats final_stats_{}; |
| 2179 |
CallFinalization finalization_; |
| 2180 |
}; |
| 2181 |
|
| 2182 |
template <typename T> |
| 2183 |
grpc_error_handle MakePromiseBasedCall(grpc_call_create_args* args, |
| 2184 |
grpc_call** out_call) { |
| 2185 |
Channel* channel = args->channel.get(); |
| 2186 |
|
| 2187 |
auto alloc = Arena::CreateWithAlloc(channel->CallSizeEstimate(), sizeof(T), |
| 2188 |
channel->allocator()); |
| 2189 |
PromiseBasedCall* call = new (alloc.second) T(alloc.first, args); |
| 2190 |
*out_call = call->c_ptr(); |
| 2191 |
GPR_DEBUG_ASSERT(Call::FromC(*out_call) == call); |
| 2192 |
return absl::OkStatus(); |
| 2193 |
} |
| 2194 |
|
| 2195 |
PromiseBasedCall::PromiseBasedCall(Arena* arena, |
| 2196 |
const grpc_call_create_args& args) |
| 2197 |
: Call(arena, args.server_transport_data == nullptr, args.send_deadline, |
| 2198 |
args.channel->Ref()), |
| 2199 |
cq_(args.cq) { |
| 2200 |
if (args.cq != nullptr) { |
| 2201 |
GPR_ASSERT(args.pollset_set_alternative == nullptr && |
| 2202 |
"Only one of 'cq' and 'pollset_set_alternative' should be " |
| 2203 |
"non-nullptr."); |
| 2204 |
GRPC_CQ_INTERNAL_REF(args.cq, "bind"); |
| 2205 |
call_context_.pollent_ = |
| 2206 |
grpc_polling_entity_create_from_pollset(grpc_cq_pollset(args.cq)); |
| 2207 |
} |
| 2208 |
if (args.pollset_set_alternative != nullptr) { |
| 2209 |
call_context_.pollent_ = grpc_polling_entity_create_from_pollset_set( |
| 2210 |
args.pollset_set_alternative); |
| 2211 |
} |
| 2212 |
} |
| 2213 |
|
| 2214 |
Waker PromiseBasedCall::MakeNonOwningWaker() { |
| 2215 |
if (non_owning_wakeable_ == nullptr) { |
| 2216 |
non_owning_wakeable_ = new NonOwningWakable(this); |
| 2217 |
} else { |
| 2218 |
non_owning_wakeable_->Ref(); |
| 2219 |
} |
| 2220 |
return Waker(non_owning_wakeable_); |
| 2221 |
} |
| 2222 |
|
| 2223 |
void PromiseBasedCall::CToMetadata(grpc_metadata* metadata, size_t count, |
| 2224 |
grpc_metadata_batch* b) { |
| 2225 |
for (size_t i = 0; i < count; i++) { |
| 2226 |
grpc_metadata* md = &metadata[i]; |
| 2227 |
auto key = StringViewFromSlice(md->key); |
| 2228 |
// Filter "content-length metadata" |
| 2229 |
if (key == "content-length") continue; |
| 2230 |
b->Append(key, Slice(CSliceRef(md->value)), |
| 2231 |
[md](absl::string_view error, const Slice& value) { |
| 2232 |
gpr_log(GPR_DEBUG, "Append error: %s", |
| 2233 |
absl::StrCat("key=", StringViewFromSlice(md->key), |
| 2234 |
" error=", error, |
| 2235 |
" value=", value.as_string_view()) |
| 2236 |
.c_str()); |
| 2237 |
}); |
| 2238 |
} |
| 2239 |
} |
| 2240 |
|
| 2241 |
void PromiseBasedCall::ContextSet(grpc_context_index elem, void* value, |
| 2242 |
void (*destroy)(void*)) { |
| 2243 |
if (context_[elem].destroy != nullptr) { |
| 2244 |
context_[elem].destroy(context_[elem].value); |
| 2245 |
} |
| 2246 |
context_[elem].value = value; |
| 2247 |
context_[elem].destroy = destroy; |
| 2248 |
} |
| 2249 |
|
| 2250 |
void* PromiseBasedCall::ContextGet(grpc_context_index elem) const { |
| 2251 |
return context_[elem].value; |
| 2252 |
} |
| 2253 |
|
| 2254 |
PromiseBasedCall::Completion PromiseBasedCall::StartCompletion( |
| 2255 |
void* tag, bool is_closure, const grpc_op* ops) { |
| 2256 |
Completion c(BatchSlotForOp(ops[0].op)); |
| 2257 |
if (grpc_call_trace.enabled()) { |
| 2258 |
gpr_log(GPR_INFO, "%sStartCompletion %s tag=%p", DebugTag().c_str(), |
| 2259 |
c.ToString().c_str(), tag); |
| 2260 |
} |
| 2261 |
if (!is_closure) { |
| 2262 |
grpc_cq_begin_op(cq(), tag); |
| 2263 |
} |
| 2264 |
completion_info_[c.index()].pending = { |
| 2265 |
PendingOpBit(PendingOp::kStartingBatch), is_closure, true, tag}; |
| 2266 |
return c; |
| 2267 |
} |
| 2268 |
|
| 2269 |
PromiseBasedCall::Completion PromiseBasedCall::AddOpToCompletion( |
| 2270 |
const Completion& completion, PendingOp reason) { |
| 2271 |
if (grpc_call_trace.enabled()) { |
| 2272 |
gpr_log(GPR_INFO, "%sAddOpToCompletion %s %s", DebugTag().c_str(), |
| 2273 |
completion.ToString().c_str(), PendingOpString(reason)); |
| 2274 |
} |
| 2275 |
auto& pending_op_bits = |
| 2276 |
completion_info_[completion.index()].pending.pending_op_bits; |
| 2277 |
GPR_ASSERT((pending_op_bits & PendingOpBit(reason)) == 0); |
| 2278 |
pending_op_bits |= PendingOpBit(reason); |
| 2279 |
return Completion(completion.index()); |
| 2280 |
} |
| 2281 |
|
| 2282 |
void PromiseBasedCall::FailCompletion(const Completion& completion) { |
| 2283 |
if (grpc_call_trace.enabled()) { |
| 2284 |
gpr_log(GPR_INFO, "%sFailCompletion %s", DebugTag().c_str(), |
| 2285 |
completion.ToString().c_str()); |
| 2286 |
} |
| 2287 |
completion_info_[completion.index()].pending.success = false; |
| 2288 |
} |
| 2289 |
|
| 2290 |
void PromiseBasedCall::FinishOpOnCompletion(Completion* completion, |
| 2291 |
PendingOp reason) { |
| 2292 |
if (grpc_call_trace.enabled()) { |
| 2293 |
auto pending_op_bits = |
| 2294 |
completion_info_[completion->index()].pending.pending_op_bits; |
| 2295 |
bool success = completion_info_[completion->index()].pending.success; |
| 2296 |
std::vector<const char*> pending; |
| 2297 |
for (size_t i = 0; i < 8 * sizeof(pending_op_bits); i++) { |
| 2298 |
if (static_cast<PendingOp>(i) == reason) continue; |
| 2299 |
if (pending_op_bits & (1 << i)) { |
| 2300 |
pending.push_back(PendingOpString(static_cast<PendingOp>(i))); |
| 2301 |
} |
| 2302 |
} |
| 2303 |
gpr_log( |
| 2304 |
GPR_INFO, "%sFinishOpOnCompletion %s %s %s", DebugTag().c_str(), |
| 2305 |
completion->ToString().c_str(), PendingOpString(reason), |
| 2306 |
(pending.empty() |
| 2307 |
? (success ? std::string("done") : std::string("failed")) |
| 2308 |
: absl::StrFormat("pending_ops={%s}", absl::StrJoin(pending, ","))) |
| 2309 |
.c_str()); |
| 2310 |
} |
| 2311 |
const uint8_t i = completion->TakeIndex(); |
| 2312 |
GPR_ASSERT(i < GPR_ARRAY_SIZE(completion_info_)); |
| 2313 |
CompletionInfo::Pending& pending = completion_info_[i].pending; |
| 2314 |
GPR_ASSERT(pending.pending_op_bits & PendingOpBit(reason)); |
| 2315 |
pending.pending_op_bits &= ~PendingOpBit(reason); |
| 2316 |
auto error = pending.success ? absl::OkStatus() : absl::CancelledError(); |
| 2317 |
if (pending.pending_op_bits == 0) { |
| 2318 |
if (pending.is_closure) { |
| 2319 |
ExecCtx::Run(DEBUG_LOCATION, static_cast<grpc_closure*>(pending.tag), |
| 2320 |
error); |
| 2321 |
} else { |
| 2322 |
grpc_cq_end_op( |
| 2323 |
cq(), pending.tag, error, [](void*, grpc_cq_completion*) {}, nullptr, |
| 2324 |
&completion_info_[i].completion); |
| 2325 |
} |
| 2326 |
} |
| 2327 |
} |
| 2328 |
|
| 2329 |
void PromiseBasedCall::Update() { |
| 2330 |
keep_polling_ = false; |
| 2331 |
do { |
| 2332 |
UpdateOnce(); |
| 2333 |
} while (std::exchange(keep_polling_, false)); |
| 2334 |
} |
| 2335 |
|
| 2336 |
void PromiseBasedCall::ForceImmediateRepoll() { keep_polling_ = true; } |
| 2337 |
|
| 2338 |
void PromiseBasedCall::SetCompletionQueue(grpc_completion_queue* cq) { |
| 2339 |
MutexLock lock(&mu_); |
| 2340 |
cq_ = cq; |
| 2341 |
GRPC_CQ_INTERNAL_REF(cq, "bind"); |
| 2342 |
call_context_.pollent_ = |
| 2343 |
grpc_polling_entity_create_from_pollset(grpc_cq_pollset(cq)); |
| 2344 |
} |
| 2345 |
|
| 2346 |
/////////////////////////////////////////////////////////////////////////////// |
| 2347 |
// CallContext |
| 2348 |
|
| 2349 |
void CallContext::RunInContext(absl::AnyInvocable<void()> fn) { |
| 2350 |
call_->RunInContext(std::move(fn)); |
| 2351 |
} |
| 2352 |
|
| 2353 |
void CallContext::IncrementRefCount(const char* reason) { |
| 2354 |
call_->InternalRef(reason); |
| 2355 |
} |
| 2356 |
|
| 2357 |
void CallContext::Unref(const char* reason) { call_->InternalUnref(reason); } |
| 2358 |
|
| 2359 |
/////////////////////////////////////////////////////////////////////////////// |
| 2360 |
// ClientPromiseBasedCall |
| 2361 |
|
| 2362 |
class ClientPromiseBasedCall final : public PromiseBasedCall { |
| 2363 |
public: |
| 2364 |
ClientPromiseBasedCall(Arena* arena, grpc_call_create_args* args) |
| 2365 |
: PromiseBasedCall(arena, *args) { |
| 2366 |
global_stats().IncrementClientCallsCreated(); |
| 2367 |
ScopedContext context(this); |
| 2368 |
send_initial_metadata_ = |
| 2369 |
GetContext<Arena>()->MakePooled<ClientMetadata>(GetContext<Arena>()); |
| 2370 |
send_initial_metadata_->Set(HttpPathMetadata(), std::move(*args->path)); |
| 2371 |
if (args->authority.has_value()) { |
| 2372 |
send_initial_metadata_->Set(HttpAuthorityMetadata(), |
| 2373 |
std::move(*args->authority)); |
| 2374 |
} |
| 2375 |
if (auto* channelz_channel = channel()->channelz_node()) { |
| 2376 |
channelz_channel->RecordCallStarted(); |
| 2377 |
} |
| 2378 |
} |
| 2379 |
|
| 2380 |
~ClientPromiseBasedCall() override { |
| 2381 |
ScopedContext context(this); |
| 2382 |
send_initial_metadata_.reset(); |
| 2383 |
recv_status_on_client_ = absl::monostate(); |
| 2384 |
promise_ = ArenaPromise<ServerMetadataHandle>(); |
| 2385 |
// Need to destroy the pipes under the ScopedContext above, so we move them |
| 2386 |
// out here and then allow the destructors to run at end of scope, but |
| 2387 |
// before context. |
| 2388 |
auto c2s = std::move(client_to_server_messages_); |
| 2389 |
auto s2c = std::move(server_to_client_messages_); |
| 2390 |
} |
| 2391 |
|
| 2392 |
absl::string_view GetServerAuthority() const override { abort(); } |
| 2393 |
void CancelWithError(grpc_error_handle error) override; |
| 2394 |
bool Completed() override; |
| 2395 |
void Orphan() override { |
| 2396 |
MutexLock lock(mu()); |
| 2397 |
ScopedContext ctx(this); |
| 2398 |
if (!completed_) Finish(ServerMetadataFromStatus(absl::CancelledError())); |
| 2399 |
} |
| 2400 |
bool is_trailers_only() const override { |
| 2401 |
MutexLock lock(mu()); |
| 2402 |
return is_trailers_only_; |
| 2403 |
} |
| 2404 |
bool failed_before_recv_message() const override { abort(); } |
| 2405 |
|
| 2406 |
grpc_call_error StartBatch(const grpc_op* ops, size_t nops, void* notify_tag, |
| 2407 |
bool is_notify_tag_closure) override; |
| 2408 |
|
| 2409 |
std::string DebugTag() const override { |
| 2410 |
return absl::StrFormat("CLIENT_CALL[%p]: ", this); |
| 2411 |
} |
| 2412 |
|
| 2413 |
private: |
| 2414 |
// Poll the underlying promise (and sundry objects) once. |
| 2415 |
void UpdateOnce() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu()) override; |
| 2416 |
// Finish the call with the given status/trailing metadata. |
| 2417 |
void Finish(ServerMetadataHandle trailing_metadata) |
| 2418 |
ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu()); |
| 2419 |
// Validate that a set of ops is valid for a client call. |
| 2420 |
grpc_call_error ValidateBatch(const grpc_op* ops, size_t nops) const |
| 2421 |
ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu()); |
| 2422 |
// Commit a valid batch of operations to be executed. |
| 2423 |
void CommitBatch(const grpc_op* ops, size_t nops, |
| 2424 |
const Completion& completion) |
| 2425 |
ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu()); |
| 2426 |
// Start the underlying promise. |
| 2427 |
void StartPromise(ClientMetadataHandle client_initial_metadata) |
| 2428 |
ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu()); |
| 2429 |
// Publish some metadata out to the application. |
| 2430 |
static void PublishMetadataArray(grpc_metadata_array* array, |
| 2431 |
ServerMetadata* md); |
| 2432 |
// Publish status out to the application. |
| 2433 |
void PublishStatus( |
| 2434 |
grpc_op::grpc_op_data::grpc_op_recv_status_on_client op_args, |
| 2435 |
ServerMetadataHandle trailing_metadata) |
| 2436 |
ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu()); |
| 2437 |
// Publish server initial metadata out to the application. |
| 2438 |
void PublishInitialMetadata(ServerMetadata* metadata) |
| 2439 |
ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu()); |
| 2440 |
|
| 2441 |
ArenaPromise<ServerMetadataHandle> promise_ ABSL_GUARDED_BY(mu()); |
| 2442 |
Latch<ServerMetadata*> server_initial_metadata_ ABSL_GUARDED_BY(mu()); |
| 2443 |
Pipe<MessageHandle> client_to_server_messages_ ABSL_GUARDED_BY(mu()){arena()}; |
| 2444 |
Pipe<MessageHandle> server_to_client_messages_ ABSL_GUARDED_BY(mu()){arena()}; |
| 2445 |
|
| 2446 |
ClientMetadataHandle send_initial_metadata_; |
| 2447 |
grpc_metadata_array* recv_initial_metadata_ ABSL_GUARDED_BY(mu()) = nullptr; |
| 2448 |
grpc_byte_buffer** recv_message_ ABSL_GUARDED_BY(mu()) = nullptr; |
| 2449 |
absl::variant<absl::monostate, |
| 2450 |
grpc_op::grpc_op_data::grpc_op_recv_status_on_client, |
| 2451 |
ServerMetadataHandle> |
| 2452 |
recv_status_on_client_ ABSL_GUARDED_BY(mu()); |
| 2453 |
absl::optional<PipeSender<MessageHandle>::PushType> outstanding_send_ |
| 2454 |
ABSL_GUARDED_BY(mu()); |
| 2455 |
absl::optional<PipeReceiver<MessageHandle>::NextType> outstanding_recv_ |
| 2456 |
ABSL_GUARDED_BY(mu()); |
| 2457 |
absl::optional<Latch<ServerMetadata*>::WaitPromise> |
| 2458 |
server_initial_metadata_ready_; |
| 2459 |
absl::optional<grpc_compression_algorithm> incoming_compression_algorithm_; |
| 2460 |
Completion recv_initial_metadata_completion_ ABSL_GUARDED_BY(mu()); |
| 2461 |
Completion recv_status_on_client_completion_ ABSL_GUARDED_BY(mu()); |
| 2462 |
Completion send_message_completion_ ABSL_GUARDED_BY(mu()); |
| 2463 |
Completion recv_message_completion_ ABSL_GUARDED_BY(mu()); |
| 2464 |
bool completed_ ABSL_GUARDED_BY(mu()) = false; |
| 2465 |
bool is_trailers_only_ ABSL_GUARDED_BY(mu()); |
| 2466 |
}; |
| 2467 |
|
| 2468 |
void ClientPromiseBasedCall::StartPromise( |
| 2469 |
ClientMetadataHandle client_initial_metadata) { |
| 2470 |
GPR_ASSERT(!promise_.has_value()); |
| 2471 |
promise_ = channel()->channel_stack()->MakeClientCallPromise(CallArgs{ |
| 2472 |
std::move(client_initial_metadata), |
| 2473 |
&server_initial_metadata_, |
| 2474 |
&client_to_server_messages_.receiver, |
| 2475 |
&server_to_client_messages_.sender, |
| 2476 |
}); |
| 2477 |
} |
| 2478 |
|
| 2479 |
void ClientPromiseBasedCall::CancelWithError(grpc_error_handle error) { |
| 2480 |
MutexLock lock(mu()); |
| 2481 |
ScopedContext context(this); |
| 2482 |
Finish(ServerMetadataFromStatus(grpc_error_to_absl_status(error))); |
| 2483 |
} |
| 2484 |
|
| 2485 |
grpc_call_error ClientPromiseBasedCall::ValidateBatch(const grpc_op* ops, |
| 2486 |
size_t nops) const { |
| 2487 |
BitSet<8> got_ops; |
| 2488 |
for (size_t op_idx = 0; op_idx < nops; op_idx++) { |
| 2489 |
const grpc_op& op = ops[op_idx]; |
| 2490 |
switch (op.op) { |
| 2491 |
case GRPC_OP_SEND_INITIAL_METADATA: |
| 2492 |
if (!AreInitialMetadataFlagsValid(op.flags)) { |
| 2493 |
return GRPC_CALL_ERROR_INVALID_FLAGS; |
| 2494 |
} |
| 2495 |
if (!ValidateMetadata(op.data.send_initial_metadata.count, |
| 2496 |
op.data.send_initial_metadata.metadata)) { |
| 2497 |
return GRPC_CALL_ERROR_INVALID_METADATA; |
| 2498 |
} |
| 2499 |
break; |
| 2500 |
case GRPC_OP_SEND_MESSAGE: |
| 2501 |
if (!AreWriteFlagsValid(op.flags)) { |
| 2502 |
return GRPC_CALL_ERROR_INVALID_FLAGS; |
| 2503 |
} |
| 2504 |
break; |
| 2505 |
case GRPC_OP_RECV_INITIAL_METADATA: |
| 2506 |
case GRPC_OP_RECV_MESSAGE: |
| 2507 |
case GRPC_OP_SEND_CLOSE_FROM_CLIENT: |
| 2508 |
case GRPC_OP_RECV_STATUS_ON_CLIENT: |
| 2509 |
if (op.flags != 0) return GRPC_CALL_ERROR_INVALID_FLAGS; |
| 2510 |
break; |
| 2511 |
case GRPC_OP_RECV_CLOSE_ON_SERVER: |
| 2512 |
case GRPC_OP_SEND_STATUS_FROM_SERVER: |
| 2513 |
return GRPC_CALL_ERROR_NOT_ON_CLIENT; |
| 2514 |
} |
| 2515 |
if (got_ops.is_set(op.op)) return GRPC_CALL_ERROR_TOO_MANY_OPERATIONS; |
| 2516 |
got_ops.set(op.op); |
| 2517 |
} |
| 2518 |
return GRPC_CALL_OK; |
| 2519 |
} |
| 2520 |
|
| 2521 |
void ClientPromiseBasedCall::CommitBatch(const grpc_op* ops, size_t nops, |
| 2522 |
const Completion& completion) { |
| 2523 |
for (size_t op_idx = 0; op_idx < nops; op_idx++) { |
| 2524 |
const grpc_op& op = ops[op_idx]; |
| 2525 |
switch (op.op) { |
| 2526 |
case GRPC_OP_SEND_INITIAL_METADATA: { |
| 2527 |
// compression not implemented |
| 2528 |
GPR_ASSERT( |
| 2529 |
!op.data.send_initial_metadata.maybe_compression_level.is_set); |
| 2530 |
if (!completed_) { |
| 2531 |
CToMetadata(op.data.send_initial_metadata.metadata, |
| 2532 |
op.data.send_initial_metadata.count, |
| 2533 |
send_initial_metadata_.get()); |
| 2534 |
StartPromise(std::move(send_initial_metadata_)); |
| 2535 |
} |
| 2536 |
} break; |
| 2537 |
case GRPC_OP_RECV_INITIAL_METADATA: { |
| 2538 |
recv_initial_metadata_ = |
| 2539 |
op.data.recv_initial_metadata.recv_initial_metadata; |
| 2540 |
server_initial_metadata_ready_ = server_initial_metadata_.Wait(); |
| 2541 |
recv_initial_metadata_completion_ = |
| 2542 |
AddOpToCompletion(completion, PendingOp::kReceiveInitialMetadata); |
| 2543 |
} break; |
| 2544 |
case GRPC_OP_RECV_STATUS_ON_CLIENT: { |
| 2545 |
recv_status_on_client_completion_ = |
| 2546 |
AddOpToCompletion(completion, PendingOp::kReceiveStatusOnClient); |
| 2547 |
if (auto* finished_metadata = |
| 2548 |
absl::get_if<ServerMetadataHandle>(&recv_status_on_client_)) { |
| 2549 |
PublishStatus(op.data.recv_status_on_client, |
| 2550 |
std::move(*finished_metadata)); |
| 2551 |
} else { |
| 2552 |
recv_status_on_client_ = op.data.recv_status_on_client; |
| 2553 |
} |
| 2554 |
} break; |
| 2555 |
case GRPC_OP_SEND_MESSAGE: { |
| 2556 |
GPR_ASSERT(!outstanding_send_.has_value()); |
| 2557 |
if (!completed_) { |
| 2558 |
send_message_completion_ = |
| 2559 |
AddOpToCompletion(completion, PendingOp::kSendMessage); |
| 2560 |
SliceBuffer send; |
| 2561 |
grpc_slice_buffer_swap( |
| 2562 |
&op.data.send_message.send_message->data.raw.slice_buffer, |
| 2563 |
send.c_slice_buffer()); |
| 2564 |
outstanding_send_.emplace(client_to_server_messages_.sender.Push( |
| 2565 |
GetContext<Arena>()->MakePooled<Message>(std::move(send), |
| 2566 |
op.flags))); |
| 2567 |
} else { |
| 2568 |
FailCompletion(completion); |
| 2569 |
} |
| 2570 |
} break; |
| 2571 |
case GRPC_OP_RECV_MESSAGE: { |
| 2572 |
GPR_ASSERT(!outstanding_recv_.has_value()); |
| 2573 |
recv_message_ = op.data.recv_message.recv_message; |
| 2574 |
recv_message_completion_ = |
| 2575 |
AddOpToCompletion(completion, PendingOp::kReceiveMessage); |
| 2576 |
outstanding_recv_.emplace(server_to_client_messages_.receiver.Next()); |
| 2577 |
} break; |
| 2578 |
case GRPC_OP_SEND_CLOSE_FROM_CLIENT: { |
| 2579 |
client_to_server_messages_.sender.Close(); |
| 2580 |
} break; |
| 2581 |
case GRPC_OP_SEND_STATUS_FROM_SERVER: |
| 2582 |
case GRPC_OP_RECV_CLOSE_ON_SERVER: |
| 2583 |
abort(); // unreachable |
| 2584 |
} |
| 2585 |
} |
| 2586 |
} |
| 2587 |
|
| 2588 |
grpc_call_error ClientPromiseBasedCall::StartBatch(const grpc_op* ops, |
| 2589 |
size_t nops, |
| 2590 |
void* notify_tag, |
| 2591 |
bool is_notify_tag_closure) { |
| 2592 |
MutexLock lock(mu()); |
| 2593 |
ScopedContext activity_context(this); |
| 2594 |
if (nops == 0) { |
| 2595 |
EndOpImmediately(cq(), notify_tag, is_notify_tag_closure); |
| 2596 |
return GRPC_CALL_OK; |
| 2597 |
} |
| 2598 |
const grpc_call_error validation_result = ValidateBatch(ops, nops); |
| 2599 |
if (validation_result != GRPC_CALL_OK) { |
| 2600 |
return validation_result; |
| 2601 |
} |
| 2602 |
Completion completion = |
| 2603 |
StartCompletion(notify_tag, is_notify_tag_closure, ops); |
| 2604 |
CommitBatch(ops, nops, completion); |
| 2605 |
Update(); |
| 2606 |
FinishOpOnCompletion(&completion, PendingOp::kStartingBatch); |
| 2607 |
return GRPC_CALL_OK; |
| 2608 |
} |
| 2609 |
|
| 2610 |
void ClientPromiseBasedCall::PublishInitialMetadata(ServerMetadata* metadata) { |
| 2611 |
incoming_compression_algorithm_ = |
| 2612 |
metadata->Take(GrpcEncodingMetadata()).value_or(GRPC_COMPRESS_NONE); |
| 2613 |
server_initial_metadata_ready_.reset(); |
| 2614 |
GPR_ASSERT(recv_initial_metadata_ != nullptr); |
| 2615 |
PublishMetadataArray(std::exchange(recv_initial_metadata_, nullptr), |
| 2616 |
metadata); |
| 2617 |
FinishOpOnCompletion(&recv_initial_metadata_completion_, |
| 2618 |
PendingOp::kReceiveInitialMetadata); |
| 2619 |
} |
| 2620 |
|
| 2621 |
void ClientPromiseBasedCall::UpdateOnce() { |
| 2622 |
if (grpc_call_trace.enabled()) { |
| 2623 |
auto present_and_completion_text = |
| 2624 |
[](const char* caption, bool has, |
| 2625 |
const Completion& completion) -> std::string { |
| 2626 |
if (has) { |
| 2627 |
if (completion.has_value()) { |
| 2628 |
return absl::StrCat(caption, ":", |
| 2629 |
static_cast<int>(completion.index()), " "); |
| 2630 |
} else { |
| 2631 |
return absl::StrCat(caption, |
| 2632 |
":!!BUG:operation is present, no completion!! "); |
| 2633 |
} |
| 2634 |
} else { |
| 2635 |
if (!completion.has_value()) { |
| 2636 |
return ""; |
| 2637 |
} else { |
| 2638 |
return absl::StrCat( |
| 2639 |
caption, ":no-op:", static_cast<int>(completion.index()), " "); |
| 2640 |
} |
| 2641 |
} |
| 2642 |
}; |
| 2643 |
gpr_log( |
| 2644 |
GPR_INFO, "%sUpdateOnce: %s%s%shas_promise=%s", DebugTag().c_str(), |
| 2645 |
present_and_completion_text("server_initial_metadata_ready", |
| 2646 |
server_initial_metadata_ready_.has_value(), |
| 2647 |
recv_initial_metadata_completion_) |
| 2648 |
.c_str(), |
| 2649 |
present_and_completion_text("outstanding_send", |
| 2650 |
outstanding_send_.has_value(), |
| 2651 |
send_message_completion_) |
| 2652 |
.c_str(), |
| 2653 |
present_and_completion_text("outstanding_recv", |
| 2654 |
outstanding_recv_.has_value(), |
| 2655 |
recv_message_completion_) |
| 2656 |
.c_str(), |
| 2657 |
promise_.has_value() ? "true" : "false"); |
| 2658 |
} |
| 2659 |
if (send_message_completion_.has_value()) { |
| 2660 |
FinishOpOnCompletion(&send_message_completion_, PendingOp::kSendMessage); |
| 2661 |
} |
| 2662 |
if (server_initial_metadata_ready_.has_value()) { |
| 2663 |
Poll<ServerMetadata**> r = (*server_initial_metadata_ready_)(); |
| 2664 |
if (ServerMetadata*** server_initial_metadata = |
| 2665 |
absl::get_if<ServerMetadata**>(&r)) { |
| 2666 |
PublishInitialMetadata(**server_initial_metadata); |
| 2667 |
} else if (completed_) { |
| 2668 |
ServerMetadata no_metadata{GetContext<Arena>()}; |
| 2669 |
PublishInitialMetadata(&no_metadata); |
| 2670 |
} |
| 2671 |
} |
| 2672 |
if (outstanding_send_.has_value()) { |
| 2673 |
Poll<bool> r = (*outstanding_send_)(); |
| 2674 |
if (const bool* result = absl::get_if<bool>(&r)) { |
| 2675 |
outstanding_send_.reset(); |
| 2676 |
if (!*result) { |
| 2677 |
FailCompletion(send_message_completion_); |
| 2678 |
Finish(ServerMetadataFromStatus(absl::Status( |
| 2679 |
absl::StatusCode::kInternal, "Failed to send message to server"))); |
| 2680 |
} |
| 2681 |
} |
| 2682 |
} |
| 2683 |
if (promise_.has_value()) { |
| 2684 |
Poll<ServerMetadataHandle> r = promise_(); |
| 2685 |
if (grpc_call_trace.enabled()) { |
| 2686 |
gpr_log(GPR_INFO, "%sUpdateOnce: promise returns %s", DebugTag().c_str(), |
| 2687 |
PollToString(r, [](const ServerMetadataHandle& h) { |
| 2688 |
return h->DebugString(); |
| 2689 |
}).c_str()); |
| 2690 |
} |
| 2691 |
if (auto* result = absl::get_if<ServerMetadataHandle>(&r)) { |
| 2692 |
AcceptTransportStatsFromContext(); |
| 2693 |
Finish(std::move(*result)); |
| 2694 |
} |
| 2695 |
} |
| 2696 |
if (incoming_compression_algorithm_.has_value() && |
| 2697 |
outstanding_recv_.has_value()) { |
| 2698 |
Poll<NextResult<MessageHandle>> r = (*outstanding_recv_)(); |
| 2699 |
if (auto* result = absl::get_if<NextResult<MessageHandle>>(&r)) { |
| 2700 |
outstanding_recv_.reset(); |
| 2701 |
if (result->has_value()) { |
| 2702 |
MessageHandle& message = **result; |
| 2703 |
if ((message->flags() & GRPC_WRITE_INTERNAL_COMPRESS) && |
| 2704 |
(incoming_compression_algorithm_ != GRPC_COMPRESS_NONE)) { |
| 2705 |
*recv_message_ = grpc_raw_compressed_byte_buffer_create( |
| 2706 |
nullptr, 0, *incoming_compression_algorithm_); |
| 2707 |
} else { |
| 2708 |
*recv_message_ = grpc_raw_byte_buffer_create(nullptr, 0); |
| 2709 |
} |
| 2710 |
grpc_slice_buffer_move_into(message->payload()->c_slice_buffer(), |
| 2711 |
&(*recv_message_)->data.raw.slice_buffer); |
| 2712 |
if (grpc_call_trace.enabled()) { |
| 2713 |
gpr_log(GPR_INFO, |
| 2714 |
"%sUpdateOnce: outstanding_recv finishes: received %" PRIdPTR |
| 2715 |
" byte message", |
| 2716 |
DebugTag().c_str(), |
| 2717 |
(*recv_message_)->data.raw.slice_buffer.length); |
| 2718 |
} |
| 2719 |
} else { |
| 2720 |
if (grpc_call_trace.enabled()) { |
| 2721 |
gpr_log( |
| 2722 |
GPR_INFO, |
| 2723 |
"%sUpdateOnce: outstanding_recv finishes: received end-of-stream", |
| 2724 |
DebugTag().c_str()); |
| 2725 |
} |
| 2726 |
*recv_message_ = nullptr; |
| 2727 |
} |
| 2728 |
FinishOpOnCompletion(&recv_message_completion_, |
| 2729 |
PendingOp::kReceiveMessage); |
| 2730 |
} else if (completed_) { |
| 2731 |
if (grpc_call_trace.enabled()) { |
| 2732 |
gpr_log(GPR_INFO, |
| 2733 |
"%sUpdateOnce: outstanding_recv finishes: promise has " |
| 2734 |
"completed without queuing a message, forcing end-of-stream", |
| 2735 |
DebugTag().c_str()); |
| 2736 |
} |
| 2737 |
outstanding_recv_.reset(); |
| 2738 |
*recv_message_ = nullptr; |
| 2739 |
FinishOpOnCompletion(&recv_message_completion_, |
| 2740 |
PendingOp::kReceiveMessage); |
| 2741 |
} |
| 2742 |
} |
| 2743 |
} |
| 2744 |
|
| 2745 |
void ClientPromiseBasedCall::Finish(ServerMetadataHandle trailing_metadata) { |
| 2746 |
if (grpc_call_trace.enabled()) { |
| 2747 |
gpr_log(GPR_INFO, "%sFinish: %s", DebugTag().c_str(), |
| 2748 |
trailing_metadata->DebugString().c_str()); |
| 2749 |
} |
| 2750 |
promise_ = ArenaPromise<ServerMetadataHandle>(); |
| 2751 |
completed_ = true; |
| 2752 |
if (recv_initial_metadata_ != nullptr) { |
| 2753 |
ForceImmediateRepoll(); |
| 2754 |
} |
| 2755 |
const bool pending_initial_metadata = |
| 2756 |
server_initial_metadata_ready_.has_value(); |
| 2757 |
server_initial_metadata_ready_.reset(); |
| 2758 |
Poll<ServerMetadata**> r = server_initial_metadata_.Wait()(); |
| 2759 |
if (auto* result = absl::get_if<ServerMetadata**>(&r)) { |
| 2760 |
if (pending_initial_metadata) PublishInitialMetadata(**result); |
| 2761 |
is_trailers_only_ = false; |
| 2762 |
} else { |
| 2763 |
if (pending_initial_metadata) { |
| 2764 |
ServerMetadata no_metadata{GetContext<Arena>()}; |
| 2765 |
PublishInitialMetadata(&no_metadata); |
| 2766 |
} |
| 2767 |
is_trailers_only_ = true; |
| 2768 |
} |
| 2769 |
if (auto* channelz_channel = channel()->channelz_node()) { |
| 2770 |
if (trailing_metadata->get(GrpcStatusMetadata()) |
| 2771 |
.value_or(GRPC_STATUS_UNKNOWN) == GRPC_STATUS_OK) { |
| 2772 |
channelz_channel->RecordCallSucceeded(); |
| 2773 |
} else { |
| 2774 |
channelz_channel->RecordCallFailed(); |
| 2775 |
} |
| 2776 |
} |
| 2777 |
if (auto* status_request = |
| 2778 |
absl::get_if<grpc_op::grpc_op_data::grpc_op_recv_status_on_client>( |
| 2779 |
&recv_status_on_client_)) { |
| 2780 |
PublishStatus(*status_request, std::move(trailing_metadata)); |
| 2781 |
} else { |
| 2782 |
recv_status_on_client_ = std::move(trailing_metadata); |
| 2783 |
} |
| 2784 |
} |
| 2785 |
|
| 2786 |
namespace { |
| 2787 |
std::string MakeErrorString(const ServerMetadata* trailing_metadata) { |
| 2788 |
std::string out = absl::StrCat( |
| 2789 |
trailing_metadata->get(GrpcStatusFromWire()).value_or(false) |
| 2790 |
? "Error received from peer" |
| 2791 |
: "Error generated by client", |
| 2792 |
"grpc_status: ", |
| 2793 |
grpc_status_code_to_string(trailing_metadata->get(GrpcStatusMetadata()) |
| 2794 |
.value_or(GRPC_STATUS_UNKNOWN))); |
| 2795 |
if (const Slice* message = |
| 2796 |
trailing_metadata->get_pointer(GrpcMessageMetadata())) { |
| 2797 |
absl::StrAppend(&out, "\ngrpc_message: ", message->as_string_view()); |
| 2798 |
} |
| 2799 |
if (auto annotations = trailing_metadata->get_pointer(GrpcStatusContext())) { |
| 2800 |
absl::StrAppend(&out, "\nStatus Context:"); |
| 2801 |
for (const std::string& annotation : *annotations) { |
| 2802 |
absl::StrAppend(&out, "\n ", annotation); |
| 2803 |
} |
| 2804 |
} |
| 2805 |
return out; |
| 2806 |
} |
| 2807 |
} // namespace |
| 2808 |
|
| 2809 |
void ClientPromiseBasedCall::PublishStatus( |
| 2810 |
grpc_op::grpc_op_data::grpc_op_recv_status_on_client op_args, |
| 2811 |
ServerMetadataHandle trailing_metadata) { |
| 2812 |
const grpc_status_code status = trailing_metadata->get(GrpcStatusMetadata()) |
| 2813 |
.value_or(GRPC_STATUS_UNKNOWN); |
| 2814 |
*op_args.status = status; |
| 2815 |
absl::string_view message_string; |
| 2816 |
if (Slice* message = trailing_metadata->get_pointer(GrpcMessageMetadata())) { |
| 2817 |
message_string = message->as_string_view(); |
| 2818 |
*op_args.status_details = message->Ref().TakeCSlice(); |
| 2819 |
} else { |
| 2820 |
*op_args.status_details = grpc_empty_slice(); |
| 2821 |
} |
| 2822 |
if (message_string.empty()) { |
| 2823 |
RunFinalization(status, nullptr); |
| 2824 |
} else { |
| 2825 |
std::string error_string(message_string); |
| 2826 |
RunFinalization(status, error_string.c_str()); |
| 2827 |
} |
| 2828 |
if (op_args.error_string != nullptr && status != GRPC_STATUS_OK) { |
| 2829 |
*op_args.error_string = |
| 2830 |
gpr_strdup(MakeErrorString(trailing_metadata.get()).c_str()); |
| 2831 |
} |
| 2832 |
PublishMetadataArray(op_args.trailing_metadata, trailing_metadata.get()); |
| 2833 |
FinishOpOnCompletion(&recv_status_on_client_completion_, |
| 2834 |
PendingOp::kReceiveStatusOnClient); |
| 2835 |
} |
| 2836 |
|
| 2837 |
void ClientPromiseBasedCall::PublishMetadataArray(grpc_metadata_array* array, |
| 2838 |
ServerMetadata* md) { |
| 2839 |
const auto md_count = md->count(); |
| 2840 |
if (md_count > array->capacity) { |
| 2841 |
array->capacity = |
| 2842 |
std::max(array->capacity + md->count(), array->capacity * 3 / 2); |
| 2843 |
array->metadata = static_cast<grpc_metadata*>( |
| 2844 |
gpr_realloc(array->metadata, sizeof(grpc_metadata) * array->capacity)); |
| 2845 |
} |
| 2846 |
PublishToAppEncoder encoder(array); |
| 2847 |
md->Encode(&encoder); |
| 2848 |
} |
| 2849 |
|
| 2850 |
bool ClientPromiseBasedCall::Completed() { |
| 2851 |
MutexLock lock(mu()); |
| 2852 |
return completed_; |
| 2853 |
} |
| 2854 |
|
| 2855 |
gpr_atm* CallContext::peer_string_atm_ptr() { |
| 2856 |
return call_->peer_string_atm_ptr(); |
| 2857 |
} |
| 2858 |
|
| 2859 |
} // namespace grpc_core |
| 2860 |
|
| 2861 |
/////////////////////////////////////////////////////////////////////////////// |
| 2862 |
// C-based API |
| 2863 |
|
| 2864 |
void* grpc_call_arena_alloc(grpc_call* call, size_t size) { |
| 2865 |
grpc_core::ExecCtx exec_ctx; |
| 2866 |
return grpc_core::Call::FromC(call)->arena()->Alloc(size); |
| 2867 |
} |
| 2868 |
|
| 2869 |
size_t grpc_call_get_initial_size_estimate() { |
| 2870 |
return grpc_core::FilterStackCall::InitialSizeEstimate(); |
| 2871 |
} |
| 2872 |
|
| 2873 |
grpc_error_handle grpc_call_create(grpc_call_create_args* args, |
| 2874 |
grpc_call** out_call) { |
| 2875 |
if (grpc_core::IsPromiseBasedClientCallEnabled() && |
| 2876 |
args->channel->is_promising()) { |
| 2877 |
if (args->server_transport_data == nullptr) { |
| 2878 |
return grpc_core::MakePromiseBasedCall<grpc_core::ClientPromiseBasedCall>( |
| 2879 |
args, out_call); |
| 2880 |
} |
| 2881 |
} |
| 2882 |
return grpc_core::FilterStackCall::Create(args, out_call); |
| 2883 |
} |
| 2884 |
|
| 2885 |
void grpc_call_set_completion_queue(grpc_call* call, |
| 2886 |
grpc_completion_queue* cq) { |
| 2887 |
grpc_core::Call::FromC(call)->SetCompletionQueue(cq); |
| 2888 |
} |
| 2889 |
|
| 2890 |
void grpc_call_ref(grpc_call* c) { grpc_core::Call::FromC(c)->ExternalRef(); } |
| 2891 |
|
| 2892 |
void grpc_call_unref(grpc_call* c) { |
| 2893 |
grpc_core::ExecCtx exec_ctx; |
| 2894 |
grpc_core::Call::FromC(c)->ExternalUnref(); |
| 2895 |
} |
| 2896 |
|
| 2897 |
char* grpc_call_get_peer(grpc_call* call) { |
| 2898 |
return grpc_core::Call::FromC(call)->GetPeer(); |
| 2899 |
} |
| 2900 |
|
| 2901 |
grpc_call* grpc_call_from_top_element(grpc_call_element* surface_element) { |
| 2902 |
return grpc_core::FilterStackCall::FromTopElem(surface_element)->c_ptr(); |
| 2903 |
} |
| 2904 |
|
| 2905 |
grpc_call_error grpc_call_cancel(grpc_call* call, void* reserved) { |
| 2906 |
GRPC_API_TRACE("grpc_call_cancel(call=%p, reserved=%p)", 2, (call, reserved)); |
| 2907 |
GPR_ASSERT(reserved == nullptr); |
| 2908 |
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; |
| 2909 |
grpc_core::ExecCtx exec_ctx; |
| 2910 |
grpc_core::Call::FromC(call)->CancelWithError(absl::CancelledError()); |
| 2911 |
return GRPC_CALL_OK; |
| 2912 |
} |
| 2913 |
|
| 2914 |
grpc_call_error grpc_call_cancel_with_status(grpc_call* c, |
| 2915 |
grpc_status_code status, |
| 2916 |
const char* description, |
| 2917 |
void* reserved) { |
| 2918 |
GRPC_API_TRACE( |
| 2919 |
"grpc_call_cancel_with_status(" |
| 2920 |
"c=%p, status=%d, description=%s, reserved=%p)", |
| 2921 |
4, (c, (int)status, description, reserved)); |
| 2922 |
GPR_ASSERT(reserved == nullptr); |
| 2923 |
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; |
| 2924 |
grpc_core::ExecCtx exec_ctx; |
| 2925 |
grpc_core::Call::FromC(c)->CancelWithStatus(status, description); |
| 2926 |
return GRPC_CALL_OK; |
| 2927 |
} |
| 2928 |
|
| 2929 |
void grpc_call_cancel_internal(grpc_call* call) { |
| 2930 |
grpc_core::Call::FromC(call)->CancelWithError(absl::CancelledError()); |
| 2931 |
} |
| 2932 |
|
| 2933 |
grpc_compression_algorithm grpc_call_test_only_get_compression_algorithm( |
| 2934 |
grpc_call* call) { |
| 2935 |
return grpc_core::Call::FromC(call)->test_only_compression_algorithm(); |
| 2936 |
} |
| 2937 |
|
| 2938 |
uint32_t grpc_call_test_only_get_message_flags(grpc_call* call) { |
| 2939 |
return grpc_core::Call::FromC(call)->test_only_message_flags(); |
| 2940 |
} |
| 2941 |
|
| 2942 |
uint32_t grpc_call_test_only_get_encodings_accepted_by_peer(grpc_call* call) { |
| 2943 |
return grpc_core::Call::FromC(call)->test_only_encodings_accepted_by_peer(); |
| 2944 |
} |
| 2945 |
|
| 2946 |
grpc_core::Arena* grpc_call_get_arena(grpc_call* call) { |
| 2947 |
return grpc_core::Call::FromC(call)->arena(); |
| 2948 |
} |
| 2949 |
|
| 2950 |
grpc_call_stack* grpc_call_get_call_stack(grpc_call* call) { |
| 2951 |
return grpc_core::Call::FromC(call)->call_stack(); |
| 2952 |
} |
| 2953 |
|
| 2954 |
grpc_call_error grpc_call_start_batch(grpc_call* call, const grpc_op* ops, |
| 2955 |
size_t nops, void* tag, void* reserved) { |
| 2956 |
GRPC_API_TRACE( |
| 2957 |
"grpc_call_start_batch(call=%p, ops=%p, nops=%lu, tag=%p, " |
| 2958 |
"reserved=%p)", |
| 2959 |
5, (call, ops, (unsigned long)nops, tag, reserved)); |
| 2960 |
|
| 2961 |
if (reserved != nullptr) { |
| 2962 |
return GRPC_CALL_ERROR; |
| 2963 |
} else { |
| 2964 |
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; |
| 2965 |
grpc_core::ExecCtx exec_ctx; |
| 2966 |
return grpc_core::Call::FromC(call)->StartBatch(ops, nops, tag, false); |
| 2967 |
} |
| 2968 |
} |
| 2969 |
|
| 2970 |
grpc_call_error grpc_call_start_batch_and_execute(grpc_call* call, |
| 2971 |
const grpc_op* ops, |
| 2972 |
size_t nops, |
| 2973 |
grpc_closure* closure) { |
| 2974 |
return grpc_core::Call::FromC(call)->StartBatch(ops, nops, closure, true); |
| 2975 |
} |
| 2976 |
|
| 2977 |
void grpc_call_context_set(grpc_call* call, grpc_context_index elem, |
| 2978 |
void* value, void (*destroy)(void* value)) { |
| 2979 |
return grpc_core::Call::FromC(call)->ContextSet(elem, value, destroy); |
| 2980 |
} |
| 2981 |
|
| 2982 |
void* grpc_call_context_get(grpc_call* call, grpc_context_index elem) { |
| 2983 |
return grpc_core::Call::FromC(call)->ContextGet(elem); |
| 2984 |
} |
| 2985 |
|
| 2986 |
uint8_t grpc_call_is_client(grpc_call* call) { |
| 2987 |
return grpc_core::Call::FromC(call)->is_client(); |
| 2988 |
} |
| 2989 |
|
| 2990 |
grpc_compression_algorithm grpc_call_compression_for_level( |
| 2991 |
grpc_call* call, grpc_compression_level level) { |
| 2992 |
return grpc_core::Call::FromC(call)->compression_for_level(level); |
| 2993 |
} |
| 2994 |
|
| 2995 |
bool grpc_call_is_trailers_only(const grpc_call* call) { |
| 2996 |
return grpc_core::Call::FromC(call)->is_trailers_only(); |
| 2997 |
} |
| 2998 |
|
| 2999 |
int grpc_call_failed_before_recv_message(const grpc_call* c) { |
| 3000 |
return grpc_core::Call::FromC(c)->failed_before_recv_message(); |
| 3001 |
} |
| 3002 |
|
| 3003 |
absl::string_view grpc_call_server_authority(const grpc_call* call) { |
| 3004 |
return grpc_core::Call::FromC(call)->GetServerAuthority(); |
| 3005 |
} |
| 3006 |
|
| 3007 |
const char* grpc_call_error_to_string(grpc_call_error error) { |
| 3008 |
switch (error) { |
| 3009 |
case GRPC_CALL_ERROR: |
| 3010 |
return "GRPC_CALL_ERROR"; |
| 3011 |
case GRPC_CALL_ERROR_ALREADY_ACCEPTED: |
| 3012 |
return "GRPC_CALL_ERROR_ALREADY_ACCEPTED"; |
| 3013 |
case GRPC_CALL_ERROR_ALREADY_FINISHED: |
| 3014 |
return "GRPC_CALL_ERROR_ALREADY_FINISHED"; |
| 3015 |
case GRPC_CALL_ERROR_ALREADY_INVOKED: |
| 3016 |
return "GRPC_CALL_ERROR_ALREADY_INVOKED"; |
| 3017 |
case GRPC_CALL_ERROR_BATCH_TOO_BIG: |
| 3018 |
return "GRPC_CALL_ERROR_BATCH_TOO_BIG"; |
| 3019 |
case GRPC_CALL_ERROR_INVALID_FLAGS: |
| 3020 |
return "GRPC_CALL_ERROR_INVALID_FLAGS"; |
| 3021 |
case GRPC_CALL_ERROR_INVALID_MESSAGE: |
| 3022 |
return "GRPC_CALL_ERROR_INVALID_MESSAGE"; |
| 3023 |
case GRPC_CALL_ERROR_INVALID_METADATA: |
| 3024 |
return "GRPC_CALL_ERROR_INVALID_METADATA"; |
| 3025 |
case GRPC_CALL_ERROR_NOT_INVOKED: |
| 3026 |
return "GRPC_CALL_ERROR_NOT_INVOKED"; |
| 3027 |
case GRPC_CALL_ERROR_NOT_ON_CLIENT: |
| 3028 |
return "GRPC_CALL_ERROR_NOT_ON_CLIENT"; |
| 3029 |
case GRPC_CALL_ERROR_NOT_ON_SERVER: |
| 3030 |
return "GRPC_CALL_ERROR_NOT_ON_SERVER"; |
| 3031 |
case GRPC_CALL_ERROR_NOT_SERVER_COMPLETION_QUEUE: |
| 3032 |
return "GRPC_CALL_ERROR_NOT_SERVER_COMPLETION_QUEUE"; |
| 3033 |
case GRPC_CALL_ERROR_PAYLOAD_TYPE_MISMATCH: |
| 3034 |
return "GRPC_CALL_ERROR_PAYLOAD_TYPE_MISMATCH"; |
| 3035 |
case GRPC_CALL_ERROR_TOO_MANY_OPERATIONS: |
| 3036 |
return "GRPC_CALL_ERROR_TOO_MANY_OPERATIONS"; |
| 3037 |
case GRPC_CALL_ERROR_COMPLETION_QUEUE_SHUTDOWN: |
| 3038 |
return "GRPC_CALL_ERROR_COMPLETION_QUEUE_SHUTDOWN"; |
| 3039 |
case GRPC_CALL_OK: |
| 3040 |
return "GRPC_CALL_OK"; |
| 3041 |
} |
| 3042 |
GPR_UNREACHABLE_CODE(return "GRPC_CALL_ERROR_UNKNOW"); |
| 3043 |
} |