diff --git a/bazel/abseil.patch b/bazel/abseil.patch new file mode 100644 index 0000000000000..d52556466e6fe --- /dev/null +++ b/bazel/abseil.patch @@ -0,0 +1,42 @@ +# Force internal versions of std classes per +# https://abseil.io/docs/cpp/guides/options +diff --git a/absl/base/options.h b/absl/base/options.h +index 230bf1e..6e1b9e5 100644 +--- a/absl/base/options.h ++++ b/absl/base/options.h +@@ -100,7 +100,7 @@ + // User code should not inspect this macro. To check in the preprocessor if + // absl::any is a typedef of std::any, use the feature macro ABSL_USES_STD_ANY. + +-#define ABSL_OPTION_USE_STD_ANY 2 ++#define ABSL_OPTION_USE_STD_ANY 0 + + + // ABSL_OPTION_USE_STD_OPTIONAL +@@ -127,7 +127,7 @@ + // absl::optional is a typedef of std::optional, use the feature macro + // ABSL_USES_STD_OPTIONAL. + +-#define ABSL_OPTION_USE_STD_OPTIONAL 2 ++#define ABSL_OPTION_USE_STD_OPTIONAL 0 + + + // ABSL_OPTION_USE_STD_STRING_VIEW +@@ -154,7 +154,7 @@ + // absl::string_view is a typedef of std::string_view, use the feature macro + // ABSL_USES_STD_STRING_VIEW. + +-#define ABSL_OPTION_USE_STD_STRING_VIEW 2 ++#define ABSL_OPTION_USE_STD_STRING_VIEW 0 + + // ABSL_OPTION_USE_STD_VARIANT + // +@@ -180,7 +180,7 @@ + // absl::variant is a typedef of std::variant, use the feature macro + // ABSL_USES_STD_VARIANT. + +-#define ABSL_OPTION_USE_STD_VARIANT 2 ++#define ABSL_OPTION_USE_STD_VARIANT 0 + + + // ABSL_OPTION_USE_INLINE_NAMESPACE diff --git a/bazel/repositories.bzl b/bazel/repositories.bzl index 89ce847384d32..e975f1cf0049e 100644 --- a/bazel/repositories.bzl +++ b/bazel/repositories.bzl @@ -516,7 +516,11 @@ def _com_google_googletest(): # pull in more bits of abseil as needed, and is now the preferred # method for pure Bazel deps. def _com_google_absl(): - external_http_archive("com_google_absl") + external_http_archive( + name = "com_google_absl", + patches = ["@envoy//bazel:abseil.patch"], + patch_args = ["-p1"], + ) native.bind( name = "abseil_any", actual = "@com_google_absl//absl/types:any", diff --git a/source/common/common/stl_helpers.h b/source/common/common/stl_helpers.h index 080edc43c4c7a..674372f64eaa1 100644 --- a/source/common/common/stl_helpers.h +++ b/source/common/common/stl_helpers.h @@ -34,6 +34,19 @@ std::string accumulateToString(const ContainerT& source, }) + "]"; } + +// Used for converting sanctioned uses of std string_view (e.g. extensions) to absl::string_view +// for internal use. +inline absl::string_view toAbslStringView(std::string_view view) { // NOLINT(std::string_view) + return absl::string_view(view.data(), view.size()); // NOLINT(std::string_view) +} + +// Used for converting internal absl::string_view to sanctioned uses of std string_view (e.g. +// extensions). +inline std::string_view toStdStringView(absl::string_view view) { // NOLINT(std::string_view) + return std::string_view(view.data(), view.size()); // NOLINT(std::string_view) +} + } // namespace Envoy // NOLINT(namespace-envoy) diff --git a/source/common/config/context_provider_impl.h b/source/common/config/context_provider_impl.h index 030d2bc3f1a85..3123b2066cef4 100644 --- a/source/common/config/context_provider_impl.h +++ b/source/common/config/context_provider_impl.h @@ -3,6 +3,7 @@ #include "envoy/config/context_provider.h" #include "source/common/common/callback_impl.h" +#include "source/common/common/stl_helpers.h" #include "source/common/common/thread.h" #include "source/common/config/xds_context_params.h" @@ -29,13 +30,16 @@ class ContextProviderImpl : public ContextProvider { void setDynamicContextParam(absl::string_view resource_type_url, absl::string_view key, absl::string_view value) override { ASSERT(Thread::MainThread::isMainThread()); - (*dynamic_context_[resource_type_url].mutable_params())[key] = value; + (*dynamic_context_[resource_type_url] + .mutable_params())[toStdStringView(key)] = // NOLINT(std::string_view) + toStdStringView(value); // NOLINT(std::string_view) update_cb_helper_.runCallbacks(resource_type_url); } void unsetDynamicContextParam(absl::string_view resource_type_url, absl::string_view key) override { ASSERT(Thread::MainThread::isMainThread()); - dynamic_context_[resource_type_url].mutable_params()->erase(key); + dynamic_context_[resource_type_url].mutable_params()->erase( + toStdStringView(key)); // NOLINT(std::string_view) update_cb_helper_.runCallbacks(resource_type_url); } ABSL_MUST_USE_RESULT Common::CallbackHandlePtr diff --git a/source/common/formatter/substitution_formatter.cc b/source/common/formatter/substitution_formatter.cc index 0d13ec9600323..1d4c080994137 100644 --- a/source/common/formatter/substitution_formatter.cc +++ b/source/common/formatter/substitution_formatter.cc @@ -415,7 +415,7 @@ FormatterProviderPtr SubstitutionFormatParser::parseBuiltinCommand(const std::st } if (serialize_type.empty()) { - serialize_type = TYPED_SERIALIZATION; + serialize_type = std::string(TYPED_SERIALIZATION); } if (serialize_type != PLAIN_SERIALIZATION && serialize_type != TYPED_SERIALIZATION) { throw EnvoyException("Invalid filter state serialize type, only support PLAIN/TYPED."); diff --git a/source/common/formatter/substitution_formatter.h b/source/common/formatter/substitution_formatter.h index a086359058218..ebe4752d1a56c 100644 --- a/source/common/formatter/substitution_formatter.h +++ b/source/common/formatter/substitution_formatter.h @@ -81,13 +81,15 @@ class SubstitutionFormatParser { if constexpr (std::is_same_v::type, std::string>) { // Compile time handler for std::string. - param = *it; + param = std::string(*it); it++; } else { // Compile time handler for container type. It will catch all remaining tokens and // move iterator to the end. - param.insert(param.begin(), it, tokens.end()); - it = tokens.end(); + do { + param.push_back(std::string(*it)); + it++; + } while (it != tokens.end()); } } }(params), diff --git a/source/common/json/json_internal.cc b/source/common/json/json_internal.cc index b4afc8ef10041..ce6138d870ad0 100644 --- a/source/common/json/json_internal.cc +++ b/source/common/json/json_internal.cc @@ -209,7 +209,7 @@ class ObjectHandler : public nlohmann::json_sax { "documentation in case error string changed."); } else { // Extract portion after ": " to get error string. - error_ = error.substr(end + 2); + error_ = std::string(error.substr(end + 2)); // Extract position information if present. auto start = error.find("at "); if (start != std::string::npos && (start + 3) < end) { diff --git a/source/common/local_info/local_info_impl.h b/source/common/local_info/local_info_impl.h index 1d583c14e8231..6280d782088c7 100644 --- a/source/common/local_info/local_info_impl.h +++ b/source/common/local_info/local_info_impl.h @@ -55,8 +55,9 @@ class LocalInfoImpl : public LocalInfo { zone_stat_name_(zone_stat_name_storage_.statName()), dynamic_update_callback_handle_(context_provider_.addDynamicContextUpdateCallback( [this](absl::string_view resource_type_url) { - (*node_.mutable_dynamic_parameters())[resource_type_url].CopyFrom( - context_provider_.dynamicContext(resource_type_url)); + (*node_.mutable_dynamic_parameters()) + [toStdStringView(resource_type_url)] // NOLINT(std::string_view) + .CopyFrom(context_provider_.dynamicContext(resource_type_url)); })) {} Network::Address::InstanceConstSharedPtr address() const override { return address_; } diff --git a/source/common/stats/tag_extractor_impl.cc b/source/common/stats/tag_extractor_impl.cc index 0756995c30695..752bcf73af61a 100644 --- a/source/common/stats/tag_extractor_impl.cc +++ b/source/common/stats/tag_extractor_impl.cc @@ -136,7 +136,7 @@ bool TagExtractorStdRegexImpl::extractTag(TagExtractionContext& context, std::ve TagExtractorRe2Impl::TagExtractorRe2Impl(absl::string_view name, absl::string_view regex, absl::string_view substr) - : TagExtractorImplBase(name, regex, substr), regex_(regex) {} + : TagExtractorImplBase(name, regex, substr), regex_(std::string(regex)) {} bool TagExtractorRe2Impl::extractTag(TagExtractionContext& context, std::vector& tags, IntervalSet& remove_characters) const { @@ -186,7 +186,7 @@ TagExtractorTokensImpl::TagExtractorTokensImpl(absl::string_view name, absl::str if (!tokens_.empty()) { const absl::string_view first = tokens_[0]; if (first != "$" && first != "*" && first != "**") { - prefix_ = first; + prefix_ = std::string(first); } } } @@ -236,7 +236,7 @@ bool TagExtractorTokensImpl::extractTag(TagExtractionContext& context, std::vect } else if (start > 0) { --start; // Remove the dot prior to the lat token, e.g. ".ef" } - addTag(tags) = tag_value; + addTag(tags) = std::string(tag_value); remove_characters.insert(start, end); PERF_RECORD(perf, "tokens-match", name_); diff --git a/source/common/stream_info/stream_info_impl.h b/source/common/stream_info/stream_info_impl.h index 537596f06b2d5..633178d2c361b 100644 --- a/source/common/stream_info/stream_info_impl.h +++ b/source/common/stream_info/stream_info_impl.h @@ -285,7 +285,7 @@ struct StreamInfoImpl : public StreamInfo { absl::optional connectionID() const override { return connection_id_; } void setFilterChainName(absl::string_view filter_chain_name) override { - filter_chain_name_ = filter_chain_name; + filter_chain_name_ = std::string(filter_chain_name); } const std::string& filterChainName() const override { return filter_chain_name_; } diff --git a/source/extensions/common/wasm/context.cc b/source/extensions/common/wasm/context.cc index 34db41d71e7f0..4591f9d2a177b 100644 --- a/source/extensions/common/wasm/context.cc +++ b/source/extensions/common/wasm/context.cc @@ -117,21 +117,21 @@ WasmResult Buffer::copyTo(WasmBase* wasm, size_t start, size_t length, uint64_t return proxy_wasm::BufferBase::copyTo(wasm, start, length, ptr_ptr, size_ptr); } -WasmResult Buffer::copyFrom(size_t start, size_t length, absl::string_view data) { +WasmResult Buffer::copyFrom(size_t start, size_t length, std::string_view data) { if (buffer_instance_) { if (start == 0) { if (length == 0) { - buffer_instance_->prepend(data); + buffer_instance_->prepend(toAbslStringView(data)); return WasmResult::Ok; } else if (length >= buffer_instance_->length()) { buffer_instance_->drain(buffer_instance_->length()); - buffer_instance_->add(data); + buffer_instance_->add(toAbslStringView(data)); return WasmResult::Ok; } else { return WasmResult::BadArgument; } } else if (start >= buffer_instance_->length()) { - buffer_instance_->add(data); + buffer_instance_->add(toAbslStringView(data)); return WasmResult::Ok; } else { return WasmResult::BadArgument; @@ -156,7 +156,7 @@ Plugin* Context::plugin() const { return static_cast(plugin_.get()); } Context* Context::rootContext() const { return static_cast(root_context()); } Upstream::ClusterManager& Context::clusterManager() const { return wasm()->clusterManager(); } -void Context::error(absl::string_view message) { ENVOY_LOG(trace, message); } +void Context::error(std::string_view message) { ENVOY_LOG(trace, message); } uint64_t Context::getCurrentTimeNanoseconds() { return std::chrono::duration_cast( @@ -564,9 +564,9 @@ Context::findValue(absl::string_view name, Protobuf::Arena* arena, bool last) co } break; case PropertyToken::PLUGIN_ROOT_ID: - return CelValue::CreateStringView(root_id()); + return CelValue::CreateStringView(toAbslStringView(root_id())); case PropertyToken::PLUGIN_VM_ID: - return CelValue::CreateStringView(wasm()->vm_id()); + return CelValue::CreateStringView(toAbslStringView(wasm()->vm_id())); case PropertyToken::FILTER_STATE: return Protobuf::Arena::Create(arena, info->filterState()) @@ -575,7 +575,7 @@ Context::findValue(absl::string_view name, Protobuf::Arena* arena, bool last) co return {}; } -WasmResult Context::getProperty(absl::string_view path, std::string* result) { +WasmResult Context::getProperty(std::string_view path, std::string* result) { using google::api::expr::runtime::CelValue; bool first = true; @@ -598,14 +598,14 @@ WasmResult Context::getProperty(absl::string_view path, std::string* result) { if (first) { // top-level identifier first = false; - auto top_value = findValue(part, &arena, start >= path.size()); + auto top_value = findValue(toAbslStringView(part), &arena, start >= path.size()); if (!top_value.has_value()) { return WasmResult::NotFound; } value = top_value.value(); } else if (value.IsMap()) { auto& map = *value.MapOrDie(); - auto field = map[CelValue::CreateStringView(part)]; + auto field = map[CelValue::CreateStringView(toAbslStringView(part))]; if (!field.has_value()) { return WasmResult::NotFound; } @@ -638,7 +638,7 @@ WasmResult Context::getProperty(absl::string_view path, std::string* result) { } else if (value.IsList()) { auto& list = *value.ListOrDie(); int idx = 0; - if (!absl::SimpleAtoi(part, &idx)) { + if (!absl::SimpleAtoi(toAbslStringView(part), &idx)) { return WasmResult::NotFound; } if (idx < 0 || idx >= list.size()) { @@ -719,8 +719,8 @@ const Http::HeaderMap* Context::getConstMap(WasmHeaderMapType type) { NOT_REACHED_GCOVR_EXCL_LINE; } -WasmResult Context::addHeaderMapValue(WasmHeaderMapType type, absl::string_view key, - absl::string_view value) { +WasmResult Context::addHeaderMapValue(WasmHeaderMapType type, std::string_view key, + std::string_view value) { auto map = getMap(type); if (!map) { return WasmResult::BadArgument; @@ -733,8 +733,8 @@ WasmResult Context::addHeaderMapValue(WasmHeaderMapType type, absl::string_view return WasmResult::Ok; } -WasmResult Context::getHeaderMapValue(WasmHeaderMapType type, absl::string_view key, - absl::string_view* value) { +WasmResult Context::getHeaderMapValue(WasmHeaderMapType type, std::string_view key, + std::string_view* value) { auto map = getConstMap(type); if (!map) { if (access_log_phase_) { @@ -761,7 +761,7 @@ WasmResult Context::getHeaderMapValue(WasmHeaderMapType type, absl::string_view } // TODO(kyessenov, PiotrSikora): This needs to either return a concatenated list of values, or // the ABI needs to be changed to return multiple values. This is a potential security issue. - *value = entry[0]->value().getStringView(); + *value = toStdStringView(entry[0]->value().getStringView()); return WasmResult::Ok; } @@ -772,7 +772,8 @@ Pairs headerMapToPairs(const Http::HeaderMap* map) { Pairs pairs; pairs.reserve(map->size()); map->iterate([&pairs](const Http::HeaderEntry& header) -> Http::HeaderMap::Iterate { - pairs.push_back(std::make_pair(header.key().getStringView(), header.value().getStringView())); + pairs.push_back(std::make_pair(toStdStringView(header.key().getStringView()), + toStdStringView(header.value().getStringView()))); return Http::HeaderMap::Iterate::Continue; }); return pairs; @@ -807,7 +808,7 @@ WasmResult Context::setHeaderMapPairs(WasmHeaderMapType type, const Pairs& pairs return WasmResult::Ok; } -WasmResult Context::removeHeaderMapValue(WasmHeaderMapType type, absl::string_view key) { +WasmResult Context::removeHeaderMapValue(WasmHeaderMapType type, std::string_view key) { auto map = getMap(type); if (!map) { return WasmResult::BadArgument; @@ -820,14 +821,14 @@ WasmResult Context::removeHeaderMapValue(WasmHeaderMapType type, absl::string_vi return WasmResult::Ok; } -WasmResult Context::replaceHeaderMapValue(WasmHeaderMapType type, absl::string_view key, - absl::string_view value) { +WasmResult Context::replaceHeaderMapValue(WasmHeaderMapType type, std::string_view key, + std::string_view value) { auto map = getMap(type); if (!map) { return WasmResult::BadArgument; } const Http::LowerCaseString lower_key{std::string(key)}; - map->setCopy(lower_key, value); + map->setCopy(lower_key, toAbslStringView(value)); if (type == WasmHeaderMapType::RequestHeaders) { decoder_callbacks_->clearRouteCache(); } @@ -885,8 +886,8 @@ BufferInterface* Context::getBuffer(WasmBufferType type) { response = rootContext()->http_call_response_; if (response) { auto& body = (*response)->body(); - return buffer_.set(absl::string_view(static_cast(body.linearize(body.length())), - body.length())); + return buffer_.set( + std::string_view(static_cast(body.linearize(body.length())), body.length())); } return nullptr; case WasmBufferType::GrpcReceiveBuffer: @@ -926,8 +927,8 @@ uint32_t Context::nextHttpCallToken() { } // Async call via HTTP -WasmResult Context::httpCall(absl::string_view cluster, const Pairs& request_headers, - absl::string_view request_body, const Pairs& request_trailers, +WasmResult Context::httpCall(std::string_view cluster, const Pairs& request_headers, + std::string_view request_body, const Pairs& request_trailers, int timeout_milliseconds, uint32_t* token_ptr) { if (timeout_milliseconds < 0) { return WasmResult::BadArgument; @@ -948,7 +949,7 @@ WasmResult Context::httpCall(absl::string_view cluster, const Pairs& request_hea } if (!request_body.empty()) { - message->body().add(request_body); + message->body().add(toAbslStringView(request_body)); message->headers().setContentLength(request_body.size()); } @@ -999,9 +1000,9 @@ uint32_t Context::nextGrpcCallToken() { return token; } -WasmResult Context::grpcCall(absl::string_view grpc_service, absl::string_view service_name, - absl::string_view method_name, const Pairs& initial_metadata, - absl::string_view request, std::chrono::milliseconds timeout, +WasmResult Context::grpcCall(std::string_view grpc_service, std::string_view service_name, + std::string_view method_name, const Pairs& initial_metadata, + std::string_view request, std::chrono::milliseconds timeout, uint32_t* token_ptr) { GrpcService service_proto; if (!service_proto.ParseFromArray(grpc_service.data(), grpc_service.size())) { @@ -1037,9 +1038,10 @@ WasmResult Context::grpcCall(absl::string_view grpc_service, absl::string_view s hash_policy.Add()->mutable_header()->set_header_name(Http::Headers::get().Host.get()); options.setHashPolicy(hash_policy); - auto grpc_request = grpc_client->sendRaw(service_name, method_name, - std::make_unique<::Envoy::Buffer::OwnedImpl>(request), - handler, Tracing::NullSpan::instance(), options); + auto grpc_request = + grpc_client->sendRaw(toAbslStringView(service_name), toAbslStringView(method_name), + std::make_unique<::Envoy::Buffer::OwnedImpl>(toAbslStringView(request)), + handler, Tracing::NullSpan::instance(), options); if (!grpc_request) { grpc_call_request_.erase(token); return WasmResult::InternalFailure; @@ -1070,8 +1072,8 @@ uint32_t Context::nextGrpcStreamToken() { return token; } -WasmResult Context::grpcStream(absl::string_view grpc_service, absl::string_view service_name, - absl::string_view method_name, const Pairs& initial_metadata, +WasmResult Context::grpcStream(std::string_view grpc_service, std::string_view service_name, + std::string_view method_name, const Pairs& initial_metadata, uint32_t* token_ptr) { GrpcService service_proto; if (!service_proto.ParseFromArray(grpc_service.data(), grpc_service.size())) { @@ -1106,7 +1108,8 @@ WasmResult Context::grpcStream(absl::string_view grpc_service, absl::string_view hash_policy.Add()->mutable_header()->set_header_name(Http::Headers::get().Host.get()); options.setHashPolicy(hash_policy); - auto grpc_stream = grpc_client->startRaw(service_name, method_name, handler, options); + auto grpc_stream = grpc_client->startRaw(toAbslStringView(service_name), + toAbslStringView(method_name), handler, options); if (!grpc_stream) { grpc_stream_.erase(token); return WasmResult::InternalFailure; @@ -1169,18 +1172,18 @@ const Network::Connection* Context::getConnection() const { return nullptr; } -WasmResult Context::setProperty(absl::string_view path, absl::string_view value) { +WasmResult Context::setProperty(std::string_view path, std::string_view value) { auto* stream_info = getRequestStreamInfo(); if (!stream_info) { return WasmResult::NotFound; } std::string key; - absl::StrAppend(&key, CelStateKeyPrefix, path); + absl::StrAppend(&key, CelStateKeyPrefix, toAbslStringView(path)); CelState* state; if (stream_info->filterState()->hasData(key)) { state = &stream_info->filterState()->getDataMutable(key); } else { - const auto& it = rootContext()->state_prototypes_.find(path); + const auto& it = rootContext()->state_prototypes_.find(toAbslStringView(path)); const CelStatePrototype& prototype = it == rootContext()->state_prototypes_.end() ? Filters::Common::Expr::DefaultCelStatePrototype::get() @@ -1191,24 +1194,24 @@ WasmResult Context::setProperty(absl::string_view path, absl::string_view value) StreamInfo::FilterState::StateType::Mutable, prototype.life_span_); } - if (!state->setValue(value)) { + if (!state->setValue(toAbslStringView(value))) { return WasmResult::BadArgument; } return WasmResult::Ok; } WasmResult -Context::declareProperty(absl::string_view path, +Context::declareProperty(std::string_view path, Filters::Common::Expr::CelStatePrototypeConstPtr state_prototype) { // Do not delete existing schema since it can be referenced by state objects. - if (state_prototypes_.find(path) == state_prototypes_.end()) { - state_prototypes_[path] = std::move(state_prototype); + if (state_prototypes_.find(toAbslStringView(path)) == state_prototypes_.end()) { + state_prototypes_[toAbslStringView(path)] = std::move(state_prototype); return WasmResult::Ok; } return WasmResult::BadArgument; } -WasmResult Context::log(uint32_t level, absl::string_view message) { +WasmResult Context::log(uint32_t level, std::string_view message) { switch (static_cast(level)) { case spdlog::level::trace: ENVOY_LOG(trace, "wasm log{}: {}", log_prefix(), message); @@ -1242,7 +1245,7 @@ uint32_t Context::getLogLevel() { // // Calls into the Wasm code. // -bool Context::validateConfiguration(absl::string_view configuration, +bool Context::validateConfiguration(std::string_view configuration, const std::shared_ptr& plugin_base) { auto plugin = std::static_pointer_cast(plugin_base); if (!wasm()->validate_configuration_) { @@ -1257,7 +1260,7 @@ bool Context::validateConfiguration(absl::string_view configuration, return result; } -absl::string_view Context::getConfiguration() { +std::string_view Context::getConfiguration() { if (temp_plugin_) { return temp_plugin_->plugin_configuration_; } else { @@ -1265,8 +1268,8 @@ absl::string_view Context::getConfiguration() { } }; -std::pair Context::getStatus() { - return std::make_pair(status_code_, status_message_); +std::pair Context::getStatus() { + return std::make_pair(status_code_, toStdStringView(status_message_)); } void Context::onGrpcReceiveInitialMetadataWrapper(uint32_t token, Http::HeaderMapPtr&& metadata) { @@ -1281,14 +1284,14 @@ void Context::onGrpcReceiveTrailingMetadataWrapper(uint32_t token, Http::HeaderM grpc_receive_trailing_metadata_ = nullptr; } -WasmResult Context::defineMetric(uint32_t metric_type, absl::string_view name, +WasmResult Context::defineMetric(uint32_t metric_type, std::string_view name, uint32_t* metric_id_ptr) { if (metric_type > static_cast(MetricType::Max)) { return WasmResult::BadArgument; } auto type = static_cast(metric_type); // TODO: Consider rethinking the scoping policy as it does not help in this case. - Stats::StatNameManagedStorage storage(name, wasm()->scope_->symbolTable()); + Stats::StatNameManagedStorage storage(toAbslStringView(name), wasm()->scope_->symbolTable()); Stats::StatName stat_name = storage.statName(); if (type == MetricType::Counter) { auto id = wasm()->nextCounterMetricId(); @@ -1655,9 +1658,9 @@ void Context::failStream(WasmStreamType stream_type) { } } -WasmResult Context::sendLocalResponse(uint32_t response_code, absl::string_view body_text, +WasmResult Context::sendLocalResponse(uint32_t response_code, std::string_view body_text, Pairs additional_headers, uint32_t grpc_status, - absl::string_view details) { + std::string_view details) { // "additional_headers" is a collection of string_views. These will no longer // be valid when "modify_headers" is finally called below, so we must // make copies of all the headers. @@ -1877,7 +1880,7 @@ void Context::onGrpcReceiveWrapper(uint32_t token, ::Envoy::Buffer::InstancePtr } void Context::onGrpcCloseWrapper(uint32_t token, const Grpc::Status::GrpcStatus& status, - const absl::string_view message) { + const std::string_view message) { if (proxy_wasm::current_context_ != nullptr) { // We are in a reentrant call, so defer. wasm()->addAfterVmCallAction([this, token, status, message = std::string(message)] { @@ -1887,7 +1890,7 @@ void Context::onGrpcCloseWrapper(uint32_t token, const Grpc::Status::GrpcStatus& } if (wasm()->on_grpc_close_) { status_code_ = static_cast(status); - status_message_ = message; + status_message_ = toAbslStringView(message); onGrpcClose(token, status_code_); status_message_ = ""; } @@ -1903,7 +1906,7 @@ void Context::onGrpcCloseWrapper(uint32_t token, const Grpc::Status::GrpcStatus& } } -WasmResult Context::grpcSend(uint32_t token, absl::string_view message, bool end_stream) { +WasmResult Context::grpcSend(uint32_t token, std::string_view message, bool end_stream) { if (isGrpcCallToken(token)) { return WasmResult::BadArgument; } diff --git a/source/extensions/common/wasm/context.h b/source/extensions/common/wasm/context.h index 53b3a273df3d8..a834be202a5aa 100644 --- a/source/extensions/common/wasm/context.h +++ b/source/extensions/common/wasm/context.h @@ -66,7 +66,7 @@ class Buffer : public proxy_wasm::BufferBase { size_t size() const override; WasmResult copyTo(WasmBase* wasm, size_t start, size_t length, uint64_t ptr_ptr, uint64_t size_ptr) const override; - WasmResult copyFrom(size_t start, size_t length, absl::string_view data) override; + WasmResult copyFrom(size_t start, size_t length, std::string_view data) override; // proxy_wasm::BufferBase void clear() override { @@ -74,7 +74,7 @@ class Buffer : public proxy_wasm::BufferBase { const_buffer_instance_ = nullptr; buffer_instance_ = nullptr; } - Buffer* set(absl::string_view data) { + Buffer* set(std::string_view data) { return static_cast(proxy_wasm::BufferBase::set(data)); } Buffer* set(std::unique_ptr owned_data, uint32_t owned_data_size) { @@ -122,7 +122,7 @@ class Context : public proxy_wasm::ContextBase, Upstream::ClusterManager& clusterManager() const; // proxy_wasm::ContextBase - void error(absl::string_view message) override; + void error(std::string_view message) override; // Retrieves the stream info associated with the request (a.k.a active stream). // It selects a value based on the following order: encoder callback, decoder @@ -141,7 +141,7 @@ class Context : public proxy_wasm::ContextBase, // // VM level down-calls into the Wasm code on Context(id == 0). // - virtual bool validateConfiguration(absl::string_view configuration, + virtual bool validateConfiguration(std::string_view configuration, const std::shared_ptr& plugin); // deprecated // AccessLog::Instance @@ -194,25 +194,25 @@ class Context : public proxy_wasm::ContextBase, // proxy_wasm::ContextBase // General - WasmResult log(uint32_t level, absl::string_view message) override; + WasmResult log(uint32_t level, std::string_view message) override; uint64_t getCurrentTimeNanoseconds() override; uint64_t getMonotonicTimeNanoseconds() override; - absl::string_view getConfiguration() override; - std::pair getStatus() override; + std::string_view getConfiguration() override; + std::pair getStatus() override; // State accessors - WasmResult getProperty(absl::string_view path, std::string* result) override; - WasmResult setProperty(absl::string_view path, absl::string_view value) override; - WasmResult declareProperty(absl::string_view path, + WasmResult getProperty(std::string_view path, std::string* result) override; + WasmResult setProperty(std::string_view path, std::string_view value) override; + WasmResult declareProperty(std::string_view path, Filters::Common::Expr::CelStatePrototypeConstPtr state_prototype); // Continue WasmResult continueStream(WasmStreamType stream_type) override; WasmResult closeStream(WasmStreamType stream_type) override; void failStream(WasmStreamType stream_type) override; - WasmResult sendLocalResponse(uint32_t response_code, absl::string_view body_text, + WasmResult sendLocalResponse(uint32_t response_code, std::string_view body_text, Pairs additional_headers, uint32_t grpc_status, - absl::string_view details) override; + std::string_view details) override; void clearRouteCache() override { if (decoder_callbacks_) { decoder_callbacks_->clearRouteCache(); @@ -220,16 +220,16 @@ class Context : public proxy_wasm::ContextBase, } // Header/Trailer/Metadata Maps - WasmResult addHeaderMapValue(WasmHeaderMapType type, absl::string_view key, - absl::string_view value) override; - WasmResult getHeaderMapValue(WasmHeaderMapType type, absl::string_view key, - absl::string_view* value) override; + WasmResult addHeaderMapValue(WasmHeaderMapType type, std::string_view key, + std::string_view value) override; + WasmResult getHeaderMapValue(WasmHeaderMapType type, std::string_view key, + std::string_view* value) override; WasmResult getHeaderMapPairs(WasmHeaderMapType type, Pairs* result) override; WasmResult setHeaderMapPairs(WasmHeaderMapType type, const Pairs& pairs) override; - WasmResult removeHeaderMapValue(WasmHeaderMapType type, absl::string_view key) override; - WasmResult replaceHeaderMapValue(WasmHeaderMapType type, absl::string_view key, - absl::string_view value) override; + WasmResult removeHeaderMapValue(WasmHeaderMapType type, std::string_view key) override; + WasmResult replaceHeaderMapValue(WasmHeaderMapType type, std::string_view key, + std::string_view value) override; WasmResult getHeaderMapSize(WasmHeaderMapType type, uint32_t* size) override; @@ -239,28 +239,28 @@ class Context : public proxy_wasm::ContextBase, bool endOfStream(WasmStreamType /* stream_type */) override { return end_of_stream_; } // HTTP - WasmResult httpCall(absl::string_view cluster, const Pairs& request_headers, - absl::string_view request_body, const Pairs& request_trailers, + WasmResult httpCall(std::string_view cluster, const Pairs& request_headers, + std::string_view request_body, const Pairs& request_trailers, int timeout_millisconds, uint32_t* token_ptr) override; // Stats/Metrics - WasmResult defineMetric(uint32_t type, absl::string_view name, uint32_t* metric_id_ptr) override; + WasmResult defineMetric(uint32_t type, std::string_view name, uint32_t* metric_id_ptr) override; WasmResult incrementMetric(uint32_t metric_id, int64_t offset) override; WasmResult recordMetric(uint32_t metric_id, uint64_t value) override; WasmResult getMetric(uint32_t metric_id, uint64_t* value_ptr) override; // gRPC - WasmResult grpcCall(absl::string_view grpc_service, absl::string_view service_name, - absl::string_view method_name, const Pairs& initial_metadata, - absl::string_view request, std::chrono::milliseconds timeout, + WasmResult grpcCall(std::string_view grpc_service, std::string_view service_name, + std::string_view method_name, const Pairs& initial_metadata, + std::string_view request, std::chrono::milliseconds timeout, uint32_t* token_ptr) override; - WasmResult grpcStream(absl::string_view grpc_service, absl::string_view service_name, - absl::string_view method_name, const Pairs& initial_metadat, + WasmResult grpcStream(std::string_view grpc_service, std::string_view service_name, + std::string_view method_name, const Pairs& initial_metadat, uint32_t* token_ptr) override; WasmResult grpcClose(uint32_t token) override; WasmResult grpcCancel(uint32_t token) override; - WasmResult grpcSend(uint32_t token, absl::string_view message, bool end_stream) override; + WasmResult grpcSend(uint32_t token, std::string_view message, bool end_stream) override; // Envoy specific ABI void onResolveDns(uint32_t token, Envoy::Network::DnsResolver::ResolutionStatus status, @@ -387,7 +387,7 @@ class Context : public proxy_wasm::ContextBase, void onGrpcReceiveWrapper(uint32_t token, ::Envoy::Buffer::InstancePtr response); void onGrpcReceiveTrailingMetadataWrapper(uint32_t token, Http::HeaderMapPtr&& metadata); void onGrpcCloseWrapper(uint32_t token, const Grpc::Status::GrpcStatus& status, - const absl::string_view message); + const std::string_view message); bool isGrpcStreamToken(uint32_t token) { return (token & 1) == 0; } bool isGrpcCallToken(uint32_t token) { return (token & 1) == 1; } diff --git a/source/extensions/common/wasm/foreign.cc b/source/extensions/common/wasm/foreign.cc index 9ace82a588172..3f153461e96c9 100644 --- a/source/extensions/common/wasm/foreign.cc +++ b/source/extensions/common/wasm/foreign.cc @@ -26,7 +26,7 @@ template WasmForeignFunction createFromClass() { RegisterForeignFunction registerCompressForeignFunction( "compress", - [](WasmBase&, absl::string_view arguments, + [](WasmBase&, std::string_view arguments, const std::function& alloc_result) -> WasmResult { unsigned long dest_len = compressBound(arguments.size()); std::unique_ptr b(new unsigned char[dest_len]); @@ -41,7 +41,7 @@ RegisterForeignFunction registerCompressForeignFunction( RegisterForeignFunction registerUncompressForeignFunction( "uncompress", - [](WasmBase&, absl::string_view arguments, + [](WasmBase&, std::string_view arguments, const std::function& alloc_result) -> WasmResult { unsigned long dest_len = arguments.size() * 2 + 2; // output estimate. while (true) { @@ -118,7 +118,7 @@ class CreateExpressionFactory : public ExpressionFactory { public: WasmForeignFunction create(std::shared_ptr self) const { WasmForeignFunction f = - [self](WasmBase&, absl::string_view expr, + [self](WasmBase&, std::string_view expr, const std::function& alloc_result) -> WasmResult { auto parse_status = google::api::expr::parser::Parse(std::string(expr)); if (!parse_status.ok()) { @@ -155,7 +155,7 @@ class EvaluateExpressionFactory : public ExpressionFactory { public: WasmForeignFunction create(std::shared_ptr self) const { WasmForeignFunction f = - [self](WasmBase&, absl::string_view argument, + [self](WasmBase&, std::string_view argument, const std::function& alloc_result) -> WasmResult { auto& expr_context = getOrCreateContext(proxy_wasm::current_context_->root_context()); if (argument.size() != sizeof(uint32_t)) { @@ -197,7 +197,7 @@ RegisterForeignFunction class DeleteExpressionFactory : public ExpressionFactory { public: WasmForeignFunction create(std::shared_ptr self) const { - WasmForeignFunction f = [self](WasmBase&, absl::string_view argument, + WasmForeignFunction f = [self](WasmBase&, std::string_view argument, const std::function&) -> WasmResult { auto& expr_context = getOrCreateContext(proxy_wasm::current_context_->root_context()); if (argument.size() != sizeof(uint32_t)) { @@ -220,7 +220,7 @@ RegisterForeignFunction class DeclarePropertyFactory { public: WasmForeignFunction create(std::shared_ptr self) const { - WasmForeignFunction f = [self](WasmBase&, absl::string_view arguments, + WasmForeignFunction f = [self](WasmBase&, std::string_view arguments, const std::function&) -> WasmResult { envoy::source::extensions::common::wasm::DeclarePropertyArguments args; if (args.ParseFromArray(arguments.data(), arguments.size())) { diff --git a/source/extensions/common/wasm/wasm.cc b/source/extensions/common/wasm/wasm.cc index 47de62bacd48e..8bef9b885485e 100644 --- a/source/extensions/common/wasm/wasm.cc +++ b/source/extensions/common/wasm/wasm.cc @@ -87,10 +87,10 @@ void Wasm::initializeLifecycle(Server::ServerLifecycleNotifier& lifecycle_notifi Wasm::Wasm(WasmConfig& config, absl::string_view vm_key, const Stats::ScopeSharedPtr& scope, Upstream::ClusterManager& cluster_manager, Event::Dispatcher& dispatcher) - : WasmBase(createWasmVm(config.config().vm_config().runtime()), - config.config().vm_config().vm_id(), - MessageUtil::anyToBytes(config.config().vm_config().configuration()), vm_key, - config.environmentVariables(), config.allowedCapabilities()), + : WasmBase( + createWasmVm(config.config().vm_config().runtime()), config.config().vm_config().vm_id(), + MessageUtil::anyToBytes(config.config().vm_config().configuration()), + toStdStringView(vm_key), config.environmentVariables(), config.allowedCapabilities()), scope_(scope), cluster_manager_(cluster_manager), dispatcher_(dispatcher), time_source_(dispatcher.timeSource()), wasm_stats_(WasmStats{ALL_WASM_STATS( @@ -105,8 +105,9 @@ Wasm::Wasm(WasmConfig& config, absl::string_view vm_key, const Stats::ScopeShare Wasm::Wasm(WasmHandleSharedPtr base_wasm_handle, Event::Dispatcher& dispatcher) : WasmBase(base_wasm_handle, [&base_wasm_handle]() { - return createWasmVm(absl::StrCat("envoy.wasm.runtime.", - base_wasm_handle->wasm()->wasm_vm()->runtime())); + return createWasmVm(absl::StrCat( + "envoy.wasm.runtime.", + toAbslStringView(base_wasm_handle->wasm()->wasm_vm()->runtime()))); }), scope_(getWasm(base_wasm_handle)->scope_), cluster_manager_(getWasm(base_wasm_handle)->clusterManager()), dispatcher_(dispatcher), @@ -115,7 +116,7 @@ Wasm::Wasm(WasmHandleSharedPtr base_wasm_handle, Event::Dispatcher& dispatcher) ENVOY_LOG(debug, "Thread-Local Wasm created {} now active", active_wasms); } -void Wasm::error(absl::string_view message) { ENVOY_LOG(error, "Wasm VM failed {}", message); } +void Wasm::error(std::string_view message) { ENVOY_LOG(error, "Wasm VM failed {}", message); } void Wasm::setTimerPeriod(uint32_t context_id, std::chrono::milliseconds new_period) { auto& period = timer_period_[context_id]; @@ -387,8 +388,9 @@ bool createWasm(const PluginSharedPtr& plugin, const Stats::ScopeSharedPtr& scop auto config = plugin->wasmConfig(); proxy_wasm::WasmHandleFactory proxy_wasm_factory = [&config, scope, &cluster_manager, &dispatcher, &lifecycle_notifier, - wasm_factory](absl::string_view vm_key) -> WasmHandleBaseSharedPtr { - return wasm_factory(config, scope, cluster_manager, dispatcher, lifecycle_notifier, vm_key); + wasm_factory](std::string_view vm_key) -> WasmHandleBaseSharedPtr { + return wasm_factory(config, scope, cluster_manager, dispatcher, lifecycle_notifier, + toAbslStringView(vm_key)); }; auto wasm = proxy_wasm::createWasm( vm_key, code, plugin, proxy_wasm_factory, diff --git a/source/extensions/common/wasm/wasm.h b/source/extensions/common/wasm/wasm.h index 2b34132b668fc..b696268ae5b75 100644 --- a/source/extensions/common/wasm/wasm.h +++ b/source/extensions/common/wasm/wasm.h @@ -61,7 +61,7 @@ class Wasm : public WasmBase, Logger::Loggable { Network::DnsResolverSharedPtr& dnsResolver() { return dns_resolver_; } // WasmBase - void error(absl::string_view message) override; + void error(std::string_view message) override; proxy_wasm::CallOnThreadFunction callOnThreadFunction() override; ContextBase* createContext(const std::shared_ptr& plugin) override; ContextBase* createRootContext(const std::shared_ptr& plugin) override; diff --git a/source/extensions/common/wasm/wasm_vm.cc b/source/extensions/common/wasm/wasm_vm.cc index c5827116cfeaf..51e1e3af52ae7 100644 --- a/source/extensions/common/wasm/wasm_vm.cc +++ b/source/extensions/common/wasm/wasm_vm.cc @@ -35,10 +35,10 @@ proxy_wasm::LogLevel EnvoyWasmVmIntegration::getLogLevel() { } } -void EnvoyWasmVmIntegration::error(absl::string_view message) { ENVOY_LOG(error, message); } -void EnvoyWasmVmIntegration::trace(absl::string_view message) { ENVOY_LOG(trace, message); } +void EnvoyWasmVmIntegration::error(std::string_view message) { ENVOY_LOG(error, message); } +void EnvoyWasmVmIntegration::trace(std::string_view message) { ENVOY_LOG(trace, message); } -bool EnvoyWasmVmIntegration::getNullVmFunction(absl::string_view function_name, bool returns_word, +bool EnvoyWasmVmIntegration::getNullVmFunction(std::string_view function_name, bool returns_word, int number_of_arguments, proxy_wasm::NullPlugin* plugin, void* ptr_to_function_return) { diff --git a/source/extensions/common/wasm/wasm_vm.h b/source/extensions/common/wasm/wasm_vm.h index be8f77e0da3fa..a4a6a1f1be03d 100644 --- a/source/extensions/common/wasm/wasm_vm.h +++ b/source/extensions/common/wasm/wasm_vm.h @@ -23,12 +23,11 @@ class EnvoyWasmVmIntegration : public proxy_wasm::WasmVmIntegration, public: // proxy_wasm::WasmVmIntegration proxy_wasm::WasmVmIntegration* clone() override { return new EnvoyWasmVmIntegration(); } - bool getNullVmFunction(absl::string_view function_name, bool returns_word, - int number_of_arguments, proxy_wasm::NullPlugin* plugin, - void* ptr_to_function_return) override; + bool getNullVmFunction(std::string_view function_name, bool returns_word, int number_of_arguments, + proxy_wasm::NullPlugin* plugin, void* ptr_to_function_return) override; proxy_wasm::LogLevel getLogLevel() override; - void error(absl::string_view message) override; - void trace(absl::string_view message) override; + void error(std::string_view message) override; + void trace(std::string_view message) override; }; // Exceptions for issues with the WebAssembly code. diff --git a/source/extensions/filters/http/set_metadata/set_metadata_filter.cc b/source/extensions/filters/http/set_metadata/set_metadata_filter.cc index a17bec4c0afb3..bb0448610af77 100644 --- a/source/extensions/filters/http/set_metadata/set_metadata_filter.cc +++ b/source/extensions/filters/http/set_metadata/set_metadata_filter.cc @@ -26,7 +26,8 @@ SetMetadataFilter::~SetMetadataFilter() = default; Http::FilterHeadersStatus SetMetadataFilter::decodeHeaders(Http::RequestHeaderMap&, bool) { const absl::string_view metadata_namespace = config_->metadataNamespace(); auto& metadata = *decoder_callbacks_->streamInfo().dynamicMetadata().mutable_filter_metadata(); - ProtobufWkt::Struct& org_fields = metadata[metadata_namespace]; + ProtobufWkt::Struct& org_fields = + metadata[toStdStringView(metadata_namespace)]; // NOLINT(std::string_view) const ProtobufWkt::Struct& to_merge = config_->value(); StructUtil::update(org_fields, to_merge); diff --git a/source/extensions/tracers/skywalking/skywalking_tracer_impl.cc b/source/extensions/tracers/skywalking/skywalking_tracer_impl.cc index 7bff0c42991e9..716db5434ee10 100644 --- a/source/extensions/tracers/skywalking/skywalking_tracer_impl.cc +++ b/source/extensions/tracers/skywalking/skywalking_tracer_impl.cc @@ -62,7 +62,8 @@ Tracing::SpanPtr Driver::startSpan(const Tracing::Config& config, } else { auto header_value_string = propagation_header[0]->value().getStringView(); try { - SpanContextPtr span_context = createSpanContext(header_value_string); + SpanContextPtr span_context = + createSpanContext(toStdStringView(header_value_string)); // NOLINT(std::string_view) tracing_context = tracing_context_factory_->create(span_context); } catch (TracerException& e) { ENVOY_LOG(warn, "New SkyWalking Span/Segment cannot be created for error: {}", e.what()); diff --git a/test/common/config/context_provider_impl_test.cc b/test/common/config/context_provider_impl_test.cc index f2f103ac4b1b9..48f90c5bcf968 100644 --- a/test/common/config/context_provider_impl_test.cc +++ b/test/common/config/context_provider_impl_test.cc @@ -46,7 +46,7 @@ TEST(ContextProviderTest, DynamicContextParameters) { auto callback_handle = context_provider.addDynamicContextUpdateCallback( [&update_count, &last_updated_resource](absl::string_view resource_type_url) { ++update_count; - last_updated_resource = resource_type_url; + last_updated_resource = std::string(resource_type_url); }); // Default empty DCP for all types. diff --git a/test/common/http/path_utility_fuzz_test.cc b/test/common/http/path_utility_fuzz_test.cc index 4833a420e081e..654ad5097369e 100644 --- a/test/common/http/path_utility_fuzz_test.cc +++ b/test/common/http/path_utility_fuzz_test.cc @@ -33,7 +33,7 @@ DEFINE_PROTO_FUZZER(const test::common::http::PathUtilityTestCase& input) { case test::common::http::PathUtilityTestCase::kRemoveQueryAndFragment: { auto path = input.remove_query_and_fragment().path(); auto sanitized_path = Http::PathUtil::removeQueryAndFragment(path); - ASSERT(path.find(sanitized_path) != std::string::npos); + ASSERT(path.find(std::string(sanitized_path)) != std::string::npos); break; } default: diff --git a/test/common/router/config_impl_test.cc b/test/common/router/config_impl_test.cc index d9f63bc39b3c5..38f3f0d65387d 100644 --- a/test/common/router/config_impl_test.cc +++ b/test/common/router/config_impl_test.cc @@ -2201,7 +2201,7 @@ TEST_F(RouterMatcherHashPolicyTest, HashHeadersWithMultipleValues) { EXPECT_FALSE(generateHash({})); EXPECT_TRUE(generateHash({"bar"})); - EXPECT_NE(0, generateHash({"bar", "foo"})); + EXPECT_NE(0UL, generateHash({"bar", "foo"})); EXPECT_EQ(generateHash({"bar", "foo"}), generateHash({"bar", "foo"})); // deterministic EXPECT_EQ(generateHash({"bar", "foo"}), generateHash({"foo", "bar"})); // order independent EXPECT_NE(generateHash({"abcd", "ef"}), generateHash({"abc", "def"})); @@ -2250,7 +2250,7 @@ TEST_F(RouterMatcherHashPolicyTest, HashHeadersRegexSubstitutionWithMultipleValu EXPECT_FALSE(generateHash({})); EXPECT_TRUE(generateHash({"/bar"})); - EXPECT_NE(0, generateHash({"/bar", "/foo"})); + EXPECT_NE(0UL, generateHash({"/bar", "/foo"})); EXPECT_EQ(generateHash({"bar", "foo"}), generateHash({"/bar", "/foo"})); // deterministic EXPECT_EQ(generateHash({"bar", "foo"}), generateHash({"/foo", "/bar"})); // order independent EXPECT_NE(generateHash({"abcd", "ef"}), generateHash({"/abc", "/def"})); diff --git a/test/common/stream_info/test_util.h b/test/common/stream_info/test_util.h index f585568b7df06..8335d6317b749 100644 --- a/test/common/stream_info/test_util.h +++ b/test/common/stream_info/test_util.h @@ -224,7 +224,7 @@ class TestStreamInfo : public StreamInfo::StreamInfo { absl::optional connectionID() const override { return connection_id_; } void setFilterChainName(absl::string_view filter_chain_name) override { - filter_chain_name_ = filter_chain_name; + filter_chain_name_ = std::string(filter_chain_name); } const std::string& filterChainName() const override { return filter_chain_name_; } diff --git a/test/common/upstream/load_balancer_benchmark.cc b/test/common/upstream/load_balancer_benchmark.cc index f5530701f434e..22f58f0f9337e 100644 --- a/test/common/upstream/load_balancer_benchmark.cc +++ b/test/common/upstream/load_balancer_benchmark.cc @@ -538,7 +538,7 @@ class SubsetLbTester : public BaseTester { envoy::config::cluster::v3::Cluster::LbSubsetConfig::ANY_ENDPOINT); auto* selector = subset_config.mutable_subset_selectors()->Add(); selector->set_single_host_per_subset(single_host_per_subset); - *selector->mutable_keys()->Add() = metadata_key; + *selector->mutable_keys()->Add() = std::string(metadata_key); subset_info_ = std::make_unique(subset_config); lb_ = std::make_unique(LoadBalancerType::Random, priority_set_, diff --git a/test/common/upstream/upstream_impl_test.cc b/test/common/upstream/upstream_impl_test.cc index d147e4ccc8c99..a0036c035e4f2 100644 --- a/test/common/upstream/upstream_impl_test.cc +++ b/test/common/upstream/upstream_impl_test.cc @@ -2342,22 +2342,22 @@ TEST_F(ClusterInfoImplTest, RetryBudgetDefaultPopulation) { std::tie(budget_percent, min_retry_concurrency) = RetryBudgetTestClusterInfo::getRetryBudgetParams(threshold[1]); EXPECT_EQ(budget_percent, 20.0); - EXPECT_EQ(min_retry_concurrency, 3); + EXPECT_EQ(min_retry_concurrency, 3UL); std::tie(budget_percent, min_retry_concurrency) = RetryBudgetTestClusterInfo::getRetryBudgetParams(threshold[2]); EXPECT_EQ(budget_percent, 20.0); - EXPECT_EQ(min_retry_concurrency, 3); + EXPECT_EQ(min_retry_concurrency, 3UL); std::tie(budget_percent, min_retry_concurrency) = RetryBudgetTestClusterInfo::getRetryBudgetParams(threshold[3]); EXPECT_EQ(budget_percent, 42.0); - EXPECT_EQ(min_retry_concurrency, 3); + EXPECT_EQ(min_retry_concurrency, 3UL); std::tie(budget_percent, min_retry_concurrency) = RetryBudgetTestClusterInfo::getRetryBudgetParams(threshold[4]); EXPECT_EQ(budget_percent, 20.0); - EXPECT_EQ(min_retry_concurrency, 123); + EXPECT_EQ(min_retry_concurrency, 123UL); } // Eds service_name is populated. diff --git a/test/config_test/config_test.cc b/test/config_test/config_test.cc index e7b227a0d27f4..3c8acc2592c68 100644 --- a/test/config_test/config_test.cc +++ b/test/config_test/config_test.cc @@ -213,7 +213,7 @@ uint32_t run(const std::string& directory) { ENVOY_LOG_MISC(info, "testing {}.\n", filename); if (std::find_if(unsuported_win32_configs.begin(), unsuported_win32_configs.end(), [filename](const absl::string_view& s) { - return filename.find(s) != std::string::npos; + return filename.find(std::string(s)) != std::string::npos; }) == unsuported_win32_configs.end()) { OptionsImpl options( Envoy::Server::createTestOptionsImpl(filename, "", Network::Address::IpVersion::v6)); diff --git a/test/extensions/bootstrap/wasm/wasm_speed_test.cc b/test/extensions/bootstrap/wasm/wasm_speed_test.cc index 9e14a8f7703a1..67f0820072057 100644 --- a/test/extensions/bootstrap/wasm/wasm_speed_test.cc +++ b/test/extensions/bootstrap/wasm/wasm_speed_test.cc @@ -32,8 +32,8 @@ class TestRoot : public Envoy::Extensions::Common::Wasm::Context { : Envoy::Extensions::Common::Wasm::Context(wasm, plugin) {} using Envoy::Extensions::Common::Wasm::Context::log; - proxy_wasm::WasmResult log(uint32_t level, absl::string_view message) override { - log_(static_cast(level), message); + proxy_wasm::WasmResult log(uint32_t level, std::string_view message) override { + log_(static_cast(level), toAbslStringView(message)); return proxy_wasm::WasmResult::Ok; } MOCK_METHOD(void, log_, (spdlog::level::level_enum level, absl::string_view message)); diff --git a/test/extensions/bootstrap/wasm/wasm_test.cc b/test/extensions/bootstrap/wasm/wasm_test.cc index 0ccd91dd7c73b..3e88a3b636689 100644 --- a/test/extensions/bootstrap/wasm/wasm_test.cc +++ b/test/extensions/bootstrap/wasm/wasm_test.cc @@ -26,9 +26,9 @@ class TestContext : public Extensions::Common::Wasm::Context { : Extensions::Common::Wasm::Context(wasm, plugin) {} ~TestContext() override = default; using Extensions::Common::Wasm::Context::log; - proxy_wasm::WasmResult log(uint32_t level, absl::string_view message) override { - std::cerr << std::string(message) << "\n"; - log_(static_cast(level), message); + proxy_wasm::WasmResult log(uint32_t level, std::string_view message) override { + std::cerr << message << "\n"; + log_(static_cast(level), toAbslStringView(message)); return proxy_wasm::WasmResult::Ok; } MOCK_METHOD(void, log_, (spdlog::level::level_enum level, absl::string_view message)); diff --git a/test/extensions/common/wasm/wasm_test.cc b/test/extensions/common/wasm/wasm_test.cc index 4ef385ed47897..65127768a1839 100644 --- a/test/extensions/common/wasm/wasm_test.cc +++ b/test/extensions/common/wasm/wasm_test.cc @@ -72,9 +72,9 @@ class TestContext : public ::Envoy::Extensions::Common::Wasm::Context { using ::Envoy::Extensions::Common::Wasm::Context::Context; ~TestContext() override = default; using ::Envoy::Extensions::Common::Wasm::Context::log; - proxy_wasm::WasmResult log(uint32_t level, absl::string_view message) override { - std::cerr << std::string(message) << "\n"; - log_(static_cast(level), message); + proxy_wasm::WasmResult log(uint32_t level, std::string_view message) override { + std::cerr << message << "\n"; + log_(static_cast(level), toAbslStringView(message)); Extensions::Common::Wasm::Context::log(static_cast(level), message); return proxy_wasm::WasmResult::Ok; } diff --git a/test/extensions/io_socket/user_space/io_handle_impl_test.cc b/test/extensions/io_socket/user_space/io_handle_impl_test.cc index 150e25c8a685a..83f8cd0ee3e72 100644 --- a/test/extensions/io_socket/user_space/io_handle_impl_test.cc +++ b/test/extensions/io_socket/user_space/io_handle_impl_test.cc @@ -737,7 +737,7 @@ TEST_F(IoHandleImplTest, Close) { should_close = true; break; } else { - accumulator += absl::string_view(buf_.data(), result.rc_); + accumulator += std::string(buf_.data(), result.rc_); } } else if (result.err_->getErrorCode() == Api::IoError::IoErrorCode::Again) { ENVOY_LOG_MISC(debug, "read returns EAGAIN"); @@ -792,7 +792,7 @@ TEST_F(IoHandleImplTest, ShutDownRaiseEvent) { if (events & Event::FileReadyType::Read) { auto result = io_handle_->recv(buf_.data(), buf_.size(), 0); if (result.ok()) { - accumulator += absl::string_view(buf_.data(), result.rc_); + accumulator += std::string(buf_.data(), result.rc_); } else if (result.err_->getErrorCode() == Api::IoError::IoErrorCode::Again) { ENVOY_LOG_MISC(debug, "read returns EAGAIN"); } else { @@ -832,7 +832,7 @@ TEST_F(IoHandleImplTest, WriteScheduleWritableEvent) { auto slice = reservation.slice(); auto result = handle->readv(1024, &slice, 1); if (result.ok()) { - accumulator += absl::string_view(static_cast(slice.mem_), result.rc_); + accumulator += std::string(static_cast(slice.mem_), result.rc_); } else if (result.err_->getErrorCode() == Api::IoError::IoErrorCode::Again) { ENVOY_LOG_MISC(debug, "read returns EAGAIN"); } else { @@ -872,7 +872,7 @@ TEST_F(IoHandleImplTest, WritevScheduleWritableEvent) { auto slice = reservation.slice(); auto result = handle->readv(1024, &slice, 1); if (result.ok()) { - accumulator += absl::string_view(static_cast(slice.mem_), result.rc_); + accumulator += std::string(static_cast(slice.mem_), result.rc_); } else if (result.err_->getErrorCode() == Api::IoError::IoErrorCode::Again) { ENVOY_LOG_MISC(debug, "read returns EAGAIN"); } else { @@ -916,7 +916,7 @@ TEST_F(IoHandleImplTest, ReadAfterShutdownWrite) { if (result.rc_ == 0) { should_close = true; } else { - accumulator += absl::string_view(static_cast(slice.mem_), result.rc_); + accumulator += std::string(static_cast(slice.mem_), result.rc_); } } else if (result.err_->getErrorCode() == Api::IoError::IoErrorCode::Again) { ENVOY_LOG_MISC(debug, "read returns EAGAIN"); diff --git a/test/extensions/stats_sinks/wasm/wasm_stat_sink_test.cc b/test/extensions/stats_sinks/wasm/wasm_stat_sink_test.cc index 42e336089f34d..4bda7d8e9d970 100644 --- a/test/extensions/stats_sinks/wasm/wasm_stat_sink_test.cc +++ b/test/extensions/stats_sinks/wasm/wasm_stat_sink_test.cc @@ -22,9 +22,9 @@ class TestContext : public ::Envoy::Extensions::Common::Wasm::Context { using ::Envoy::Extensions::Common::Wasm::Context::Context; ~TestContext() override = default; using ::Envoy::Extensions::Common::Wasm::Context::log; - proxy_wasm::WasmResult log(uint32_t level, absl::string_view message) override { - std::cerr << std::string(message) << "\n"; - log_(static_cast(level), message); + proxy_wasm::WasmResult log(uint32_t level, std::string_view message) override { + std::cerr << message << "\n"; + log_(static_cast(level), toAbslStringView(message)); Extensions::Common::Wasm::Context::log(static_cast(level), message); return proxy_wasm::WasmResult::Ok; } diff --git a/test/extensions/transport_sockets/tls/context_impl_test.cc b/test/extensions/transport_sockets/tls/context_impl_test.cc index ef8fa8f72f485..72bff36b463bd 100644 --- a/test/extensions/transport_sockets/tls/context_impl_test.cc +++ b/test/extensions/transport_sockets/tls/context_impl_test.cc @@ -668,13 +668,13 @@ TEST_F(SslServerContextImplOcspTest, TestGetCertInformationWithOCSP) { for (const auto& detail : ocsp_text_details) { std::string::size_type pos = detail.find(this_update); if (pos != std::string::npos) { - valid_from = detail.substr(pos + this_update.size()); + valid_from = std::string(detail.substr(pos + this_update.size())); continue; } pos = detail.find(next_update); if (pos != std::string::npos) { - expiration = detail.substr(pos + next_update.size()); + expiration = std::string(detail.substr(pos + next_update.size())); continue; } } diff --git a/test/integration/sds_dynamic_integration_test.cc b/test/integration/sds_dynamic_integration_test.cc index 79d9dc47a589c..e29fc1e9cf4b9 100644 --- a/test/integration/sds_dynamic_integration_test.cc +++ b/test/integration/sds_dynamic_integration_test.cc @@ -240,7 +240,7 @@ class SdsDynamicDownstreamIntegrationTest : public SdsDynamicIntegrationBaseTest secret_config_ecdsa->set_name(server_cert_ecdsa_); auto* config_source = secret_config_ecdsa->mutable_sds_config(); - constexpr absl::string_view sds_template = + const std::string sds_template = R"EOF( --- version_info: "0" diff --git a/test/integration/upstreams/per_host_upstream_config.h b/test/integration/upstreams/per_host_upstream_config.h index dc5cbbe330490..e649aa087a8f6 100644 --- a/test/integration/upstreams/per_host_upstream_config.h +++ b/test/integration/upstreams/per_host_upstream_config.h @@ -28,11 +28,12 @@ namespace { void addHeader(Envoy::Http::RequestHeaderMap& header_map, absl::string_view header_name, const envoy::config::core::v3::Metadata& metadata, absl::string_view key1, absl::string_view key2) { - if (auto filter_metadata = metadata.filter_metadata().find(key1); + if (auto filter_metadata = metadata.filter_metadata().find(std::string(key1)); filter_metadata != metadata.filter_metadata().end()) { const ProtobufWkt::Struct& data_struct = filter_metadata->second; const auto& fields = data_struct.fields(); - if (auto iter = fields.find(key2); iter != fields.end()) { + if (auto iter = fields.find(toStdStringView(key2)); // NOLINT(std::string_view) + iter != fields.end()) { if (iter->second.kind_case() == ProtobufWkt::Value::kStringValue) { header_map.setCopy(Envoy::Http::LowerCaseString(std::string(header_name)), iter->second.string_value()); diff --git a/test/mocks/stream_info/mocks.cc b/test/mocks/stream_info/mocks.cc index 4fd097f65f2ff..3907bb515f131 100644 --- a/test/mocks/stream_info/mocks.cc +++ b/test/mocks/stream_info/mocks.cc @@ -31,8 +31,9 @@ MockStreamInfo::MockStreamInfo() response_code_details_ = std::string(details); })); ON_CALL(*this, setConnectionTerminationDetails(_)) - .WillByDefault( - Invoke([this](absl::string_view details) { connection_termination_details_ = details; })); + .WillByDefault(Invoke([this](absl::string_view details) { + connection_termination_details_ = std::string(details); + })); ON_CALL(*this, startTime()).WillByDefault(ReturnPointee(&start_time_)); ON_CALL(*this, startTimeMonotonic()).WillByDefault(ReturnPointee(&start_time_monotonic_)); ON_CALL(*this, lastDownstreamRxByteReceived()) diff --git a/test/test_common/file_system_for_test.h b/test/test_common/file_system_for_test.h index 9a8e813c02f34..bd5abfcfd5020 100644 --- a/test/test_common/file_system_for_test.h +++ b/test/test_common/file_system_for_test.h @@ -35,7 +35,7 @@ class MemfileImpl : public FileSharedImpl { if (!flags_.test(File::Operation::Append)) { info_->data_.clear(); } - info_->data_.append(buffer); + info_->data_.append(std::string(buffer)); const ssize_t size = info_->data_.size(); return resultSuccess(size); } diff --git a/test/test_common/wasm_base.h b/test/test_common/wasm_base.h index 89e49b16e1e11..8231788e24ec3 100644 --- a/test/test_common/wasm_base.h +++ b/test/test_common/wasm_base.h @@ -33,8 +33,8 @@ namespace Wasm { #define MOCK_CONTEXT_LOG_ \ using Context::log; \ - proxy_wasm::WasmResult log(uint32_t level, absl::string_view message) override { \ - log_(static_cast(level), message); \ + proxy_wasm::WasmResult log(uint32_t level, std::string_view message) override { \ + log_(static_cast(level), toAbslStringView(message)); \ return proxy_wasm::WasmResult::Ok; \ } \ MOCK_METHOD(void, log_, (spdlog::level::level_enum level, absl::string_view message)) diff --git a/tools/code_format/check_format.py b/tools/code_format/check_format.py index 92a00dee80db7..f9594121db81b 100755 --- a/tools/code_format/check_format.py +++ b/tools/code_format/check_format.py @@ -123,6 +123,25 @@ "./source/common/network/utility.cc", ) +# These are entire files that are allowed to use std::string_view vs. individual exclusions. Right +# now this is just WASM which makes use of std::string_view heavily so we need to convert to +# absl::string_view internally. Everywhere else should be using absl::string_view for additional +# safety. +STD_STRING_VIEW_ALLOWLIST = ( + "./source/extensions/common/wasm/context.h", + "./source/extensions/common/wasm/context.cc", + "./source/extensions/common/wasm/foreign.cc", + "./source/extensions/common/wasm/wasm.h", + "./source/extensions/common/wasm/wasm.cc", + "./source/extensions/common/wasm/wasm_vm.h", + "./source/extensions/common/wasm/wasm_vm.cc", + "./test/extensions/bootstrap/wasm/wasm_speed_test.cc", + "./test/extensions/bootstrap/wasm/wasm_test.cc", + "./test/extensions/common/wasm/wasm_test.cc", + "./test/extensions/stats_sinks/wasm/wasm_stat_sink_test.cc", + "./test/test_common/wasm_base.h", +) + # Header files that can throw exceptions. These should be limited; the only # valid situation identified so far is template functions used for config # processing. @@ -438,6 +457,9 @@ def allow_listed_for_register_factory(self, file_path): def allow_listed_for_serialize_as_string(self, file_path): return file_path in SERIALIZE_AS_STRING_ALLOWLIST or file_path.endswith(DOCS_SUFFIX) + def allow_listed_for_std_string_view(self, file_path): + return file_path in STD_STRING_VIEW_ALLOWLIST + def allow_listed_for_json_string_to_message(self, file_path): return file_path in JSON_STRING_TO_MESSAGE_ALLOWLIST @@ -824,8 +846,12 @@ def check_source_line(self, line, file_path, report_error): report_error("Don't use std::monostate; use absl::monostate instead") if self.token_in_line("std::optional", line): report_error("Don't use std::optional; use absl::optional instead") - if self.token_in_line("std::string_view", line): - report_error("Don't use std::string_view; use absl::string_view instead") + if not self.allow_listed_for_std_string_view( + file_path) and not "NOLINT(std::string_view)" in line: + if self.token_in_line("std::string_view", line) or self.token_in_line("toStdStringView", + line): + report_error( + "Don't use std::string_view or toStdStringView; use absl::string_view instead") if self.token_in_line("std::variant", line): report_error("Don't use std::variant; use absl::variant instead") if self.token_in_line("std::visit", line): diff --git a/tools/code_format/check_format_test_helper.py b/tools/code_format/check_format_test_helper.py index 8f8d0ac8a31b0..057362709f760 100755 --- a/tools/code_format/check_format_test_helper.py +++ b/tools/code_format/check_format_test_helper.py @@ -265,7 +265,8 @@ def run_checks(): errors += check_unfixable_error( "std_optional.cc", "Don't use std::optional; use absl::optional instead") errors += check_unfixable_error( - "std_string_view.cc", "Don't use std::string_view; use absl::string_view instead") + "std_string_view.cc", + "Don't use std::string_view or toStdStringView; use absl::string_view instead") errors += check_unfixable_error( "std_variant.cc", "Don't use std::variant; use absl::variant instead") errors += check_unfixable_error("std_visit.cc", "Don't use std::visit; use absl::visit instead")