aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/libs/grpc/src/core/lib/channel/channel_args.h
blob: 81a696ca3b60f79e69b5f619e2ad37d26227dd6c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
//
//
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//

#ifndef GRPC_SRC_CORE_LIB_CHANNEL_CHANNEL_ARGS_H
#define GRPC_SRC_CORE_LIB_CHANNEL_CHANNEL_ARGS_H

#include <grpc/support/port_platform.h>

#include <stddef.h>

#include <algorithm>  // IWYU pragma: keep
#include <iosfwd>
#include <memory>
#include <util/generic/string.h>
#include <util/string/cast.h>
#include <type_traits>
#include <utility>

#include "y_absl/meta/type_traits.h"
#include "y_absl/strings/string_view.h"
#include "y_absl/types/optional.h"
#include "y_absl/types/variant.h"

#include <grpc/event_engine/event_engine.h>
#include <grpc/grpc.h>

#include "src/core/lib/avl/avl.h"
#include "src/core/lib/gpr/useful.h"
#include "src/core/lib/gprpp/debug_location.h"
#include "src/core/lib/gprpp/dual_ref_counted.h"
#include "src/core/lib/gprpp/ref_counted.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
#include "src/core/lib/gprpp/time.h"
#include "src/core/lib/surface/channel_stack_type.h"

// TODO(hork): When we're ready to allow setting via a channel arg from the
// application, replace this with a macro in
// include/grpc/impl/codegen/grpc_types.h.
#define GRPC_INTERNAL_ARG_EVENT_ENGINE "grpc.internal.event_engine"

// Channel args are intentionally immutable, to avoid the need for locking.

