composite_propagator.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // Copyright The OpenTelemetry Authors
  2. // SPDX-License-Identifier: Apache-2.0
  3. #pragma once
  4. #include <memory>
  5. #include <vector>
  6. #include "opentelemetry/context/propagation/text_map_propagator.h"
  7. #include "opentelemetry/version.h"
  8. OPENTELEMETRY_BEGIN_NAMESPACE
  9. namespace context
  10. {
  11. namespace propagation
  12. {
  13. class CompositePropagator : public TextMapPropagator
  14. {
  15. public:
  16. CompositePropagator(std::vector<std::unique_ptr<TextMapPropagator>> propagators)
  17. : propagators_(std::move(propagators))
  18. {}
  19. /**
  20. * Run each of the configured propagators with the given context and carrier.
  21. * Propagators are run in the order they are configured, so if multiple
  22. * propagators write the same carrier key, the propagator later in the list
  23. * will "win".
  24. *
  25. * @param carrier Carrier into which context will be injected
  26. * @param context Context to inject
  27. *
  28. */
  29. void Inject(TextMapCarrier &carrier, const context::Context &context) noexcept override
  30. {
  31. for (auto &p : propagators_)
  32. {
  33. p->Inject(carrier, context);
  34. }
  35. }
  36. /**
  37. * Run each of the configured propagators with the given context and carrier.
  38. * Propagators are run in the order they are configured, so if multiple
  39. * propagators write the same context key, the propagator later in the list
  40. * will "win".
  41. *
  42. * @param carrier Carrier from which to extract context
  43. * @param context Context to add values to
  44. */
  45. context::Context Extract(const TextMapCarrier &carrier,
  46. context::Context &context) noexcept override
  47. {
  48. auto first = true;
  49. context::Context tmp_context;
  50. for (auto &p : propagators_)
  51. {
  52. if (first)
  53. {
  54. tmp_context = p->Extract(carrier, context);
  55. first = false;
  56. }
  57. else
  58. {
  59. tmp_context = p->Extract(carrier, tmp_context);
  60. }
  61. }
  62. return propagators_.size() ? tmp_context : context;
  63. }
  64. /**
  65. * Invoke callback with fields set to carrier by `inject` method for all the
  66. * configured propagators
  67. * Returns true if all invocation return true
  68. */
  69. bool Fields(nostd::function_ref<bool(nostd::string_view)> callback) const noexcept override
  70. {
  71. bool status = true;
  72. for (auto &p : propagators_)
  73. {
  74. status = status && p->Fields(callback);
  75. }
  76. return status;
  77. }
  78. private:
  79. std::vector<std::unique_ptr<TextMapPropagator>> propagators_;
  80. };
  81. } // namespace propagation
  82. } // namespace context
  83. OPENTELEMETRY_END_NAMESPACE