namespace grpc_core {

// Define a traits object for vtable lookup - allows us to integrate with
// existing code easily (just define the trait!) and allows some magic in
// ChannelArgs to automatically derive a vtable from a T*.
// To participate as a pointer, instances should expose the function:
//   // Gets the vtable for this type
//   static const grpc_arg_pointer_vtable* VTable();
//   // Performs any mutations required for channel args to own a pointer
//   // Only needed if ChannelArgs::Set is to be called with a raw pointer.
//   static void* TakeUnownedPointer(T* p);
template <typename T, typename Ignored = void /* for SFINAE */>
struct ChannelArgTypeTraits;

namespace channel_args_detail {
inline int PointerCompare(void* a_ptr, const grpc_arg_pointer_vtable* a_vtable,
                          void* b_ptr,
                          const grpc_arg_pointer_vtable* b_vtable) {
  int c = QsortCompare(a_ptr, b_ptr);
  if (c == 0) return 0;
  c = QsortCompare(a_vtable, b_vtable);
  if (c != 0) return c;
  return a_vtable->cmp(a_ptr, b_ptr);
}

// The type returned by calling Ref() on a T - used to determine the basest-type
// before the crt refcount base class.
template <typename T>
using RefType = y_absl::remove_cvref_t<decltype(*std::declval<T>().Ref())>;
}  // namespace channel_args_detail

// Specialization for ref-counted pointers.
// Types should expose:
// static int ChannelArgsCompare(const T* a, const T* b);
template <typename T>
struct ChannelArgTypeTraits<
    T, y_absl::enable_if_t<
           std::is_base_of<RefCounted<channel_args_detail::RefType<T>>,
                           channel_args_detail::RefType<T>>::value ||
               std::is_base_of<RefCounted<channel_args_detail::RefType<T>,
                                          NonPolymorphicRefCount>,
                               channel_args_detail::RefType<T>>::value ||
               std::is_base_of<DualRefCounted<channel_args_detail::RefType<T>>,
                               channel_args_detail::RefType<T>>::value,
           void>> {
  static const grpc_arg_pointer_vtable* VTable() {
    static const grpc_arg_pointer_vtable tbl = {
        // copy
        [](void* p) -> void* {
          return p == nullptr ? nullptr
                              : static_cast<T*>(p)
                                    ->Ref(DEBUG_LOCATION, "ChannelArgs copy")
                                    .release();
        },
        // destroy
        [](void* p) {
          if (p != nullptr) {
            static_cast<T*>(p)->Unref(DEBUG_LOCATION, "ChannelArgs destroy");
          }
        },
        // compare
        [](void* p1, void* p2) {
          return T::ChannelArgsCompare(static_cast<const T*>(p1),
                                       static_cast<const T*>(p2));
        },
    };
    return &tbl;
  };
};

// Specialization for shared_ptr
// Incurs an allocation because shared_ptr.release is not a thing.
template <typename T>
struct is_shared_ptr : std::false_type {};
template <typename T>
struct is_shared_ptr<std::shared_ptr<T>> : std::true_type {};
template <typename T>
struct ChannelArgTypeTraits<T,
                            y_absl::enable_if_t<is_shared_ptr<T>::value, void>> {
  static void* TakeUnownedPointer(T* p) { return p; }
  static const grpc_arg_pointer_vtable* VTable() {
    static const grpc_arg_pointer_vtable tbl = {
        // copy
        [](void* p) -> void* { return new T(*static_cast<T*>(p)); },
        // destroy
        [](void* p) { delete static_cast<T*>(p); },
        // compare
        [](void* p1, void* p2) {
          return QsortCompare(static_cast<const T*>(p1)->get(),
                              static_cast<const T*>(p2)->get());
        },
    };
    return &tbl;
  };
};

// If a type declares some member 'struct RawPointerChannelArgTag {}' then
// we automatically generate a vtable for it that does not do any ownership
// management and compares the type by pointer identity.
// This is intended to be relatively ugly because *most types should worry about
// ownership*.
template <typename T>
struct ChannelArgTypeTraits<T,
                            y_absl::void_t<typename T::RawPointerChannelArgTag>> {
  static void* TakeUnownedPointer(T* p) { return p; }
  static const grpc_arg_pointer_vtable* VTable() {
    static const grpc_arg_pointer_vtable tbl = {
        // copy
        [](void* p) -> void* { return p; },
        // destroy
        [](void*) {},
        // compare
        [](void* p1, void* p2) { return QsortCompare(p1, p2); },
    };
    return &tbl;
  };
};

// GetObject support for shared_ptr and RefCountedPtr
template <typename T>
struct WrapInSharedPtr
    : std::integral_constant<
          bool, std::is_base_of<std::enable_shared_from_this<T>, T>::value> {};
template <>
struct WrapInSharedPtr<grpc_event_engine::experimental::EventEngine>
    : std::true_type {};
template <typename T, typename Ignored = void /* for SFINAE */>
struct GetObjectImpl;
// std::shared_ptr implementation
template <typename T>
struct GetObjectImpl<T, y_absl::enable_if_t<WrapInSharedPtr<T>::value, void>> {
  using Result = T*;
  using ReffedResult = std::shared_ptr<T>;
  using StoredType = std::shared_ptr<T>*;
  static Result Get(StoredType p) {
    if (p == nullptr) return nullptr;
    return p->get();
  };
  static ReffedResult GetReffed(StoredType p) {
    if (p == nullptr) return nullptr;
    return ReffedResult(*p);
  };
  static ReffedResult GetReffed(StoredType p,
                                const DebugLocation& /* location */,
                                const char* /* reason */) {
    return GetReffed(*p);
  };
};
// RefCountedPtr
template <typename T>
struct GetObjectImpl<T, y_absl::enable_if_t<!WrapInSharedPtr<T>::value, void>> {
  using Result = T*;
  using ReffedResult = RefCountedPtr<T>;
  using StoredType = Result;
  static Result Get(StoredType p) { return p; };
  static ReffedResult GetReffed(StoredType p) {
    if (p == nullptr) return nullptr;
    return p->Ref();
  };
  static ReffedResult GetReffed(StoredType p, const DebugLocation& location,
                                const char* reason) {
    if (p == nullptr) return nullptr;
    return p->Ref(location, reason);
  };
};

// Provide the canonical name for a type's channel arg key
template <typename T>
struct ChannelArgNameTraits {
  static y_absl::string_view ChannelArgName() { return T::ChannelArgName(); }
};
template <typename T>
struct ChannelArgNameTraits<std::shared_ptr<T>> {
  static y_absl::string_view ChannelArgName() { return T::ChannelArgName(); }
};
// Specialization for the EventEngine
template <>
struct ChannelArgNameTraits<grpc_event_engine::experimental::EventEngine> {
  static y_absl::string_view ChannelArgName() {
    return GRPC_INTERNAL_ARG_EVENT_ENGINE;
  }
};
class ChannelArgs {
 public:
  class Pointer {
   public:
    Pointer(void* p, const grpc_arg_pointer_vtable* vtable);
    ~Pointer() { vtable_->destroy(p_); }

    Pointer(const Pointer& other);
    Pointer& operator=(Pointer other) {
      std::swap(p_, other.p_);
      std::swap(vtable_, other.vtable_);
      return *this;
    }
    Pointer(Pointer&& other) noexcept;
    Pointer& operator=(Pointer&& other) noexcept {
      std::swap(p_, other.p_);
      std::swap(vtable_, other.vtable_);
      return *this;
    }

    friend int QsortCompare(const Pointer& a, const Pointer& b) {
      return channel_args_detail::PointerCompare(a.p_, a.vtable_, b.p_,
                                                 b.vtable_);
    }

    bool operator==(const Pointer& rhs) const {
      return QsortCompare(*this, rhs) == 0;
    }
    bool operator<(const Pointer& rhs) const {
      return QsortCompare(*this, rhs) < 0;
    }
    bool operator!=(const Pointer& rhs) const {
      return QsortCompare(*this, rhs) != 0;
    }

    void* c_pointer() const { return p_; }
    const grpc_arg_pointer_vtable* c_vtable() const { return vtable_; }

   private:
    static const grpc_arg_pointer_vtable* EmptyVTable();

    void* p_;
    const grpc_arg_pointer_vtable* vtable_;
  };

  using Value = y_absl::variant<int, TString, Pointer>;

  struct ChannelArgsDeleter {
    void operator()(const grpc_channel_args* p) const;
  };
  using CPtr =
      std::unique_ptr<const grpc_channel_args, ChannelArgs::ChannelArgsDeleter>;

  ChannelArgs();
  ~ChannelArgs();
  ChannelArgs(const ChannelArgs&);
  ChannelArgs& operator=(const ChannelArgs&);
  ChannelArgs(ChannelArgs&&) noexcept;
  ChannelArgs& operator=(ChannelArgs&&) noexcept;

  static ChannelArgs FromC(const grpc_channel_args* args);
  static ChannelArgs FromC(const grpc_channel_args& args) {
    return FromC(&args);
  }
  // Construct a new grpc_channel_args struct.
  CPtr ToC() const;

  // Returns the union of this channel args with other.
  // If a key is present in both, the value from this is used.
  GRPC_MUST_USE_RESULT ChannelArgs UnionWith(ChannelArgs other) const;

  const Value* Get(y_absl::string_view name) const;
  GRPC_MUST_USE_RESULT ChannelArgs Set(y_absl::string_view name,
                                       Pointer value) const;
  GRPC_MUST_USE_RESULT ChannelArgs Set(y_absl::string_view name, int value) const;
  GRPC_MUST_USE_RESULT ChannelArgs Set(y_absl::string_view name,
                                       y_absl::string_view value) const;
  GRPC_MUST_USE_RESULT ChannelArgs Set(y_absl::string_view name,
                                       TString value) const;
  GRPC_MUST_USE_RESULT ChannelArgs Set(y_absl::string_view name,
                                       const char* value) const;
  GRPC_MUST_USE_RESULT ChannelArgs Set(grpc_arg arg) const;
  template <typename T>
  GRPC_MUST_USE_RESULT y_absl::enable_if_t<
      std::is_same<const grpc_arg_pointer_vtable*,
                   decltype(ChannelArgTypeTraits<T>::VTable())>::value,
      ChannelArgs>
  Set(y_absl::string_view name, T* value) const {
    return Set(name, Pointer(ChannelArgTypeTraits<T>::TakeUnownedPointer(value),
                             ChannelArgTypeTraits<T>::VTable()));
  }
  template <typename T>
  GRPC_MUST_USE_RESULT auto Set(y_absl::string_view name,
                                RefCountedPtr<T> value) const
      -> y_absl::enable_if_t<
          std::is_same<const grpc_arg_pointer_vtable*,
                       decltype(ChannelArgTypeTraits<
                                y_absl::remove_cvref_t<T>>::VTable())>::value,
          ChannelArgs> {
    return Set(
        name, Pointer(value.release(),
                      ChannelArgTypeTraits<y_absl::remove_cvref_t<T>>::VTable()));
  }
  template <typename T>
  GRPC_MUST_USE_RESULT y_absl::enable_if_t<
      std::is_same<
          const grpc_arg_pointer_vtable*,
          decltype(ChannelArgTypeTraits<std::shared_ptr<T>>::VTable())>::value,
      ChannelArgs>
  Set(y_absl::string_view name, std::shared_ptr<T> value) const {
    auto* store_value = new std::shared_ptr<T>(value);
    return Set(
        name,
        Pointer(ChannelArgTypeTraits<std::shared_ptr<T>>::TakeUnownedPointer(
                    store_value),
                ChannelArgTypeTraits<std::shared_ptr<T>>::VTable()));
  }
  template <typename T>
  GRPC_MUST_USE_RESULT ChannelArgs SetIfUnset(y_absl::string_view name,
                                              T value) const {
    if (Contains(name)) return *this;
    return Set(name, std::move(value));
  }
  GRPC_MUST_USE_RESULT ChannelArgs Remove(y_absl::string_view name) const;
  bool Contains(y_absl::string_view name) const;

  template <typename T>
  bool ContainsObject() const {
    return Get(ChannelArgNameTraits<T>::ChannelArgName()) != nullptr;
  }

  y_absl::optional<int> GetInt(y_absl::string_view name) const;
  y_absl::optional<y_absl::string_view> GetString(y_absl::string_view name) const;
  y_absl::optional<TString> GetOwnedString(y_absl::string_view name) const;
  void* GetVoidPointer(y_absl::string_view name) const;
  template <typename T>
  typename GetObjectImpl<T>::StoredType GetPointer(
      y_absl::string_view name) const {
    return static_cast<typename GetObjectImpl<T>::StoredType>(
        GetVoidPointer(name));
  }
  y_absl::optional<Duration> GetDurationFromIntMillis(
      y_absl::string_view name) const;
  y_absl::optional<bool> GetBool(y_absl::string_view name) const;

  // Object based get/set.
  // Deal with the common case that we set a pointer to an object under
  // the same name in every usage.
  // Expects ChannelArgTypeTraits to exist for T, and T to expose:
  //   static string_view ChannelArgName();
  template <typename T>
  GRPC_MUST_USE_RESULT ChannelArgs SetObject(T* p) const {
    return Set(T::ChannelArgName(), p);
  }
  template <typename T>
  GRPC_MUST_USE_RESULT ChannelArgs SetObject(RefCountedPtr<T> p) const {
    return Set(T::ChannelArgName(), std::move(p));
  }
  template <typename T>
  GRPC_MUST_USE_RESULT ChannelArgs SetObject(std::shared_ptr<T> p) const {
    return Set(ChannelArgNameTraits<T>::ChannelArgName(), std::move(p));
  }
  template <typename T>
  typename GetObjectImpl<T>::Result GetObject() const {
    return GetObjectImpl<T>::Get(
        GetPointer<T>(ChannelArgNameTraits<T>::ChannelArgName()));
  }
  template <typename T>
  typename GetObjectImpl<T>::ReffedResult GetObjectRef() const {
    return GetObjectImpl<T>::GetReffed(
        GetPointer<T>(ChannelArgNameTraits<T>::ChannelArgName()));
  }
  template <typename T>
  typename GetObjectImpl<T>::ReffedResult GetObjectRef(
      const DebugLocation& location, const char* reason) const {
    return GetObjectImpl<T>::GetReffed(
        GetPointer<T>(ChannelArgNameTraits<T>::ChannelArgName()), location,
        reason);
  }

  bool operator!=(const ChannelArgs& other) const;
  bool operator<(const ChannelArgs& other) const;
  bool operator==(const ChannelArgs& other) const;

  // Helpers for commonly accessed things

  bool WantMinimalStack() const;
  TString ToString() const;

 private:
  explicit ChannelArgs(AVL<TString, Value> args);

  GRPC_MUST_USE_RESULT ChannelArgs Set(y_absl::string_view name,
                                       Value value) const;

  AVL<TString, Value> args_;
};

std::ostream& operator<<(std::ostream& out, const ChannelArgs& args);

}  // namespace grpc_core

/// Copy the arguments in \a src into a new instance
grpc_channel_args* grpc_channel_args_copy(const grpc_channel_args* src);

/// Copy the arguments in \a src into a new instance, stably sorting keys
grpc_channel_args* grpc_channel_args_normalize(const grpc_channel_args* src);

/// Copy the arguments in \a src and append \a to_add. If \a to_add is NULL, it
/// is equivalent to calling \a grpc_channel_args_copy.
grpc_channel_args* grpc_channel_args_copy_and_add(const grpc_channel_args* src,
                                                  const grpc_arg* to_add,
                                                  size_t num_to_add);

/// Copies the arguments in \a src except for those whose keys are in
/// \a to_remove.
grpc_channel_args* grpc_channel_args_copy_and_remove(
    const grpc_channel_args* src, const char** to_remove, size_t num_to_remove);

/// Copies the arguments from \a src except for those whose keys are in
/// \a to_remove and appends the arguments in \a to_add.
grpc_channel_args* grpc_channel_args_copy_and_add_and_remove(
    const grpc_channel_args* src, const char** to_remove, size_t num_to_remove,
    const grpc_arg* to_add, size_t num_to_add);

/// Perform the union of \a a and \a b, prioritizing \a a entries
grpc_channel_args* grpc_channel_args_union(const grpc_channel_args* a,
                                           const grpc_channel_args* b);

/// Destroy arguments created by \a grpc_channel_args_copy
void grpc_channel_args_destroy(grpc_channel_args* a);
inline void grpc_channel_args_destroy(const grpc_channel_args* a) {
  grpc_channel_args_destroy(const_cast<grpc_channel_args*>(a));
}

int grpc_channel_args_compare(const grpc_channel_args* a,
                              const grpc_channel_args* b);

/// Returns the value of argument \a name from \a args, or NULL if not found.
const grpc_arg* grpc_channel_args_find(const grpc_channel_args* args,
                                       const char* name);

bool grpc_channel_args_want_minimal_stack(const grpc_channel_args* args);

typedef struct grpc_integer_options {
  int default_value;  // Return this if value is outside of expected bounds.
  int min_value;
  int max_value;
} grpc_integer_options;

/// Returns the value of \a arg, subject to the constraints in \a options.
int grpc_channel_arg_get_integer(const grpc_arg* arg,
                                 const grpc_integer_options options);
/// Similar to the above, but needs to find the arg from \a args by the name
/// first.
int grpc_channel_args_find_integer(const grpc_channel_args* args,
                                   const char* name,
                                   const grpc_integer_options options);

/// Returns the value of \a arg if \a arg is of type GRPC_ARG_STRING.
/// Otherwise, emits a warning log, and returns nullptr.
/// If arg is nullptr, returns nullptr, and does not emit a warning.
char* grpc_channel_arg_get_string(const grpc_arg* arg);
/// Similar to the above, but needs to find the arg from \a args by the name
/// first.
char* grpc_channel_args_find_string(const grpc_channel_args* args,
                                    const char* name);
/// If \a arg is of type GRPC_ARG_INTEGER, returns true if it's non-zero.
/// Returns \a default_value if \a arg is of other types.
bool grpc_channel_arg_get_bool(const grpc_arg* arg, bool default_value);
/// Similar to the above, but needs to find the arg from \a args by the name
/// first.
bool grpc_channel_args_find_bool(const grpc_channel_args* args,
                                 const char* name, bool default_value);

template <typename T>
T* grpc_channel_args_find_pointer(const grpc_channel_args* args,
                                  const char* name) {
  const grpc_arg* arg = grpc_channel_args_find(args, name);
  if (arg == nullptr || arg->type != GRPC_ARG_POINTER) return nullptr;
  return static_cast<T*>(arg->value.pointer.p);
}

// Helpers for creating channel args.
grpc_arg grpc_channel_arg_string_create(char* name, char* value);
grpc_arg grpc_channel_arg_integer_create(char* name, int value);
grpc_arg grpc_channel_arg_pointer_create(char* name, void* value,
                                         const grpc_arg_pointer_vtable* vtable);

// Returns a string representing channel args in human-readable form.
TString grpc_channel_args_string(const grpc_channel_args* args);

namespace grpc_core {
// Ensure no duplicate channel args (with some backwards compatibility hacks).
// Eliminate any grpc.internal.* args.
// Return a C++ object.
ChannelArgs ChannelArgsBuiltinPrecondition(const grpc_channel_args* src);
}  // namespace grpc_core

// Takes ownership of the old_args
typedef grpc_core::ChannelArgs (
    *grpc_channel_args_client_channel_creation_mutator)(
    const char* target, const grpc_core::ChannelArgs& old_args,
    grpc_channel_stack_type type);

// Should be called only once globaly before grpc is init'ed.
void grpc_channel_args_set_client_channel_creation_mutator(
    grpc_channel_args_client_channel_creation_mutator cb);
// This will be called at the creation of each channel.
grpc_channel_args_client_channel_creation_mutator
grpc_channel_args_get_client_channel_creation_mutator();

#endif  // GRPC_SRC_CORE_LIB_CHANNEL_CHANNEL_ARGS_H