diff --git a/bazel/repositories.bzl b/bazel/repositories.bzl index 68f01cd34869..66f717943846 100644 --- a/bazel/repositories.bzl +++ b/bazel/repositories.bzl @@ -324,6 +324,10 @@ def _com_google_absl(): name = "abseil_int128", actual = "@com_google_absl//absl/numeric:int128", ) + native.bind( + name = "abseil_optional", + actual = "@com_google_absl//absl/types:optional", + ) def _com_google_protobuf(): _repository_impl("com_google_protobuf") diff --git a/include/envoy/common/BUILD b/include/envoy/common/BUILD index 6efff3c4595e..5805872cf737 100644 --- a/include/envoy/common/BUILD +++ b/include/envoy/common/BUILD @@ -28,11 +28,6 @@ envoy_cc_library( hdrs = ["interval_set.h"], ) -envoy_cc_library( - name = "optional", - hdrs = ["optional.h"], -) - envoy_cc_library( name = "callback", hdrs = ["callback.h"], diff --git a/include/envoy/common/optional.h b/include/envoy/common/optional.h deleted file mode 100644 index eaa04be24775..000000000000 --- a/include/envoy/common/optional.h +++ /dev/null @@ -1,70 +0,0 @@ -#pragma once - -#include "envoy/common/exception.h" - -namespace Envoy { - -/** - * Contains an optional value. Like boost::optional and std::optional (not included in C++11). - * TODO: Replace with https://github.com/abseil/abseil-cpp/blob/master/absl/types/optional.h - */ -template class Optional { -public: - Optional() {} - Optional(const T& value) : value_(value), valid_(true) {} - - const T& operator=(const T& new_value) { - value_ = new_value; - valid_ = true; - return value_; - } - - bool operator==(const Optional& rhs) const { - if (valid_) { - return valid_ == rhs.valid_ && value_ == rhs.value_; - } else { - return valid_ == rhs.valid_; - } - } - - /** - * @return whether the contained value is valid. - */ - bool valid() const { return valid_; } - - /** - * Set the contained value which will make it valid. - */ - void value(const T& new_value) { - value_ = new_value; - valid_ = true; - } - - /** - * @return the contained value. Will throw if the contained value is not valid. - */ - const T& value() const { - if (!valid_) { - throw EnvoyException("fetching invalid Optional value"); - } - - return value_; - } - - /** - * @return the contained value. Will throw if the contained value is not valid. - */ - T& value() { - if (!valid_) { - throw EnvoyException("fetching invalid Optional value"); - } - - return value_; - } - -private: - T value_{}; - bool valid_{}; -}; - -} // namespace Envoy diff --git a/include/envoy/grpc/BUILD b/include/envoy/grpc/BUILD index 70532429c510..d92978ca7661 100644 --- a/include/envoy/grpc/BUILD +++ b/include/envoy/grpc/BUILD @@ -11,9 +11,9 @@ envoy_package() envoy_cc_library( name = "async_client_interface", hdrs = ["async_client.h"], + external_deps = ["abseil_optional"], deps = [ ":status", - "//include/envoy/common:optional", "//include/envoy/http:header_map_interface", "//include/envoy/tracing:http_tracer_interface", "//source/common/protobuf", diff --git a/include/envoy/grpc/async_client.h b/include/envoy/grpc/async_client.h index 789347c92603..8a8bdc8d2cd2 100644 --- a/include/envoy/grpc/async_client.h +++ b/include/envoy/grpc/async_client.h @@ -2,7 +2,6 @@ #include -#include "envoy/common/optional.h" #include "envoy/common/pure.h" #include "envoy/grpc/status.h" #include "envoy/http/header_map.h" @@ -10,6 +9,8 @@ #include "common/protobuf/protobuf.h" +#include "absl/types/optional.h" + namespace Envoy { namespace Grpc { @@ -194,7 +195,7 @@ class AsyncClient { virtual AsyncRequest* send(const Protobuf::MethodDescriptor& service_method, const Protobuf::Message& request, AsyncRequestCallbacks& callbacks, Tracing::Span& parent_span, - const Optional& timeout) PURE; + const absl::optional& timeout) PURE; /** * Start a gRPC stream asynchronously. diff --git a/include/envoy/http/BUILD b/include/envoy/http/BUILD index ea057049e442..ac4dc2ad8b63 100644 --- a/include/envoy/http/BUILD +++ b/include/envoy/http/BUILD @@ -11,9 +11,9 @@ envoy_package() envoy_cc_library( name = "async_client_interface", hdrs = ["async_client.h"], + external_deps = ["abseil_optional"], deps = [ ":message_interface", - "//include/envoy/common:optional", "//include/envoy/event:dispatcher_interface", ], ) diff --git a/include/envoy/http/async_client.h b/include/envoy/http/async_client.h index 0a6298197c01..f8f0232bf4aa 100644 --- a/include/envoy/http/async_client.h +++ b/include/envoy/http/async_client.h @@ -3,10 +3,11 @@ #include #include -#include "envoy/common/optional.h" #include "envoy/event/dispatcher.h" #include "envoy/http/message.h" +#include "absl/types/optional.h" + namespace Envoy { namespace Http { @@ -140,7 +141,7 @@ class AsyncClient { * handle should just be used to cancel. */ virtual Request* send(MessagePtr&& request, Callbacks& callbacks, - const Optional& timeout) PURE; + const absl::optional& timeout) PURE; /** * Start an HTTP stream asynchronously. @@ -156,7 +157,7 @@ class AsyncClient { * the handle can be used to send more messages or close the stream. */ virtual Stream* start(StreamCallbacks& callbacks, - const Optional& timeout, + const absl::optional& timeout, bool buffer_body_for_retry) PURE; /** diff --git a/include/envoy/ratelimit/BUILD b/include/envoy/ratelimit/BUILD index 439b637ae9fc..ed2aadf2ac07 100644 --- a/include/envoy/ratelimit/BUILD +++ b/include/envoy/ratelimit/BUILD @@ -11,8 +11,8 @@ envoy_package() envoy_cc_library( name = "ratelimit_interface", hdrs = ["ratelimit.h"], + external_deps = ["abseil_optional"], deps = [ - "//include/envoy/common:optional", "//include/envoy/tracing:http_tracer_interface", ], ) diff --git a/include/envoy/ratelimit/ratelimit.h b/include/envoy/ratelimit/ratelimit.h index ef1a6deb6a8a..228aa696dc18 100644 --- a/include/envoy/ratelimit/ratelimit.h +++ b/include/envoy/ratelimit/ratelimit.h @@ -5,10 +5,11 @@ #include #include -#include "envoy/common/optional.h" #include "envoy/common/pure.h" #include "envoy/tracing/http_tracer.h" +#include "absl/types/optional.h" + namespace Envoy { namespace RateLimit { @@ -92,7 +93,7 @@ class ClientFactory { /** * Return a new rate limit client. */ - virtual ClientPtr create(const Optional& timeout) PURE; + virtual ClientPtr create(const absl::optional& timeout) PURE; }; typedef std::unique_ptr ClientFactoryPtr; diff --git a/include/envoy/request_info/BUILD b/include/envoy/request_info/BUILD index 89fa50062417..57bc0ae18b78 100644 --- a/include/envoy/request_info/BUILD +++ b/include/envoy/request_info/BUILD @@ -11,8 +11,8 @@ envoy_package() envoy_cc_library( name = "request_info_interface", hdrs = ["request_info.h"], + external_deps = ["abseil_optional"], deps = [ - "//include/envoy/common:optional", "//include/envoy/common:time_interface", "//include/envoy/http:protocol_interface", "//include/envoy/upstream:upstream_interface", diff --git a/include/envoy/request_info/request_info.h b/include/envoy/request_info/request_info.h index 863b923d0971..f51018baa1f9 100644 --- a/include/envoy/request_info/request_info.h +++ b/include/envoy/request_info/request_info.h @@ -4,12 +4,13 @@ #include #include -#include "envoy/common/optional.h" #include "envoy/common/pure.h" #include "envoy/common/time.h" #include "envoy/http/protocol.h" #include "envoy/upstream/upstream.h" +#include "absl/types/optional.h" + namespace Envoy { namespace Router { @@ -75,7 +76,7 @@ class RequestInfo { /** * @return the protocol of the request. */ - virtual Optional protocol() const PURE; + virtual absl::optional protocol() const PURE; /** * @param protocol the request's protocol. @@ -85,7 +86,7 @@ class RequestInfo { /** * @return the response code. */ - virtual Optional responseCode() const PURE; + virtual absl::optional responseCode() const PURE; /** * @return the time that the first byte of the request was received. @@ -102,7 +103,7 @@ class RequestInfo { * @return the duration between the last byte of the request was received and the start of the * request. */ - virtual Optional lastDownstreamRxByteReceived() const PURE; + virtual absl::optional lastDownstreamRxByteReceived() const PURE; /** * Sets the time when the last byte of the request was received. @@ -114,7 +115,7 @@ class RequestInfo { * the request. There may be a considerable delta between lastDownstreamByteReceived and this * value due to filters. */ - virtual Optional firstUpstreamTxByteSent() const PURE; + virtual absl::optional firstUpstreamTxByteSent() const PURE; /** * Sets the time when the first byte of the request was sent upstream. @@ -125,7 +126,7 @@ class RequestInfo { * @return the duration between the last bye of the request was sent upstream and the start of the * request. */ - virtual Optional lastUpstreamTxByteSent() const PURE; + virtual absl::optional lastUpstreamTxByteSent() const PURE; /** * Sets the time when the last bye of the request was sent upstream. @@ -136,7 +137,7 @@ class RequestInfo { * @return the duration between the first byte of the response is received from upstream and the * start of the request. */ - virtual Optional firstUpstreamRxByteReceived() const PURE; + virtual absl::optional firstUpstreamRxByteReceived() const PURE; /** * Sets the time when the first byte of the response is received from @@ -148,7 +149,7 @@ class RequestInfo { * @return the duration between the last byte of the response is received from upstream and the * start of the request. */ - virtual Optional lastUpstreamRxByteReceived() const PURE; + virtual absl::optional lastUpstreamRxByteReceived() const PURE; /** * Sets the time when the last byte of the response is received from @@ -161,7 +162,7 @@ class RequestInfo { * the request. There may be a considerable delta between lastUpstreamByteReceived and this value * due to filters. */ - virtual Optional firstDownstreamTxByteSent() const PURE; + virtual absl::optional firstDownstreamTxByteSent() const PURE; /** * Sets the time when the first byte of the response is sent downstream. @@ -172,7 +173,7 @@ class RequestInfo { * @return the duration between the last byte of the response is sent downstream and the start of * the request. */ - virtual Optional lastDownstreamTxByteSent() const PURE; + virtual absl::optional lastDownstreamTxByteSent() const PURE; /** * Sets the time when the last byte of the response is sent downstream. @@ -183,7 +184,7 @@ class RequestInfo { * @return the total duration of the request (i.e., when the request's ActiveStream is destroyed) * and may be longer than lastDownstreamTxByteSent. */ - virtual Optional requestComplete() const PURE; + virtual absl::optional requestComplete() const PURE; /** * Sets the end time for the request. This method is called once the request has been fully diff --git a/include/envoy/router/BUILD b/include/envoy/router/BUILD index 013d12e8d784..3fa384ec415e 100644 --- a/include/envoy/router/BUILD +++ b/include/envoy/router/BUILD @@ -34,9 +34,9 @@ envoy_cc_library( envoy_cc_library( name = "router_interface", hdrs = ["router.h"], + external_deps = ["abseil_optional"], deps = [ "//include/envoy/access_log:access_log_interface", - "//include/envoy/common:optional", "//include/envoy/http:codec_interface", "//include/envoy/http:codes_interface", "//include/envoy/http:header_map_interface", diff --git a/include/envoy/router/router.h b/include/envoy/router/router.h index 73ed99555942..1e1ead94333a 100644 --- a/include/envoy/router/router.h +++ b/include/envoy/router/router.h @@ -10,7 +10,6 @@ #include "envoy/access_log/access_log.h" #include "envoy/api/v2/core/base.pb.h" -#include "envoy/common/optional.h" #include "envoy/http/codec.h" #include "envoy/http/codes.h" #include "envoy/http/header_map.h" @@ -20,6 +19,8 @@ #include "common/protobuf/protobuf.h" #include "common/protobuf/utility.h" +#include "absl/types/optional.h" + namespace Envoy { namespace Router { @@ -111,9 +112,9 @@ class CorsPolicy { virtual const std::string& maxAge() const PURE; /** - * @return const Optional& Whether access-control-allow-credentials should be true. + * @return const absl::optional& Whether access-control-allow-credentials should be true. */ - virtual const Optional& allowCredentials() const PURE; + virtual const absl::optional& allowCredentials() const PURE; /** * @return bool Whether CORS is enabled for the route or virtual host. @@ -186,7 +187,7 @@ class RetryState { * called. Calling code should proceed with error handling. */ virtual RetryStatus shouldRetry(const Http::HeaderMap* response_headers, - const Optional& reset_reason, + const absl::optional& reset_reason, DoRetryCallback callback) PURE; }; @@ -282,12 +283,12 @@ class HashPolicy { * @param headers stores the HTTP headers for the stream * @param add_cookie is called to add a set-cookie header on the reply sent to the downstream * host - * @return Optional an optional hash value to route on. A hash value might not be + * @return absl::optional an optional hash value to route on. A hash value might not be * returned if for example the specified HTTP header does not exist. */ - virtual Optional generateHash(const std::string& downstream_address, - const Http::HeaderMap& headers, - AddCookieCallback add_cookie) const PURE; + virtual absl::optional generateHash(const std::string& downstream_address, + const Http::HeaderMap& headers, + AddCookieCallback add_cookie) const PURE; }; class MetadataMatchCriterion { diff --git a/include/envoy/runtime/runtime.h b/include/envoy/runtime/runtime.h index c22d59f6d935..9fc144244419 100644 --- a/include/envoy/runtime/runtime.h +++ b/include/envoy/runtime/runtime.h @@ -5,9 +5,10 @@ #include #include -#include "envoy/common/optional.h" #include "envoy/common/pure.h" +#include "absl/types/optional.h" + namespace Envoy { namespace Runtime { @@ -51,7 +52,7 @@ class Snapshot { /** * The possibly parsed integer value from the runtime data. */ - Optional uint_value_; + absl::optional uint_value_; }; /** diff --git a/include/envoy/server/BUILD b/include/envoy/server/BUILD index 67b5d12544f0..5d21efc67b1f 100644 --- a/include/envoy/server/BUILD +++ b/include/envoy/server/BUILD @@ -31,8 +31,8 @@ envoy_cc_library( envoy_cc_library( name = "configuration_interface", hdrs = ["configuration.h"], + external_deps = ["abseil_optional"], deps = [ - "//include/envoy/common:optional", "//include/envoy/ratelimit:ratelimit_interface", "//include/envoy/tracing:http_tracer_interface", "//include/envoy/upstream:cluster_manager_interface", diff --git a/include/envoy/server/configuration.h b/include/envoy/server/configuration.h index 9d62cfdba206..c8f19c5823af 100644 --- a/include/envoy/server/configuration.h +++ b/include/envoy/server/configuration.h @@ -7,11 +7,12 @@ #include #include -#include "envoy/common/optional.h" #include "envoy/ratelimit/ratelimit.h" #include "envoy/tracing/http_tracer.h" #include "envoy/upstream/cluster_manager.h" +#include "absl/types/optional.h" + namespace Envoy { namespace Server { namespace Configuration { @@ -134,9 +135,9 @@ class Initial { virtual Admin& admin() PURE; /** - * @return Optional the path to look for flag files. + * @return absl::optional the path to look for flag files. */ - virtual Optional flagsPath() PURE; + virtual absl::optional flagsPath() PURE; /** * @return Runtime* the local disk runtime configuration or nullptr if there is no configuration. diff --git a/include/envoy/server/filter_config.h b/include/envoy/server/filter_config.h index 56f32c904146..8f90619c77e0 100644 --- a/include/envoy/server/filter_config.h +++ b/include/envoy/server/filter_config.h @@ -90,7 +90,7 @@ class FactoryContext { * @return a new ratelimit client. The implementation depends on the configuration of the server. */ virtual RateLimit::ClientPtr - rateLimitClient(const Optional& timeout) PURE; + rateLimitClient(const absl::optional& timeout) PURE; /** * @return Runtime::Loader& the singleton runtime loader for the server. diff --git a/include/envoy/server/instance.h b/include/envoy/server/instance.h index b6b1299da420..af7fd56e11f4 100644 --- a/include/envoy/server/instance.h +++ b/include/envoy/server/instance.h @@ -127,7 +127,7 @@ class Instance { * @return a new ratelimit client. The implementation depends on the configuration of the server. */ virtual RateLimit::ClientPtr - rateLimitClient(const Optional& timeout) PURE; + rateLimitClient(const absl::optional& timeout) PURE; /** * @return Runtime::Loader& the singleton runtime loader for the server. diff --git a/include/envoy/upstream/BUILD b/include/envoy/upstream/BUILD index b093c3715cdf..6fe663ff209d 100644 --- a/include/envoy/upstream/BUILD +++ b/include/envoy/upstream/BUILD @@ -71,8 +71,8 @@ envoy_cc_library( envoy_cc_library( name = "outlier_detection_interface", hdrs = ["outlier_detection.h"], + external_deps = ["abseil_optional"], deps = [ - "//include/envoy/common:optional", "//include/envoy/common:time_interface", ], ) @@ -90,12 +90,12 @@ envoy_cc_library( envoy_cc_library( name = "upstream_interface", hdrs = ["upstream.h"], + external_deps = ["abseil_optional"], deps = [ ":health_check_host_monitor_interface", ":load_balancer_type_interface", ":resource_manager_interface", "//include/envoy/common:callback", - "//include/envoy/common:optional", "//include/envoy/http:codec_interface", "//include/envoy/network:connection_interface", "//include/envoy/network:transport_socket_interface", diff --git a/include/envoy/upstream/cluster_manager.h b/include/envoy/upstream/cluster_manager.h index f4f022b3c401..817532f88918 100644 --- a/include/envoy/upstream/cluster_manager.h +++ b/include/envoy/upstream/cluster_manager.h @@ -219,7 +219,7 @@ class ClusterManagerFactory { * Create a CDS API provider from configuration proto. */ virtual CdsApiPtr createCds(const envoy::api::v2::core::ConfigSource& cds_config, - const Optional& eds_config, + const absl::optional& eds_config, ClusterManager& cm) PURE; }; diff --git a/include/envoy/upstream/load_balancer.h b/include/envoy/upstream/load_balancer.h index cecd8175745a..58d557b5ef3f 100644 --- a/include/envoy/upstream/load_balancer.h +++ b/include/envoy/upstream/load_balancer.h @@ -22,9 +22,9 @@ class LoadBalancerContext { * Compute and return an optional hash key to use during load balancing. This * method may modify internal state so it should only be called once per * routing attempt. - * @return Optional the optional hash key to use. + * @return absl::optional the optional hash key to use. */ - virtual Optional computeHashKey() PURE; + virtual absl::optional computeHashKey() PURE; /** * @return Router::MetadataMatchCriteria* metadata for use in selecting a subset of hosts diff --git a/include/envoy/upstream/outlier_detection.h b/include/envoy/upstream/outlier_detection.h index 98c9bbb27896..5d7a33c6e613 100644 --- a/include/envoy/upstream/outlier_detection.h +++ b/include/envoy/upstream/outlier_detection.h @@ -5,10 +5,11 @@ #include #include -#include "envoy/common/optional.h" #include "envoy/common/pure.h" #include "envoy/common/time.h" +#include "absl/types/optional.h" + namespace Envoy { namespace Upstream { @@ -67,13 +68,13 @@ class DetectorHostMonitor { * Get the time of last ejection. * @return the last time this host was ejected, if the host has been ejected previously. */ - virtual const Optional& lastEjectionTime() PURE; + virtual const absl::optional& lastEjectionTime() PURE; /** * Get the time of last unejection. * @return the last time this host was unejected, if the host has been unejected previously. */ - virtual const Optional& lastUnejectionTime() PURE; + virtual const absl::optional& lastUnejectionTime() PURE; /** * @return the success rate of the host in the last calculated interval, in the range 0-100. diff --git a/include/envoy/upstream/upstream.h b/include/envoy/upstream/upstream.h index 0ab058f36f04..cf54a51674a4 100644 --- a/include/envoy/upstream/upstream.h +++ b/include/envoy/upstream/upstream.h @@ -10,7 +10,6 @@ #include "envoy/api/v2/core/base.pb.h" #include "envoy/common/callback.h" -#include "envoy/common/optional.h" #include "envoy/http/codec.h" #include "envoy/network/connection.h" #include "envoy/network/transport_socket.h" @@ -20,6 +19,8 @@ #include "envoy/upstream/outlier_detection.h" #include "envoy/upstream/resource_manager.h" +#include "absl/types/optional.h" + namespace Envoy { namespace Upstream { @@ -417,7 +418,8 @@ class ClusterInfo { /** * @return configuration for ring hash load balancing, only used if type is set to ring_hash_lb. */ - virtual const Optional& lbRingHashConfig() const PURE; + virtual const absl::optional& + lbRingHashConfig() const PURE; /** * @return Whether the cluster is currently in maintenance mode and should not be routed to. diff --git a/source/common/access_log/access_log_formatter.cc b/source/common/access_log/access_log_formatter.cc index 7e357345a7a5..146bb760f15f 100644 --- a/source/common/access_log/access_log_formatter.cc +++ b/source/common/access_log/access_log_formatter.cc @@ -26,8 +26,9 @@ FormatterPtr AccessLogFormatUtils::defaultAccessLogFormatter() { return FormatterPtr{new FormatterImpl(DEFAULT_FORMAT)}; } -std::string AccessLogFormatUtils::durationToString(const Optional& time) { - if (time.valid()) { +std::string +AccessLogFormatUtils::durationToString(const absl::optional& time) { + if (time) { return std::to_string( std::chrono::duration_cast(time.value()).count()); } else { @@ -36,8 +37,8 @@ std::string AccessLogFormatUtils::durationToString(const Optional& protocol) { - if (protocol.valid()) { +AccessLogFormatUtils::protocolToString(const absl::optional& protocol) { + if (protocol) { return Http::Utility::getProtocolString(protocol.value()); } return UnspecifiedValueString; @@ -62,7 +63,7 @@ std::string FormatterImpl::format(const Http::HeaderMap& request_headers, void AccessLogFormatParser::parseCommand(const std::string& token, const size_t start, std::string& main_header, std::string& alternative_header, - Optional& max_length) { + absl::optional& max_length) { size_t end_request = token.find(')', start); if (end_request != token.length() - 1) { @@ -83,7 +84,7 @@ void AccessLogFormatParser::parseCommand(const std::string& token, const size_t throw EnvoyException(fmt::format("Length must be an integer, given: {}", length_str)); } - max_length.value(length_value); + max_length = length_value; } std::string header_name = token.substr(start, end_request - start); @@ -119,7 +120,7 @@ std::vector AccessLogFormatParser::parse(const std::string& format if (token.find("REQ(") == 0) { std::string main_header, alternative_header; - Optional max_length; + absl::optional max_length; const size_t start = 4; parseCommand(token, start, main_header, alternative_header, max_length); @@ -128,7 +129,7 @@ std::vector AccessLogFormatParser::parse(const std::string& format FormatterPtr(new RequestHeaderFormatter(main_header, alternative_header, max_length))); } else if (token.find("RESP(") == 0) { std::string main_header, alternative_header; - Optional max_length; + absl::optional max_length; const size_t start = 5; parseCommand(token, start, main_header, alternative_header, max_length); @@ -175,9 +176,8 @@ RequestInfoFormatter::RequestInfoFormatter(const std::string& field_name) { }; } else if (field_name == "RESPONSE_CODE") { field_extractor_ = [](const RequestInfo::RequestInfo& request_info) { - return request_info.responseCode().valid() - ? std::to_string(request_info.responseCode().value()) - : "0"; + return request_info.responseCode() ? std::to_string(request_info.responseCode().value()) + : "0"; }; } else if (field_name == "BYTES_SENT") { field_extractor_ = [](const RequestInfo::RequestInfo& request_info) { @@ -253,7 +253,7 @@ std::string PlainStringFormatter::format(const Http::HeaderMap&, const Http::Hea HeaderFormatter::HeaderFormatter(const std::string& main_header, const std::string& alternative_header, - const Optional& max_length) + const absl::optional& max_length) : main_header_(main_header), alternative_header_(alternative_header), max_length_(max_length) {} std::string HeaderFormatter::format(const Http::HeaderMap& headers) const { @@ -270,7 +270,7 @@ std::string HeaderFormatter::format(const Http::HeaderMap& headers) const { header_value_string = header->value().c_str(); } - if (max_length_.valid() && header_value_string.length() > max_length_.value()) { + if (max_length_ && header_value_string.length() > max_length_.value()) { return header_value_string.substr(0, max_length_.value()); } @@ -279,7 +279,7 @@ std::string HeaderFormatter::format(const Http::HeaderMap& headers) const { ResponseHeaderFormatter::ResponseHeaderFormatter(const std::string& main_header, const std::string& alternative_header, - const Optional& max_length) + const absl::optional& max_length) : HeaderFormatter(main_header, alternative_header, max_length) {} std::string ResponseHeaderFormatter::format(const Http::HeaderMap&, @@ -290,7 +290,7 @@ std::string ResponseHeaderFormatter::format(const Http::HeaderMap&, RequestHeaderFormatter::RequestHeaderFormatter(const std::string& main_header, const std::string& alternative_header, - const Optional& max_length) + const absl::optional& max_length) : HeaderFormatter(main_header, alternative_header, max_length) {} std::string RequestHeaderFormatter::format(const Http::HeaderMap& request_headers, diff --git a/source/common/access_log/access_log_formatter.h b/source/common/access_log/access_log_formatter.h index 7b41e6481ed8..57ea6807fdac 100644 --- a/source/common/access_log/access_log_formatter.h +++ b/source/common/access_log/access_log_formatter.h @@ -5,10 +5,11 @@ #include #include "envoy/access_log/access_log.h" -#include "envoy/common/optional.h" #include "envoy/common/time.h" #include "envoy/request_info/request_info.h" +#include "absl/types/optional.h" + namespace Envoy { namespace AccessLog { @@ -21,7 +22,7 @@ class AccessLogFormatParser { private: static void parseCommand(const std::string& token, const size_t start, std::string& main_header, - std::string& alternative_header, Optional& max_length); + std::string& alternative_header, absl::optional& max_length); }; /** @@ -30,8 +31,8 @@ class AccessLogFormatParser { class AccessLogFormatUtils { public: static FormatterPtr defaultAccessLogFormatter(); - static const std::string& protocolToString(const Optional& protocol); - static std::string durationToString(const Optional& time); + static const std::string& protocolToString(const absl::optional& protocol); + static std::string durationToString(const absl::optional& time); private: AccessLogFormatUtils(); @@ -74,14 +75,14 @@ class PlainStringFormatter : public Formatter { class HeaderFormatter { public: HeaderFormatter(const std::string& main_header, const std::string& alternative_header, - const Optional& max_length); + const absl::optional& max_length); std::string format(const Http::HeaderMap& headers) const; private: Http::LowerCaseString main_header_; Http::LowerCaseString alternative_header_; - Optional max_length_; + absl::optional max_length_; }; /** @@ -90,7 +91,7 @@ class HeaderFormatter { class RequestHeaderFormatter : public Formatter, HeaderFormatter { public: RequestHeaderFormatter(const std::string& main_header, const std::string& alternative_header, - const Optional& max_length); + const absl::optional& max_length); // Formatter::format std::string format(const Http::HeaderMap& request_headers, const Http::HeaderMap&, @@ -103,7 +104,7 @@ class RequestHeaderFormatter : public Formatter, HeaderFormatter { class ResponseHeaderFormatter : public Formatter, HeaderFormatter { public: ResponseHeaderFormatter(const std::string& main_header, const std::string& alternative_header, - const Optional& max_length); + const absl::optional& max_length); // Formatter::format std::string format(const Http::HeaderMap&, const Http::HeaderMap& response_headers, diff --git a/source/common/access_log/access_log_impl.cc b/source/common/access_log/access_log_impl.cc index b2d61e5ba094..ca22b1770ca6 100644 --- a/source/common/access_log/access_log_impl.cc +++ b/source/common/access_log/access_log_impl.cc @@ -3,7 +3,6 @@ #include #include -#include "envoy/common/optional.h" #include "envoy/common/time.h" #include "envoy/filesystem/filesystem.h" #include "envoy/http/header_map.h" @@ -20,6 +19,8 @@ #include "common/runtime/uuid_util.h" #include "common/tracing/http_tracer_impl.h" +#include "absl/types/optional.h" + namespace Envoy { namespace AccessLog { @@ -77,7 +78,7 @@ bool TraceableRequestFilter::evaluate(const RequestInfo::RequestInfo& info, } bool StatusCodeFilter::evaluate(const RequestInfo::RequestInfo& info, const Http::HeaderMap&) { - if (!info.responseCode().valid()) { + if (!info.responseCode()) { return compareAgainstValue(0ULL); } @@ -85,8 +86,8 @@ bool StatusCodeFilter::evaluate(const RequestInfo::RequestInfo& info, const Http } bool DurationFilter::evaluate(const RequestInfo::RequestInfo& info, const Http::HeaderMap&) { - Optional final = info.requestComplete(); - ASSERT(final.valid()); + absl::optional final = info.requestComplete(); + ASSERT(final); return compareAgainstValue( std::chrono::duration_cast(final.value()).count()); diff --git a/source/common/access_log/grpc_access_log_impl.cc b/source/common/access_log/grpc_access_log_impl.cc index 59df6d79dc7c..f5c734e31757 100644 --- a/source/common/access_log/grpc_access_log_impl.cc +++ b/source/common/access_log/grpc_access_log_impl.cc @@ -170,44 +170,44 @@ void HttpGrpcAccessLog::log(const Http::HeaderMap* request_headers, request_info.startTime().time_since_epoch()) .count())); - Optional dur = request_info.lastDownstreamRxByteReceived(); - if (dur.valid()) { + absl::optional dur = request_info.lastDownstreamRxByteReceived(); + if (dur) { common_properties->mutable_time_to_last_rx_byte()->MergeFrom( Protobuf::util::TimeUtil::NanosecondsToDuration(dur.value().count())); } dur = request_info.firstUpstreamTxByteSent(); - if (dur.valid()) { + if (dur) { common_properties->mutable_time_to_first_upstream_tx_byte()->MergeFrom( Protobuf::util::TimeUtil::NanosecondsToDuration(dur.value().count())); } dur = request_info.lastUpstreamTxByteSent(); - if (dur.valid()) { + if (dur) { common_properties->mutable_time_to_last_upstream_tx_byte()->MergeFrom( Protobuf::util::TimeUtil::NanosecondsToDuration(dur.value().count())); } dur = request_info.firstUpstreamRxByteReceived(); - if (dur.valid()) { + if (dur) { common_properties->mutable_time_to_first_upstream_rx_byte()->MergeFrom( Protobuf::util::TimeUtil::NanosecondsToDuration(dur.value().count())); } dur = request_info.lastUpstreamRxByteReceived(); - if (dur.valid()) { + if (dur) { common_properties->mutable_time_to_last_upstream_rx_byte()->MergeFrom( Protobuf::util::TimeUtil::NanosecondsToDuration(dur.value().count())); } dur = request_info.firstDownstreamTxByteSent(); - if (dur.valid()) { + if (dur) { common_properties->mutable_time_to_first_downstream_tx_byte()->MergeFrom( Protobuf::util::TimeUtil::NanosecondsToDuration(dur.value().count())); } dur = request_info.lastDownstreamTxByteSent(); - if (dur.valid()) { + if (dur) { common_properties->mutable_time_to_last_downstream_tx_byte()->MergeFrom( Protobuf::util::TimeUtil::NanosecondsToDuration(dur.value().count())); } @@ -224,7 +224,7 @@ void HttpGrpcAccessLog::log(const Http::HeaderMap* request_headers, } responseFlagsToAccessLogResponseFlags(*common_properties, request_info); - if (request_info.protocol().valid()) { + if (request_info.protocol()) { switch (request_info.protocol().value()) { case Http::Protocol::Http10: log_entry->set_protocol_version( @@ -275,7 +275,7 @@ void HttpGrpcAccessLog::log(const Http::HeaderMap* request_headers, // HTTP response properties. // TODO(mattklein123): Populate custom response headers. auto* response_properties = log_entry->mutable_response(); - if (request_info.responseCode().valid()) { + if (request_info.responseCode()) { response_properties->mutable_response_code()->set_value(request_info.responseCode().value()); } response_properties->set_response_headers_bytes(response_headers->byteSize()); diff --git a/source/common/common/shared_memory_hash_set.h b/source/common/common/shared_memory_hash_set.h index 5af93469f97e..dcff5a1282d7 100644 --- a/source/common/common/shared_memory_hash_set.h +++ b/source/common/common/shared_memory_hash_set.h @@ -4,6 +4,8 @@ #include #include +#include "envoy/common/exception.h" + #include "common/common/assert.h" #include "common/common/fmt.h" #include "common/common/logger.h" diff --git a/source/common/config/BUILD b/source/common/config/BUILD index 20971a5a625f..3e419ad95f17 100644 --- a/source/common/config/BUILD +++ b/source/common/config/BUILD @@ -54,13 +54,13 @@ envoy_cc_library( name = "cds_json_lib", srcs = ["cds_json.cc"], hdrs = ["cds_json.h"], + external_deps = ["abseil_optional"], deps = [ ":address_json_lib", ":json_utility_lib", ":protocol_json_lib", ":tls_context_json_lib", ":utility_lib", - "//include/envoy/common:optional", "//include/envoy/json:json_object_interface", "//include/envoy/upstream:cluster_manager_interface", "//source/common/common:assert_lib", diff --git a/source/common/config/bootstrap_json.cc b/source/common/config/bootstrap_json.cc index d14cefb9954d..5d9e3c31cb7d 100644 --- a/source/common/config/bootstrap_json.cc +++ b/source/common/config/bootstrap_json.cc @@ -17,16 +17,17 @@ void BootstrapJson::translateClusterManagerBootstrap( const Json::Object& json_cluster_manager, envoy::config::bootstrap::v2::Bootstrap& bootstrap) { json_cluster_manager.validateSchema(Json::Schema::CLUSTER_MANAGER_SCHEMA); - Optional eds_config; + absl::optional eds_config; if (json_cluster_manager.hasObject("sds")) { const auto json_sds = json_cluster_manager.getObject("sds"); auto* cluster = bootstrap.mutable_static_resources()->mutable_clusters()->Add(); Config::CdsJson::translateCluster(*json_sds->getObject("cluster"), - Optional(), *cluster); + absl::optional(), + *cluster); Config::Utility::translateEdsConfig( *json_sds, *bootstrap.mutable_dynamic_resources()->mutable_deprecated_v1()->mutable_sds_config()); - eds_config.value(bootstrap.dynamic_resources().deprecated_v1().sds_config()); + eds_config = bootstrap.dynamic_resources().deprecated_v1().sds_config(); } if (json_cluster_manager.hasObject("cds")) { diff --git a/source/common/config/cds_json.cc b/source/common/config/cds_json.cc index 37c19fbd3f84..3cf33249a764 100644 --- a/source/common/config/cds_json.cc +++ b/source/common/config/cds_json.cc @@ -98,7 +98,7 @@ void CdsJson::translateOutlierDetection( } void CdsJson::translateCluster(const Json::Object& json_cluster, - const Optional& eds_config, + const absl::optional& eds_config, envoy::api::v2::Cluster& cluster) { json_cluster.validateSchema(Json::Schema::CLUSTER_SCHEMA); @@ -140,6 +140,9 @@ void CdsJson::translateCluster(const Json::Object& json_cluster, cluster.set_type(envoy::api::v2::Cluster::ORIGINAL_DST); } else { ASSERT(string_type == "sds"); + if (!eds_config) { + throw EnvoyException("cannot create sds cluster with no sds config"); + } cluster.set_type(envoy::api::v2::Cluster::EDS); cluster.mutable_eds_cluster_config()->mutable_eds_config()->CopyFrom(eds_config.value()); JSON_UTIL_SET_STRING(json_cluster, *cluster.mutable_eds_cluster_config(), service_name); diff --git a/source/common/config/cds_json.h b/source/common/config/cds_json.h index b4f3f7d11230..f2995074f79a 100644 --- a/source/common/config/cds_json.h +++ b/source/common/config/cds_json.h @@ -2,10 +2,11 @@ #include "envoy/api/v2/cds.pb.h" #include "envoy/api/v2/cluster/circuit_breaker.pb.h" -#include "envoy/common/optional.h" #include "envoy/json/json_object.h" #include "envoy/upstream/cluster_manager.h" +#include "absl/types/optional.h" + namespace Envoy { namespace Config { @@ -62,7 +63,7 @@ class CdsJson { * @param cluster destination v2 envoy::api::v2::Cluster. */ static void translateCluster(const Json::Object& json_cluster, - const Optional& eds_config, + const absl::optional& eds_config, envoy::api::v2::Cluster& cluster); }; diff --git a/source/common/ext_authz/ext_authz_impl.cc b/source/common/ext_authz/ext_authz_impl.cc index 3f0534d5dfb5..1b51a9d292f6 100644 --- a/source/common/ext_authz/ext_authz_impl.cc +++ b/source/common/ext_authz/ext_authz_impl.cc @@ -21,7 +21,7 @@ namespace Envoy { namespace ExtAuthz { GrpcClientImpl::GrpcClientImpl(Grpc::AsyncClientPtr&& async_client, - const Optional& timeout) + const absl::optional& timeout) : service_method_(*Protobuf::DescriptorPool::generated_pool()->FindMethodByName( "envoy.service.auth.v2.Authorization.Check")), async_client_(std::move(async_client)), timeout_(timeout) {} @@ -135,7 +135,7 @@ void CheckRequestUtils::setHttpRequest( httpreq.set_size(sdfc->requestInfo().bytesReceived()); // Set protocol - if (sdfc->requestInfo().protocol().valid()) { + if (sdfc->requestInfo().protocol()) { httpreq.set_protocol( Envoy::Http::Utility::getProtocolString(sdfc->requestInfo().protocol().value())); } diff --git a/source/common/ext_authz/ext_authz_impl.h b/source/common/ext_authz/ext_authz_impl.h index a7b79bf1a156..2474369f8a25 100644 --- a/source/common/ext_authz/ext_authz_impl.h +++ b/source/common/ext_authz/ext_authz_impl.h @@ -38,7 +38,7 @@ typedef ConstSingleton Constants; class GrpcClientImpl : public Client, public ExtAuthzAsyncCallbacks { public: GrpcClientImpl(Grpc::AsyncClientPtr&& async_client, - const Optional& timeout); + const absl::optional& timeout); ~GrpcClientImpl(); // ExtAuthz::Client @@ -57,7 +57,7 @@ class GrpcClientImpl : public Client, public ExtAuthzAsyncCallbacks { const Protobuf::MethodDescriptor& service_method_; Grpc::AsyncClientPtr async_client_; Grpc::AsyncRequest* request_{}; - Optional timeout_; + absl::optional timeout_; RequestCallbacks* callbacks_{}; }; diff --git a/source/common/filter/tcp_proxy.cc b/source/common/filter/tcp_proxy.cc index fcfe3f24d22e..275757285b06 100644 --- a/source/common/filter/tcp_proxy.cc +++ b/source/common/filter/tcp_proxy.cc @@ -42,8 +42,8 @@ TcpProxyConfig::SharedConfig::SharedConfig( : stats_scope_(context.scope().createScope(fmt::format("tcp.{}.", config.stat_prefix()))), stats_(generateStats(*stats_scope_)) { if (config.has_idle_timeout()) { - idle_timeout_.value(std::chrono::milliseconds( - Protobuf::util::TimeUtil::DurationToMilliseconds(config.idle_timeout()))); + idle_timeout_ = std::chrono::milliseconds( + Protobuf::util::TimeUtil::DurationToMilliseconds(config.idle_timeout())); } } @@ -472,7 +472,7 @@ void TcpProxy::onUpstreamEvent(Network::ConnectionEvent event) { Upstream::Outlier::Result::SUCCESS); onConnectionSuccess(); - if (config_ != nullptr && config_->idleTimeout().valid()) { + if (config_ != nullptr && config_->idleTimeout()) { // The idle_timer_ can be moved to a TcpProxyDrainer, so related callbacks call into // the UpstreamCallbacks, which has the same lifetime as the timer, and can dispatch // the call to either TcpProxy or to TcpProxyDrainer, depending on the current state. @@ -497,7 +497,7 @@ void TcpProxy::onIdleTimeout() { void TcpProxy::resetIdleTimer() { if (idle_timer_ != nullptr) { - ASSERT(config_->idleTimeout().valid()); + ASSERT(config_->idleTimeout()); idle_timer_->enableTimer(config_->idleTimeout().value()); } } diff --git a/source/common/filter/tcp_proxy.h b/source/common/filter/tcp_proxy.h index bb6699b0494f..ac9bf1df118f 100644 --- a/source/common/filter/tcp_proxy.h +++ b/source/common/filter/tcp_proxy.h @@ -71,7 +71,7 @@ class TcpProxyConfig { SharedConfig(const envoy::config::filter::network::tcp_proxy::v2::TcpProxy& config, Server::Configuration::FactoryContext& context); const TcpProxyStats& stats() { return stats_; } - const Optional& idleTimeout() { return idle_timeout_; } + const absl::optional& idleTimeout() { return idle_timeout_; } private: static TcpProxyStats generateStats(Stats::Scope& scope); @@ -81,7 +81,7 @@ class TcpProxyConfig { const Stats::ScopePtr stats_scope_; const TcpProxyStats stats_; - Optional idle_timeout_; + absl::optional idle_timeout_; }; typedef std::shared_ptr SharedConfigSharedPtr; @@ -102,7 +102,9 @@ class TcpProxyConfig { const TcpProxyStats& stats() { return shared_config_->stats(); } const std::vector& accessLogs() { return access_logs_; } uint32_t maxConnectAttempts() const { return max_connect_attempts_; } - const Optional& idleTimeout() { return shared_config_->idleTimeout(); } + const absl::optional& idleTimeout() { + return shared_config_->idleTimeout(); + } TcpProxyUpstreamDrainManager& drainManager(); SharedConfigSharedPtr sharedConfig() { return shared_config_; } const Router::MetadataMatchCriteria* metadataMatchCriteria() { @@ -149,7 +151,7 @@ class TcpProxy : public Network::ReadFilter, void initializeReadFilterCallbacks(Network::ReadFilterCallbacks& callbacks) override; // Upstream::LoadBalancerContext - Optional computeHashKey() override { return {}; } + absl::optional computeHashKey() override { return {}; } const Router::MetadataMatchCriteria* metadataMatchCriteria() const override { if (config_) { return config_->metadataMatchCriteria(); diff --git a/source/common/grpc/BUILD b/source/common/grpc/BUILD index 6c362eda992e..63ac961cc433 100644 --- a/source/common/grpc/BUILD +++ b/source/common/grpc/BUILD @@ -50,8 +50,8 @@ envoy_cc_library( name = "common_lib", srcs = ["common.cc"], hdrs = ["common.h"], + external_deps = ["abseil_optional"], deps = [ - "//include/envoy/common:optional", "//include/envoy/grpc:status", "//include/envoy/http:header_map_interface", "//include/envoy/http:message_interface", diff --git a/source/common/grpc/async_client_impl.cc b/source/common/grpc/async_client_impl.cc index 33ebaf3f2920..abde58eff497 100644 --- a/source/common/grpc/async_client_impl.cc +++ b/source/common/grpc/async_client_impl.cc @@ -24,7 +24,7 @@ AsyncClientImpl::~AsyncClientImpl() { AsyncRequest* AsyncClientImpl::send(const Protobuf::MethodDescriptor& service_method, const Protobuf::Message& request, AsyncRequestCallbacks& callbacks, Tracing::Span& parent_span, - const Optional& timeout) { + const absl::optional& timeout) { auto* const async_request = new AsyncRequestImpl(*this, service_method, request, callbacks, parent_span, timeout); std::unique_ptr grpc_stream{async_request}; @@ -40,7 +40,7 @@ AsyncRequest* AsyncClientImpl::send(const Protobuf::MethodDescriptor& service_me AsyncStream* AsyncClientImpl::start(const Protobuf::MethodDescriptor& service_method, AsyncStreamCallbacks& callbacks) { - const Optional no_timeout; + const absl::optional no_timeout; auto grpc_stream = std::make_unique(*this, service_method, callbacks, no_timeout); @@ -56,13 +56,13 @@ AsyncStream* AsyncClientImpl::start(const Protobuf::MethodDescriptor& service_me AsyncStreamImpl::AsyncStreamImpl(AsyncClientImpl& parent, const Protobuf::MethodDescriptor& service_method, AsyncStreamCallbacks& callbacks, - const Optional& timeout) + const absl::optional& timeout) : parent_(parent), service_method_(service_method), callbacks_(callbacks), timeout_(timeout) {} void AsyncStreamImpl::initialize(bool buffer_body_for_retry) { auto& http_async_client = parent_.cm_.httpAsyncClientForCluster(parent_.remote_cluster_name_); dispatcher_ = &http_async_client.dispatcher(); - stream_ = http_async_client.start(*this, Optional(timeout_), + stream_ = http_async_client.start(*this, absl::optional(timeout_), buffer_body_for_retry); if (stream_ == nullptr) { @@ -94,7 +94,7 @@ void AsyncStreamImpl::onHeaders(Http::HeaderMapPtr&& headers, bool end_stream) { if (http_response_status != enumToInt(Http::Code::OK)) { // https://github.com/grpc/grpc/blob/master/doc/http-grpc-status-mapping.md requires that // grpc-status be used if available. - if (end_stream && grpc_status.valid()) { + if (end_stream && grpc_status) { onTrailers(std::move(headers)); return; } @@ -143,8 +143,8 @@ void AsyncStreamImpl::onTrailers(Http::HeaderMapPtr&& trailers) { auto grpc_status = Common::getGrpcStatus(*trailers); const std::string grpc_message = Common::getGrpcMessage(*trailers); callbacks_.onReceiveTrailingMetadata(std::move(trailers)); - if (!grpc_status.valid()) { - grpc_status.value(Status::GrpcStatus::Unknown); + if (!grpc_status) { + grpc_status = Status::GrpcStatus::Unknown; } callbacks_.onRemoteClose(grpc_status.value(), grpc_message); cleanup(); @@ -194,7 +194,7 @@ AsyncRequestImpl::AsyncRequestImpl(AsyncClientImpl& parent, const Protobuf::MethodDescriptor& service_method, const Protobuf::Message& request, AsyncRequestCallbacks& callbacks, Tracing::Span& parent_span, - const Optional& timeout) + const absl::optional& timeout) : AsyncStreamImpl(parent, service_method, *this, timeout), request_(request), callbacks_(callbacks) { diff --git a/source/common/grpc/async_client_impl.h b/source/common/grpc/async_client_impl.h index 96cf69af5792..06d8d173dc73 100644 --- a/source/common/grpc/async_client_impl.h +++ b/source/common/grpc/async_client_impl.h @@ -21,7 +21,7 @@ class AsyncClientImpl final : public AsyncClient { AsyncRequest* send(const Protobuf::MethodDescriptor& service_method, const Protobuf::Message& request, AsyncRequestCallbacks& callbacks, Tracing::Span& parent_span, - const Optional& timeout) override; + const absl::optional& timeout) override; AsyncStream* start(const Protobuf::MethodDescriptor& service_method, AsyncStreamCallbacks& callbacks) override; @@ -42,7 +42,7 @@ class AsyncStreamImpl : public AsyncStream, public: AsyncStreamImpl(AsyncClientImpl& parent, const Protobuf::MethodDescriptor& service_method, AsyncStreamCallbacks& callbacks, - const Optional& timeout); + const absl::optional& timeout); virtual void initialize(bool buffer_body_for_retry); @@ -64,14 +64,15 @@ class AsyncStreamImpl : public AsyncStream, void streamError(Status::GrpcStatus grpc_status) { streamError(grpc_status, EMPTY_STRING); } void cleanup(); - void trailerResponse(Optional grpc_status, const std::string& grpc_message); + void trailerResponse(absl::optional grpc_status, + const std::string& grpc_message); Event::Dispatcher* dispatcher_{}; Http::MessagePtr headers_message_; AsyncClientImpl& parent_; const Protobuf::MethodDescriptor& service_method_; AsyncStreamCallbacks& callbacks_; - const Optional& timeout_; + const absl::optional& timeout_; bool http_reset_{}; Http::AsyncClient::Stream* stream_{}; Decoder decoder_; @@ -85,7 +86,8 @@ class AsyncRequestImpl : public AsyncRequest, public AsyncStreamImpl, AsyncStrea public: AsyncRequestImpl(AsyncClientImpl& parent, const Protobuf::MethodDescriptor& service_method, const Protobuf::Message& request, AsyncRequestCallbacks& callbacks, - Tracing::Span& parent_span, const Optional& timeout); + Tracing::Span& parent_span, + const absl::optional& timeout); void initialize(bool buffer_body_for_retry) override; diff --git a/source/common/grpc/common.cc b/source/common/grpc/common.cc index e6948a58e055..6f7714cc5156 100644 --- a/source/common/grpc/common.cc +++ b/source/common/grpc/common.cc @@ -91,18 +91,18 @@ void Common::chargeStat(const Upstream::ClusterInfo& cluster, const std::string& chargeStat(cluster, "grpc", grpc_service, grpc_method, success); } -Optional Common::getGrpcStatus(const Http::HeaderMap& trailers) { +absl::optional Common::getGrpcStatus(const Http::HeaderMap& trailers) { const Http::HeaderEntry* grpc_status_header = trailers.GrpcStatus(); uint64_t grpc_status_code; if (!grpc_status_header || grpc_status_header->value().empty()) { - return Optional(); + return absl::optional(); } if (!StringUtil::atoul(grpc_status_header->value().c_str(), grpc_status_code) || grpc_status_code > Status::GrpcStatus::Unauthenticated) { - return Optional(Status::GrpcStatus::InvalidCode); + return absl::optional(Status::GrpcStatus::InvalidCode); } - return Optional(static_cast(grpc_status_code)); + return absl::optional(static_cast(grpc_status_code)); } std::string Common::getGrpcMessage(const Http::HeaderMap& trailers) { @@ -248,13 +248,14 @@ Http::MessagePtr Common::prepareHeaders(const std::string& upstream_cluster, void Common::checkForHeaderOnlyError(Http::Message& http_response) { // First check for grpc-status in headers. If it is here, we have an error. - Optional grpc_status_code = Common::getGrpcStatus(http_response.headers()); - if (!grpc_status_code.valid()) { + absl::optional grpc_status_code = + Common::getGrpcStatus(http_response.headers()); + if (!grpc_status_code) { return; } if (grpc_status_code.value() == Status::GrpcStatus::InvalidCode) { - throw Exception(Optional(), "bad grpc-status header"); + throw Exception(absl::optional(), "bad grpc-status header"); } const Http::HeaderEntry* grpc_status_message = http_response.headers().GrpcMessage(); @@ -264,19 +265,20 @@ void Common::checkForHeaderOnlyError(Http::Message& http_response) { void Common::validateResponse(Http::Message& http_response) { if (Http::Utility::getResponseStatus(http_response.headers()) != enumToInt(Http::Code::OK)) { - throw Exception(Optional(), "non-200 response code"); + throw Exception(absl::optional(), "non-200 response code"); } checkForHeaderOnlyError(http_response); // Check for existence of trailers. if (!http_response.trailers()) { - throw Exception(Optional(), "no response trailers"); + throw Exception(absl::optional(), "no response trailers"); } - Optional grpc_status_code = Common::getGrpcStatus(*http_response.trailers()); - if (!grpc_status_code.valid() || grpc_status_code.value() < 0) { - throw Exception(Optional(), "bad grpc-status trailer"); + absl::optional grpc_status_code = + Common::getGrpcStatus(*http_response.trailers()); + if (!grpc_status_code || grpc_status_code.value() < 0) { + throw Exception(absl::optional(), "bad grpc-status trailer"); } if (grpc_status_code.value() != 0) { diff --git a/source/common/grpc/common.h b/source/common/grpc/common.h index 9ce4b67c5895..910018bcfd53 100644 --- a/source/common/grpc/common.h +++ b/source/common/grpc/common.h @@ -4,7 +4,6 @@ #include #include "envoy/common/exception.h" -#include "envoy/common/optional.h" #include "envoy/grpc/status.h" #include "envoy/http/filter.h" #include "envoy/http/header_map.h" @@ -13,15 +12,17 @@ #include "common/protobuf/protobuf.h" +#include "absl/types/optional.h" + namespace Envoy { namespace Grpc { class Exception : public EnvoyException { public: - Exception(const Optional& grpc_status, const std::string& message) + Exception(const absl::optional& grpc_status, const std::string& message) : EnvoyException(message), grpc_status_(grpc_status) {} - const Optional grpc_status_; + const absl::optional grpc_status_; }; class Common { @@ -42,10 +43,10 @@ class Common { /** * Returns the GrpcStatus code from a given set of trailers, if present. * @param trailers the trailers to parse. - * @return Optional the parsed status code or InvalidCode if no valid status - * is found. + * @return absl::optional the parsed status code or InvalidCode if no valid + * status is found. */ - static Optional getGrpcStatus(const Http::HeaderMap& trailers); + static absl::optional getGrpcStatus(const Http::HeaderMap& trailers); /** * Returns the grpc-message from a given set of trailers, if present. diff --git a/source/common/grpc/google_async_client_impl.cc b/source/common/grpc/google_async_client_impl.cc index 6053cbbd16f0..667ebae8288f 100644 --- a/source/common/grpc/google_async_client_impl.cc +++ b/source/common/grpc/google_async_client_impl.cc @@ -104,11 +104,11 @@ GoogleAsyncClientImpl::~GoogleAsyncClientImpl() { } } -AsyncRequest* GoogleAsyncClientImpl::send(const Protobuf::MethodDescriptor& service_method, - const Protobuf::Message& request, - AsyncRequestCallbacks& callbacks, - Tracing::Span& parent_span, - const Optional& timeout) { +AsyncRequest* +GoogleAsyncClientImpl::send(const Protobuf::MethodDescriptor& service_method, + const Protobuf::Message& request, AsyncRequestCallbacks& callbacks, + Tracing::Span& parent_span, + const absl::optional& timeout) { auto* const async_request = new GoogleAsyncRequestImpl(*this, service_method, request, callbacks, parent_span, timeout); std::unique_ptr grpc_stream{async_request}; @@ -124,7 +124,7 @@ AsyncRequest* GoogleAsyncClientImpl::send(const Protobuf::MethodDescriptor& serv AsyncStream* GoogleAsyncClientImpl::start(const Protobuf::MethodDescriptor& service_method, AsyncStreamCallbacks& callbacks) { - const Optional no_timeout; + const absl::optional no_timeout; auto grpc_stream = std::make_unique(*this, service_method, callbacks, no_timeout); @@ -137,10 +137,9 @@ AsyncStream* GoogleAsyncClientImpl::start(const Protobuf::MethodDescriptor& serv return active_streams_.front().get(); } -GoogleAsyncStreamImpl::GoogleAsyncStreamImpl(GoogleAsyncClientImpl& parent, - const Protobuf::MethodDescriptor& service_method, - AsyncStreamCallbacks& callbacks, - const Optional& timeout) +GoogleAsyncStreamImpl::GoogleAsyncStreamImpl( + GoogleAsyncClientImpl& parent, const Protobuf::MethodDescriptor& service_method, + AsyncStreamCallbacks& callbacks, const absl::optional& timeout) : parent_(parent), tls_(parent_.tls_), dispatcher_(parent_.dispatcher_), stub_(parent_.stub_), service_method_(service_method), callbacks_(callbacks), timeout_(timeout) {} @@ -153,9 +152,9 @@ GoogleAsyncStreamImpl::~GoogleAsyncStreamImpl() { void GoogleAsyncStreamImpl::initialize(bool /*buffer_body_for_retry*/) { parent_.stats_.streams_total_->inc(); gpr_timespec abs_deadline = - timeout_.valid() ? gpr_time_add(gpr_now(GPR_CLOCK_REALTIME), - gpr_time_from_millis(timeout_.value().count(), GPR_TIMESPAN)) - : gpr_inf_future(GPR_CLOCK_REALTIME); + timeout_ ? gpr_time_add(gpr_now(GPR_CLOCK_REALTIME), + gpr_time_from_millis(timeout_.value().count(), GPR_TIMESPAN)) + : gpr_inf_future(GPR_CLOCK_REALTIME); ctxt_.set_deadline(abs_deadline); // Fill service-wide initial metadata. for (const auto& header_value : parent_.initial_metadata_) { @@ -224,7 +223,7 @@ void GoogleAsyncStreamImpl::writeQueued() { write_pending_ = true; const PendingMessage& msg = write_pending_queue_.front(); - if (!msg.buf_.valid()) { + if (!msg.buf_) { ASSERT(msg.end_stream_); rw_->WritesDone(&write_last_tag_); ++inflight_tags_; @@ -404,12 +403,10 @@ void GoogleAsyncStreamImpl::cleanup() { } } -GoogleAsyncRequestImpl::GoogleAsyncRequestImpl(GoogleAsyncClientImpl& parent, - const Protobuf::MethodDescriptor& service_method, - const Protobuf::Message& request, - AsyncRequestCallbacks& callbacks, - Tracing::Span& parent_span, - const Optional& timeout) +GoogleAsyncRequestImpl::GoogleAsyncRequestImpl( + GoogleAsyncClientImpl& parent, const Protobuf::MethodDescriptor& service_method, + const Protobuf::Message& request, AsyncRequestCallbacks& callbacks, Tracing::Span& parent_span, + const absl::optional& timeout) : GoogleAsyncStreamImpl(parent, service_method, *this, timeout), request_(request), callbacks_(callbacks) { current_span_ = parent_span.spawnChild(Tracing::EgressConfig::get(), diff --git a/source/common/grpc/google_async_client_impl.h b/source/common/grpc/google_async_client_impl.h index e11006e9c990..b898f002ad95 100644 --- a/source/common/grpc/google_async_client_impl.h +++ b/source/common/grpc/google_async_client_impl.h @@ -159,7 +159,7 @@ class GoogleAsyncClientImpl final : public AsyncClient, Logger::Loggable& timeout) override; + const absl::optional& timeout) override; AsyncStream* start(const Protobuf::MethodDescriptor& service_method, AsyncStreamCallbacks& callbacks) override; @@ -192,7 +192,7 @@ class GoogleAsyncStreamImpl : public AsyncStream, GoogleAsyncStreamImpl(GoogleAsyncClientImpl& parent, const Protobuf::MethodDescriptor& service_method, AsyncStreamCallbacks& callbacks, - const Optional& timeout); + const absl::optional& timeout); ~GoogleAsyncStreamImpl(); virtual void initialize(bool buffer_body_for_retry); @@ -246,7 +246,7 @@ class GoogleAsyncStreamImpl : public AsyncStream, PendingMessage() : end_stream_(true) {} const grpc::Slice slice_; - const Optional buf_; + const absl::optional buf_; const bool end_stream_; }; @@ -269,7 +269,7 @@ class GoogleAsyncStreamImpl : public AsyncStream, std::shared_ptr stub_; const Protobuf::MethodDescriptor& service_method_; AsyncStreamCallbacks& callbacks_; - const Optional& timeout_; + const absl::optional& timeout_; grpc::ClientContext ctxt_; std::unique_ptr rw_; std::queue write_pending_queue_; @@ -307,7 +307,7 @@ class GoogleAsyncRequestImpl : public AsyncRequest, const Protobuf::MethodDescriptor& service_method, const Protobuf::Message& request, AsyncRequestCallbacks& callbacks, Tracing::Span& parent_span, - const Optional& timeout); + const absl::optional& timeout); void initialize(bool buffer_body_for_retry) override; diff --git a/source/common/grpc/http1_bridge_filter.cc b/source/common/grpc/http1_bridge_filter.cc index 33c38d4d7cde..73ca1b35d635 100644 --- a/source/common/grpc/http1_bridge_filter.cc +++ b/source/common/grpc/http1_bridge_filter.cc @@ -28,8 +28,8 @@ Http::FilterHeadersStatus Http1BridgeFilter::decodeHeaders(Http::HeaderMap& head setupStatTracking(headers); } - const Optional& protocol = decoder_callbacks_->requestInfo().protocol(); - ASSERT(protocol.valid()); + const absl::optional& protocol = decoder_callbacks_->requestInfo().protocol(); + ASSERT(protocol); if (protocol.value() != Http::Protocol::Http2 && grpc_request) { do_bridging_ = true; } diff --git a/source/common/grpc/json_transcoder_filter.cc b/source/common/grpc/json_transcoder_filter.cc index 337e3b35c6f2..ffd9d9fa6f13 100644 --- a/source/common/grpc/json_transcoder_filter.cc +++ b/source/common/grpc/json_transcoder_filter.cc @@ -361,8 +361,8 @@ Http::FilterTrailersStatus JsonTranscoderFilter::encodeTrailers(Http::HeaderMap& return Http::FilterTrailersStatus::Continue; } - const Optional grpc_status = Common::getGrpcStatus(trailers); - if (!grpc_status.valid() || grpc_status.value() == Status::GrpcStatus::InvalidCode) { + const absl::optional grpc_status = Common::getGrpcStatus(trailers); + if (!grpc_status || grpc_status.value() == Status::GrpcStatus::InvalidCode) { response_headers_->Status()->value(enumToInt(Http::Code::ServiceUnavailable)); } else { response_headers_->Status()->value(Common::grpcToHttpStatus(grpc_status.value())); diff --git a/source/common/http/async_client_impl.cc b/source/common/http/async_client_impl.cc index 95d0ba32bf04..09425ac818a1 100644 --- a/source/common/http/async_client_impl.cc +++ b/source/common/http/async_client_impl.cc @@ -12,7 +12,7 @@ namespace Envoy { namespace Http { const std::list AsyncStreamImpl::NullCorsPolicy::allow_origin_; -const Optional AsyncStreamImpl::NullCorsPolicy::allow_credentials_; +const absl::optional AsyncStreamImpl::NullCorsPolicy::allow_credentials_; const std::vector> AsyncStreamImpl::NullRateLimitPolicy::rate_limit_policy_entry_; const AsyncStreamImpl::NullRateLimitPolicy AsyncStreamImpl::RouteEntryImpl::rate_limit_policy_; @@ -43,8 +43,9 @@ AsyncClientImpl::~AsyncClientImpl() { } } -AsyncClient::Request* AsyncClientImpl::send(MessagePtr&& request, AsyncClient::Callbacks& callbacks, - const Optional& timeout) { +AsyncClient::Request* +AsyncClientImpl::send(MessagePtr&& request, AsyncClient::Callbacks& callbacks, + const absl::optional& timeout) { AsyncRequestImpl* async_request = new AsyncRequestImpl(std::move(request), *this, callbacks, timeout); async_request->initialize(); @@ -60,9 +61,10 @@ AsyncClient::Request* AsyncClientImpl::send(MessagePtr&& request, AsyncClient::C } } -AsyncClient::Stream* AsyncClientImpl::start(AsyncClient::StreamCallbacks& callbacks, - const Optional& timeout, - bool buffer_body_for_retry) { +AsyncClient::Stream* +AsyncClientImpl::start(AsyncClient::StreamCallbacks& callbacks, + const absl::optional& timeout, + bool buffer_body_for_retry) { std::unique_ptr new_stream{ new AsyncStreamImpl(*this, callbacks, timeout, buffer_body_for_retry)}; new_stream->moveIntoList(std::move(new_stream), active_streams_); @@ -70,7 +72,7 @@ AsyncClient::Stream* AsyncClientImpl::start(AsyncClient::StreamCallbacks& callba } AsyncStreamImpl::AsyncStreamImpl(AsyncClientImpl& parent, AsyncClient::StreamCallbacks& callbacks, - const Optional& timeout, + const absl::optional& timeout, bool buffer_body_for_retry) : parent_(parent), stream_callbacks_(callbacks), stream_id_(parent.config_.random_.random()), router_(parent.config_), request_info_(Protocol::Http11), @@ -184,7 +186,7 @@ void AsyncStreamImpl::resetStream() { AsyncRequestImpl::AsyncRequestImpl(MessagePtr&& request, AsyncClientImpl& parent, AsyncClient::Callbacks& callbacks, - const Optional& timeout) + const absl::optional& timeout) // We tell the underlying stream to not buffer because we already have the full request and // and can handle any buffered body requests. : AsyncStreamImpl(parent, *this, timeout, false), request_(std::move(request)), diff --git a/source/common/http/async_client_impl.h b/source/common/http/async_client_impl.h index 0791641ff6d7..66a976d39bed 100644 --- a/source/common/http/async_client_impl.h +++ b/source/common/http/async_client_impl.h @@ -43,9 +43,10 @@ class AsyncClientImpl final : public AsyncClient { // Http::AsyncClient Request* send(MessagePtr&& request, Callbacks& callbacks, - const Optional& timeout) override; + const absl::optional& timeout) override; - Stream* start(StreamCallbacks& callbacks, const Optional& timeout, + Stream* start(StreamCallbacks& callbacks, + const absl::optional& timeout, bool buffer_body_for_retry) override; Event::Dispatcher& dispatcher() override { return dispatcher_; } @@ -71,7 +72,8 @@ class AsyncStreamImpl : public AsyncClient::Stream, LinkedObject { public: AsyncStreamImpl(AsyncClientImpl& parent, AsyncClient::StreamCallbacks& callbacks, - const Optional& timeout, bool buffer_body_for_retry); + const absl::optional& timeout, + bool buffer_body_for_retry); // Http::AsyncClient::Stream void sendHeaders(HeaderMap& headers, bool end_stream) override; @@ -92,11 +94,11 @@ class AsyncStreamImpl : public AsyncClient::Stream, const std::string& allowHeaders() const override { return EMPTY_STRING; }; const std::string& exposeHeaders() const override { return EMPTY_STRING; }; const std::string& maxAge() const override { return EMPTY_STRING; }; - const Optional& allowCredentials() const override { return allow_credentials_; }; + const absl::optional& allowCredentials() const override { return allow_credentials_; }; bool enabled() const override { return false; }; static const std::list allow_origin_; - static const Optional allow_credentials_; + static const absl::optional allow_credentials_; }; struct NullRateLimitPolicy : public Router::RateLimitPolicy { @@ -158,7 +160,7 @@ class AsyncStreamImpl : public AsyncClient::Stream, struct RouteEntryImpl : public Router::RouteEntry { RouteEntryImpl(const std::string& cluster_name, - const Optional& timeout) + const absl::optional& timeout) : cluster_name_(cluster_name), timeout_(timeout) {} // Router::RouteEntry @@ -179,7 +181,7 @@ class AsyncStreamImpl : public AsyncClient::Stream, const Router::RetryPolicy& retryPolicy() const override { return retry_policy_; } const Router::ShadowPolicy& shadowPolicy() const override { return shadow_policy_; } std::chrono::milliseconds timeout() const override { - if (timeout_.valid()) { + if (timeout_) { return timeout_.value(); } else { return std::chrono::milliseconds(0); @@ -209,11 +211,12 @@ class AsyncStreamImpl : public AsyncClient::Stream, static const NullPathMatchCriterion path_match_criterion_; const std::string& cluster_name_; - Optional timeout_; + absl::optional timeout_; }; struct RouteImpl : public Router::Route { - RouteImpl(const std::string& cluster_name, const Optional& timeout) + RouteImpl(const std::string& cluster_name, + const absl::optional& timeout) : route_entry_(cluster_name, timeout) {} // Router::Route @@ -273,7 +276,7 @@ class AsyncRequestImpl final : public AsyncClient::Request, AsyncClient::StreamCallbacks { public: AsyncRequestImpl(MessagePtr&& request, AsyncClientImpl& parent, AsyncClient::Callbacks& callbacks, - const Optional& timeout); + const absl::optional& timeout); // AsyncClient::Request virtual void cancel() override; diff --git a/source/common/http/conn_manager_impl.cc b/source/common/http/conn_manager_impl.cc index 769058d205e6..c740b5f41b54 100644 --- a/source/common/http/conn_manager_impl.cc +++ b/source/common/http/conn_manager_impl.cc @@ -81,7 +81,7 @@ void ConnectionManagerImpl::initializeReadFilterCallbacks(Network::ReadFilterCal read_callbacks_->connection().addConnectionCallbacks(*this); - if (config_.idleTimeout().valid()) { + if (config_.idleTimeout()) { idle_timer_ = read_callbacks_->connection().dispatcher().createTimer( [this]() -> void { onIdleTimeout(); }); idle_timer_->enableTimer(config_.idleTimeout().value()); @@ -405,7 +405,7 @@ void ConnectionManagerImpl::ActiveStream::addAccessLogHandler( void ConnectionManagerImpl::ActiveStream::chargeStats(const HeaderMap& headers) { uint64_t response_code = Utility::getResponseStatus(headers); - request_info_.response_code_.value(response_code); + request_info_.response_code_ = response_code; if (request_info_.hc_request_) { return; @@ -530,7 +530,7 @@ void ConnectionManagerImpl::ActiveStream::decodeHeaders(HeaderMapPtr&& headers, connection_manager_.runtime_, connection_manager_.local_info_); ASSERT(request_info_.downstream_remote_address_ != nullptr); - ASSERT(!cached_route_.valid()); + ASSERT(!cached_route_); refreshCachedRoute(); // Check for WebSocket upgrade request if the route exists, and supports WebSockets. @@ -792,7 +792,7 @@ void ConnectionManagerImpl::startDrainSequence() { void ConnectionManagerImpl::ActiveStream::refreshCachedRoute() { Router::RouteConstSharedPtr route = snapped_route_config_->route(*request_headers_, stream_id_); request_info_.route_entry_ = route ? route->routeEntry() : nullptr; - cached_route_.value(std::move(route)); + cached_route_ = std::move(route); } void ConnectionManagerImpl::ActiveStream::encode100ContinueHeaders( @@ -1251,7 +1251,7 @@ Tracing::Span& ConnectionManagerImpl::ActiveStreamFilterBase::activeSpan() { Tracing::Config& ConnectionManagerImpl::ActiveStreamFilterBase::tracingConfig() { return parent_; } Router::RouteConstSharedPtr ConnectionManagerImpl::ActiveStreamFilterBase::route() { - if (!parent_.cached_route_.valid()) { + if (!parent_.cached_route_) { parent_.refreshCachedRoute(); } @@ -1259,7 +1259,7 @@ Router::RouteConstSharedPtr ConnectionManagerImpl::ActiveStreamFilterBase::route } void ConnectionManagerImpl::ActiveStreamFilterBase::clearRouteCache() { - parent_.cached_route_ = Optional(); + parent_.cached_route_ = absl::optional(); } Buffer::WatermarkBufferPtr ConnectionManagerImpl::ActiveStreamDecoderFilter::createBuffer() { diff --git a/source/common/http/conn_manager_impl.h b/source/common/http/conn_manager_impl.h index b81336f32751..2c4683b1915e 100644 --- a/source/common/http/conn_manager_impl.h +++ b/source/common/http/conn_manager_impl.h @@ -215,7 +215,7 @@ class ConnectionManagerConfig { /** * @return optional idle timeout for incoming connection manager connections. */ - virtual const Optional& idleTimeout() PURE; + virtual const absl::optional& idleTimeout() PURE; /** * @return Router::RouteConfigProvider& the configuration provider used to acquire a route @@ -272,7 +272,7 @@ class ConnectionManagerConfig { * be enabled. User agent will only overwritten if it doesn't already exist. If enabled, * the same user agent will be written to the x-envoy-downstream-service-cluster header. */ - virtual const Optional& userAgent() PURE; + virtual const absl::optional& userAgent() PURE; /** * @return tracing config. @@ -621,7 +621,7 @@ class ConnectionManagerImpl : Logger::Loggable, Stats::TimespanPtr request_timer_; State state_; RequestInfo::RequestInfoImpl request_info_; - Optional cached_route_; + absl::optional cached_route_; DownstreamWatermarkCallbacks* watermark_callbacks_{nullptr}; uint32_t buffer_limit_{0}; uint32_t high_watermark_count_{0}; diff --git a/source/common/http/conn_manager_utility.cc b/source/common/http/conn_manager_utility.cc index 988407282a77..b84e56149587 100644 --- a/source/common/http/conn_manager_utility.cc +++ b/source/common/http/conn_manager_utility.cc @@ -139,7 +139,7 @@ Network::Address::InstanceConstSharedPtr ConnectionManagerUtility::mutateRequest } } - if (config.userAgent().valid()) { + if (config.userAgent()) { request_headers.insertEnvoyDownstreamServiceCluster().value(config.userAgent().value()); HeaderEntry& user_agent_header = request_headers.insertUserAgent(); if (user_agent_header.value().empty()) { diff --git a/source/common/http/filter/cors_filter.cc b/source/common/http/filter/cors_filter.cc index 41a869b45351..eada243ee733 100644 --- a/source/common/http/filter/cors_filter.cc +++ b/source/common/http/filter/cors_filter.cc @@ -159,7 +159,7 @@ const std::string& CorsFilter::maxAge() { bool CorsFilter::allowCredentials() { for (const auto policy : policies_) { - if (policy && policy->allowCredentials().valid()) { + if (policy && policy->allowCredentials()) { return policy->allowCredentials().value(); } } diff --git a/source/common/http/filter/fault_filter.cc b/source/common/http/filter/fault_filter.cc index 0fc6867a3d17..350d38a80e9b 100644 --- a/source/common/http/filter/fault_filter.cc +++ b/source/common/http/filter/fault_filter.cc @@ -95,8 +95,8 @@ FilterHeadersStatus FaultFilter::decodeHeaders(HeaderMap& headers, bool) { fmt::format("fault.http.{}.abort.http_status", downstream_cluster_); } - Optional duration_ms = delayDuration(); - if (duration_ms.valid()) { + absl::optional duration_ms = delayDuration(); + if (duration_ms) { delay_timer_ = callbacks_->dispatcher().createTimer([this]() -> void { postDelayInjection(); }); delay_timer_->enableTimer(std::chrono::milliseconds(duration_ms.value())); recordDelaysInjectedStats(); @@ -136,8 +136,8 @@ bool FaultFilter::isAbortEnabled() { return enabled; } -Optional FaultFilter::delayDuration() { - Optional ret; +absl::optional FaultFilter::delayDuration() { + absl::optional ret; if (!isDelayEnabled()) { return ret; @@ -152,7 +152,7 @@ Optional FaultFilter::delayDuration() { // Delay only if the duration is >0ms if (duration > 0) { - ret.value(duration); + ret = duration; } return ret; diff --git a/source/common/http/filter/fault_filter.h b/source/common/http/filter/fault_filter.h index f5e4643bae1c..b30a91f49195 100644 --- a/source/common/http/filter/fault_filter.h +++ b/source/common/http/filter/fault_filter.h @@ -102,7 +102,7 @@ class FaultFilter : public StreamDecoderFilter { bool isAbortEnabled(); bool isDelayEnabled(); - Optional delayDuration(); + absl::optional delayDuration(); uint64_t abortHttpStatus(); FaultFilterConfigSharedPtr config_; diff --git a/source/common/http/filter/lua/lua_filter.cc b/source/common/http/filter/lua/lua_filter.cc index f7b2774069cd..970e015c015e 100644 --- a/source/common/http/filter/lua/lua_filter.cc +++ b/source/common/http/filter/lua/lua_filter.cc @@ -183,9 +183,9 @@ int StreamHandleWrapper::luaHttpCall(lua_State* state) { message->headers().insertContentLength().value(body_size); } - Optional timeout; + absl::optional timeout; if (timeout_ms > 0) { - timeout.value(std::chrono::milliseconds(timeout_ms)); + timeout = std::chrono::milliseconds(timeout_ms); } http_request_ = filter_.clusterManager().httpAsyncClientForCluster(cluster).send( diff --git a/source/common/http/filter/squash_filter.h b/source/common/http/filter/squash_filter.h index 45dfcdbfbcf5..c6b6f10efb8e 100644 --- a/source/common/http/filter/squash_filter.h +++ b/source/common/http/filter/squash_filter.h @@ -4,7 +4,6 @@ #include #include -#include "envoy/common/optional.h" #include "envoy/config/filter/http/squash/v2/squash.pb.h" #include "envoy/http/async_client.h" #include "envoy/http/filter.h" @@ -13,6 +12,8 @@ #include "common/common/logger.h" #include "common/protobuf/protobuf.h" +#include "absl/types/optional.h" + namespace Envoy { namespace Http { diff --git a/source/common/http/http1/BUILD b/source/common/http/http1/BUILD index a5d80a5b9567..3ee1fb2d00a0 100644 --- a/source/common/http/http1/BUILD +++ b/source/common/http/http1/BUILD @@ -36,8 +36,8 @@ envoy_cc_library( name = "conn_pool_lib", srcs = ["conn_pool.cc"], hdrs = ["conn_pool.h"], + external_deps = ["abseil_optional"], deps = [ - "//include/envoy/common:optional", "//include/envoy/event:deferred_deletable", "//include/envoy/event:dispatcher_interface", "//include/envoy/event:timer_interface", diff --git a/source/common/http/http1/conn_pool.h b/source/common/http/http1/conn_pool.h index 3427340e2be2..223367402ec0 100644 --- a/source/common/http/http1/conn_pool.h +++ b/source/common/http/http1/conn_pool.h @@ -4,7 +4,6 @@ #include #include -#include "envoy/common/optional.h" #include "envoy/event/deferred_deletable.h" #include "envoy/event/timer.h" #include "envoy/http/conn_pool.h" @@ -16,6 +15,8 @@ #include "common/http/codec_client.h" #include "common/http/codec_wrappers.h" +#include "absl/types/optional.h" + namespace Envoy { namespace Http { namespace Http1 { diff --git a/source/common/http/http2/BUILD b/source/common/http/http2/BUILD index 32a45a555778..bc0ebe376d28 100644 --- a/source/common/http/http2/BUILD +++ b/source/common/http/http2/BUILD @@ -12,9 +12,11 @@ envoy_cc_library( name = "codec_lib", srcs = ["codec_impl.cc"], hdrs = ["codec_impl.h"], - external_deps = ["nghttp2"], + external_deps = [ + "nghttp2", + "abseil_optional", + ], deps = [ - "//include/envoy/common:optional", "//include/envoy/event:deferred_deletable", "//include/envoy/event:dispatcher_interface", "//include/envoy/http:codec_interface", diff --git a/source/common/http/http2/codec_impl.cc b/source/common/http/http2/codec_impl.cc index ff471395059b..7b7dc37ee116 100644 --- a/source/common/http/http2/codec_impl.cc +++ b/source/common/http/http2/codec_impl.cc @@ -268,7 +268,7 @@ void ConnectionImpl::StreamImpl::resetStream(StreamResetReason reason) { // end the local stream. if (local_end_stream_ && !local_end_stream_sent_) { parent_.pending_deferred_reset_ = true; - deferred_reset_.value(reason); + deferred_reset_ = reason; ENVOY_CONN_LOG(trace, "deferred reset stream", parent_.connection_); } else { resetStreamWorker(reason); @@ -399,7 +399,7 @@ int ConnectionImpl::onFrameReceived(const nghttp2_frame* frame) { case NGHTTP2_HCAT_HEADERS: { // It's possible that we are waiting to send a deferred reset, so only raise headers/trailers // if local is not complete. - if (!stream->deferred_reset_.valid()) { + if (!stream->deferred_reset_) { if (!stream->waiting_for_non_informational_headers_) { if (!stream->remote_end_stream_) { // This indicates we have received more headers frames than Envoy @@ -441,7 +441,7 @@ int ConnectionImpl::onFrameReceived(const nghttp2_frame* frame) { // It's possible that we are waiting to send a deferred reset, so only raise data if local // is not complete. - if (!stream->deferred_reset_.valid()) { + if (!stream->deferred_reset_) { stream->decoder_->decodeData(stream->pending_recv_data_, stream->remote_end_stream_); } @@ -583,7 +583,7 @@ void ConnectionImpl::sendPendingFrames() { if (pending_deferred_reset_) { pending_deferred_reset_ = false; for (auto& stream : active_streams_) { - if (stream->deferred_reset_.valid()) { + if (stream->deferred_reset_) { stream->resetStreamWorker(stream->deferred_reset_.value()); } } diff --git a/source/common/http/http2/codec_impl.h b/source/common/http/http2/codec_impl.h index 40865067f7dd..6c534393638e 100644 --- a/source/common/http/http2/codec_impl.h +++ b/source/common/http/http2/codec_impl.h @@ -6,7 +6,6 @@ #include #include -#include "envoy/common/optional.h" #include "envoy/event/deferred_deletable.h" #include "envoy/http/codec.h" #include "envoy/network/connection.h" @@ -20,6 +19,7 @@ #include "common/http/codec_helper.h" #include "common/http/header_map_impl.h" +#include "absl/types/optional.h" #include "nghttp2/nghttp2.h" namespace Envoy { @@ -195,7 +195,7 @@ class ConnectionImpl : public virtual Connection, protected Logger::Loggable void { this->pendingSendBufferLowWatermark(); }, [this]() -> void { this->pendingSendBufferHighWatermark(); }}; HeaderMapPtr pending_trailers_; - Optional deferred_reset_; + absl::optional deferred_reset_; HeaderString cookies_; bool local_end_stream_sent_ : 1; bool remote_end_stream_ : 1; diff --git a/source/common/http/rest_api_fetcher.cc b/source/common/http/rest_api_fetcher.cc index 6b3b976e2d96..f62f96f3a23b 100644 --- a/source/common/http/rest_api_fetcher.cc +++ b/source/common/http/rest_api_fetcher.cc @@ -51,9 +51,10 @@ void RestApiFetcher::refresh() { MessagePtr message(new RequestMessageImpl()); createRequest(*message); message->headers().insertHost().value(remote_cluster_name_); - active_request_ = cm_.httpAsyncClientForCluster(remote_cluster_name_) - .send(std::move(message), *this, - Optional(std::chrono::milliseconds(1000))); + active_request_ = + cm_.httpAsyncClientForCluster(remote_cluster_name_) + .send(std::move(message), *this, + absl::optional(std::chrono::milliseconds(1000))); } void RestApiFetcher::requestComplete() { diff --git a/source/common/mongo/proxy.cc b/source/common/mongo/proxy.cc index 5f26d6843f26..8533b6f66781 100644 --- a/source/common/mongo/proxy.cc +++ b/source/common/mongo/proxy.cc @@ -293,8 +293,8 @@ DecoderPtr ProdProxyFilter::createDecoder(DecoderCallbacks& callbacks) { return DecoderPtr{new DecoderImpl(callbacks)}; } -Optional ProxyFilter::delayDuration() { - Optional result; +absl::optional ProxyFilter::delayDuration() { + absl::optional result; if (!fault_config_) { return result; @@ -310,7 +310,7 @@ Optional ProxyFilter::delayDuration() { // Delay only if the duration is > 0ms. if (duration > 0) { - result.value(duration); + result = duration; } return result; @@ -330,9 +330,9 @@ void ProxyFilter::tryInjectDelay() { return; } - const Optional delay_ms = delayDuration(); + const absl::optional delay_ms = delayDuration(); - if (delay_ms.valid()) { + if (delay_ms) { delay_timer_ = read_callbacks_->connection().dispatcher().createTimer( [this]() -> void { delayInjectionTimerCallback(); }); delay_timer_->enableTimer(std::chrono::milliseconds(delay_ms.value())); diff --git a/source/common/mongo/proxy.h b/source/common/mongo/proxy.h index e2c230887949..f1915e3c7bb7 100644 --- a/source/common/mongo/proxy.h +++ b/source/common/mongo/proxy.h @@ -176,7 +176,7 @@ class ProxyFilter : public Network::Filter, void doDecode(Buffer::Instance& buffer); void logMessage(Message& message, bool full); void onDrainClose(); - Optional delayDuration(); + absl::optional delayDuration(); void delayInjectionTimerCallback(); void tryInjectDelay(); diff --git a/source/common/network/BUILD b/source/common/network/BUILD index e1c39dc90801..defbac786e67 100644 --- a/source/common/network/BUILD +++ b/source/common/network/BUILD @@ -38,12 +38,12 @@ envoy_cc_library( name = "connection_lib", srcs = ["connection_impl.cc"], hdrs = ["connection_impl.h"], + external_deps = ["abseil_optional"], deps = [ ":address_lib", ":filter_manager_lib", ":raw_buffer_socket_lib", ":utility_lib", - "//include/envoy/common:optional", "//include/envoy/event:dispatcher_interface", "//include/envoy/event:timer_interface", "//include/envoy/network:connection_interface", diff --git a/source/common/network/cidr_range.h b/source/common/network/cidr_range.h index 404468140c66..ece8fdf40e52 100644 --- a/source/common/network/cidr_range.h +++ b/source/common/network/cidr_range.h @@ -47,8 +47,8 @@ class CidrRange { const Ip* ip() const; /** - * TODO(jamessynge) Consider making this Optional length, or modifying the create() methods - * below to return Optional (the latter is probably better). + * TODO(jamessynge) Consider making this absl::optional length, or modifying the create() + * methods below to return absl::optional (the latter is probably better). * @return the number of bits of the address that are included in the mask. -1 if uninitialized * or invalid, else in the range 0 to 32 for IPv4, and 0 to 128 for IPv6. */ diff --git a/source/common/network/connection_impl.h b/source/common/network/connection_impl.h index c0db1ac3aee5..688571fb00c1 100644 --- a/source/common/network/connection_impl.h +++ b/source/common/network/connection_impl.h @@ -6,7 +6,6 @@ #include #include -#include "envoy/common/optional.h" #include "envoy/event/dispatcher.h" #include "envoy/network/connection.h" #include "envoy/network/transport_socket.h" @@ -17,6 +16,8 @@ #include "common/network/filter_manager_impl.h" #include "common/ssl/ssl_socket.h" +#include "absl/types/optional.h" + namespace Envoy { namespace Network { diff --git a/source/common/ratelimit/ratelimit_impl.cc b/source/common/ratelimit/ratelimit_impl.cc index a56d71727e48..8ea443d13a57 100644 --- a/source/common/ratelimit/ratelimit_impl.cc +++ b/source/common/ratelimit/ratelimit_impl.cc @@ -12,7 +12,7 @@ namespace Envoy { namespace RateLimit { GrpcClientImpl::GrpcClientImpl(Grpc::AsyncClientPtr&& async_client, - const Optional& timeout) + const absl::optional& timeout) : service_method_(*Protobuf::DescriptorPool::generated_pool()->FindMethodByName( "pb.lyft.ratelimit.RateLimitService.ShouldRateLimit")), async_client_(std::move(async_client)), timeout_(timeout) {} @@ -86,7 +86,7 @@ GrpcFactoryImpl::GrpcFactoryImpl(const envoy::config::ratelimit::v2::RateLimitSe async_client_factory_ = async_client_manager.factoryForGrpcService(grpc_service, scope); } -ClientPtr GrpcFactoryImpl::create(const Optional& timeout) { +ClientPtr GrpcFactoryImpl::create(const absl::optional& timeout) { return std::make_unique(async_client_factory_->create(), timeout); } diff --git a/source/common/ratelimit/ratelimit_impl.h b/source/common/ratelimit/ratelimit_impl.h index 7d000b6d3293..8d6857dade8b 100644 --- a/source/common/ratelimit/ratelimit_impl.h +++ b/source/common/ratelimit/ratelimit_impl.h @@ -36,7 +36,7 @@ typedef ConstSingleton Constants; class GrpcClientImpl : public Client, public RateLimitAsyncCallbacks { public: GrpcClientImpl(Grpc::AsyncClientPtr&& async_client, - const Optional& timeout); + const absl::optional& timeout); ~GrpcClientImpl(); static void createRequest(pb::lyft::ratelimit::RateLimitRequest& request, @@ -58,7 +58,7 @@ class GrpcClientImpl : public Client, public RateLimitAsyncCallbacks { const Protobuf::MethodDescriptor& service_method_; Grpc::AsyncClientPtr async_client_; Grpc::AsyncRequest* request_{}; - Optional timeout_; + absl::optional timeout_; RequestCallbacks* callbacks_{}; }; @@ -68,7 +68,7 @@ class GrpcFactoryImpl : public ClientFactory { Grpc::AsyncClientManager& async_client_manager, Stats::Scope& scope); // RateLimit::ClientFactory - ClientPtr create(const Optional& timeout) override; + ClientPtr create(const absl::optional& timeout) override; private: Grpc::AsyncClientFactoryPtr async_client_factory_; @@ -87,7 +87,7 @@ class NullClientImpl : public Client { class NullFactoryImpl : public ClientFactory { public: // RateLimit::ClientFactory - ClientPtr create(const Optional&) override { + ClientPtr create(const absl::optional&) override { return ClientPtr{new NullClientImpl()}; } }; diff --git a/source/common/redis/conn_pool_impl.h b/source/common/redis/conn_pool_impl.h index 161166c0e813..a914c769c7aa 100644 --- a/source/common/redis/conn_pool_impl.h +++ b/source/common/redis/conn_pool_impl.h @@ -162,11 +162,11 @@ class InstanceImpl : public Instance { LbContextImpl(const std::string& hash_key) : hash_key_(std::hash()(hash_key)) {} // TODO(danielhochman): convert to HashUtil::xxHash64 when we have a migration strategy. // Upstream::LoadBalancerContext - Optional computeHashKey() override { return hash_key_; } + absl::optional computeHashKey() override { return hash_key_; } const Router::MetadataMatchCriteria* metadataMatchCriteria() const override { return nullptr; } const Network::Connection* downstreamConnection() const override { return nullptr; } - const Optional hash_key_; + const absl::optional hash_key_; }; Upstream::ClusterManager& cm_; diff --git a/source/common/request_info/BUILD b/source/common/request_info/BUILD index 49c139783b3f..77d0e7d0774f 100644 --- a/source/common/request_info/BUILD +++ b/source/common/request_info/BUILD @@ -21,8 +21,8 @@ envoy_cc_library( name = "utility_lib", srcs = ["utility.cc"], hdrs = ["utility.h"], + external_deps = ["abseil_optional"], deps = [ - "//include/envoy/common:optional", "//include/envoy/common:time_interface", "//include/envoy/request_info:request_info_interface", ], diff --git a/source/common/request_info/request_info_impl.h b/source/common/request_info/request_info_impl.h index 79a62a06e6d7..736e10d2b383 100644 --- a/source/common/request_info/request_info_impl.h +++ b/source/common/request_info/request_info_impl.h @@ -21,8 +21,8 @@ struct RequestInfoImpl : public RequestInfo { MonotonicTime startTimeMonotonic() const override { return start_time_monotonic_; } - Optional duration(Optional time) const { - if (!time.valid()) { + absl::optional duration(absl::optional time) const { + if (!time) { return {}; } @@ -30,92 +30,92 @@ struct RequestInfoImpl : public RequestInfo { start_time_monotonic_); } - Optional lastDownstreamRxByteReceived() const override { + absl::optional lastDownstreamRxByteReceived() const override { return duration(last_downstream_rx_byte_received); } void onLastDownstreamRxByteReceived() override { - ASSERT(!last_downstream_rx_byte_received.valid()); - last_downstream_rx_byte_received.value(std::chrono::steady_clock::now()); + ASSERT(!last_downstream_rx_byte_received); + last_downstream_rx_byte_received = std::chrono::steady_clock::now(); } - Optional firstUpstreamTxByteSent() const override { + absl::optional firstUpstreamTxByteSent() const override { return duration(first_upstream_tx_byte_sent_); } void onFirstUpstreamTxByteSent() override { - ASSERT(!first_upstream_tx_byte_sent_.valid()); - first_upstream_tx_byte_sent_.value(std::chrono::steady_clock::now()); + ASSERT(!first_upstream_tx_byte_sent_); + first_upstream_tx_byte_sent_ = std::chrono::steady_clock::now(); } - Optional lastUpstreamTxByteSent() const override { + absl::optional lastUpstreamTxByteSent() const override { return duration(last_upstream_tx_byte_sent_); } void onLastUpstreamTxByteSent() override { - ASSERT(!last_upstream_tx_byte_sent_.valid()); - last_upstream_tx_byte_sent_.value(std::chrono::steady_clock::now()); + ASSERT(!last_upstream_tx_byte_sent_); + last_upstream_tx_byte_sent_ = std::chrono::steady_clock::now(); } - Optional firstUpstreamRxByteReceived() const override { + absl::optional firstUpstreamRxByteReceived() const override { return duration(first_upstream_rx_byte_received_); } void onFirstUpstreamRxByteReceived() override { - ASSERT(!first_upstream_rx_byte_received_.valid()); - first_upstream_rx_byte_received_.value(std::chrono::steady_clock::now()); + ASSERT(!first_upstream_rx_byte_received_); + first_upstream_rx_byte_received_ = std::chrono::steady_clock::now(); } - Optional lastUpstreamRxByteReceived() const override { + absl::optional lastUpstreamRxByteReceived() const override { return duration(last_upstream_rx_byte_received_); } void onLastUpstreamRxByteReceived() override { - ASSERT(!last_upstream_rx_byte_received_.valid()); - last_upstream_rx_byte_received_.value(std::chrono::steady_clock::now()); + ASSERT(!last_upstream_rx_byte_received_); + last_upstream_rx_byte_received_ = std::chrono::steady_clock::now(); } - Optional firstDownstreamTxByteSent() const override { + absl::optional firstDownstreamTxByteSent() const override { return duration(first_downstream_tx_byte_sent_); } void onFirstDownstreamTxByteSent() override { - ASSERT(!first_downstream_tx_byte_sent_.valid()); - first_downstream_tx_byte_sent_.value(std::chrono::steady_clock::now()); + ASSERT(!first_downstream_tx_byte_sent_); + first_downstream_tx_byte_sent_ = std::chrono::steady_clock::now(); } - Optional lastDownstreamTxByteSent() const override { + absl::optional lastDownstreamTxByteSent() const override { return duration(last_downstream_tx_byte_sent_); } void onLastDownstreamTxByteSent() override { - ASSERT(!last_downstream_tx_byte_sent_.valid()); - last_downstream_tx_byte_sent_.value(std::chrono::steady_clock::now()); + ASSERT(!last_downstream_tx_byte_sent_); + last_downstream_tx_byte_sent_ = std::chrono::steady_clock::now(); } - Optional requestComplete() const override { + absl::optional requestComplete() const override { return duration(final_time_); } void onRequestComplete() override { - ASSERT(!final_time_.valid()); - final_time_.value(std::chrono::steady_clock::now()); + ASSERT(!final_time_); + final_time_ = std::chrono::steady_clock::now(); } void resetUpstreamTimings() override { - first_upstream_tx_byte_sent_ = Optional{}; - last_upstream_tx_byte_sent_ = Optional{}; - first_upstream_rx_byte_received_ = Optional{}; - last_upstream_rx_byte_received_ = Optional{}; + first_upstream_tx_byte_sent_ = absl::optional{}; + last_upstream_tx_byte_sent_ = absl::optional{}; + first_upstream_rx_byte_received_ = absl::optional{}; + last_upstream_rx_byte_received_ = absl::optional{}; } uint64_t bytesReceived() const override { return bytes_received_; } - Optional protocol() const override { return protocol_; } + absl::optional protocol() const override { return protocol_; } void protocol(Http::Protocol protocol) override { protocol_ = protocol; } - Optional responseCode() const override { return response_code_; } + absl::optional responseCode() const override { return response_code_; } uint64_t bytesSent() const override { return bytes_sent_; } @@ -149,18 +149,18 @@ struct RequestInfoImpl : public RequestInfo { const SystemTime start_time_; const MonotonicTime start_time_monotonic_; - Optional last_downstream_rx_byte_received; - Optional first_upstream_tx_byte_sent_; - Optional last_upstream_tx_byte_sent_; - Optional first_upstream_rx_byte_received_; - Optional last_upstream_rx_byte_received_; - Optional first_downstream_tx_byte_sent_; - Optional last_downstream_tx_byte_sent_; - Optional final_time_; + absl::optional last_downstream_rx_byte_received; + absl::optional first_upstream_tx_byte_sent_; + absl::optional last_upstream_tx_byte_sent_; + absl::optional first_upstream_rx_byte_received_; + absl::optional last_upstream_rx_byte_received_; + absl::optional first_downstream_tx_byte_sent_; + absl::optional last_downstream_tx_byte_sent_; + absl::optional final_time_; - Optional protocol_; + absl::optional protocol_; uint64_t bytes_received_{}; - Optional response_code_; + absl::optional response_code_; uint64_t bytes_sent_{}; uint64_t response_flags_{}; Upstream::HostDescriptionConstSharedPtr upstream_host_{}; diff --git a/source/common/router/BUILD b/source/common/router/BUILD index 796fe656cfc2..e95dd180a334 100644 --- a/source/common/router/BUILD +++ b/source/common/router/BUILD @@ -12,13 +12,13 @@ envoy_cc_library( name = "config_lib", srcs = ["config_impl.cc"], hdrs = ["config_impl.h"], + external_deps = ["abseil_optional"], deps = [ ":config_utility_lib", ":header_formatter_lib", ":header_parser_lib", ":retry_state_lib", ":router_ratelimit_lib", - "//include/envoy/common:optional", "//include/envoy/http:header_map_interface", "//include/envoy/router:router_interface", "//include/envoy/runtime:runtime_interface", @@ -101,8 +101,8 @@ envoy_cc_library( name = "retry_state_lib", srcs = ["retry_state_impl.cc"], hdrs = ["retry_state_impl.h"], + external_deps = ["abseil_optional"], deps = [ - "//include/envoy/common:optional", "//include/envoy/event:timer_interface", "//include/envoy/http:codec_interface", "//include/envoy/http:header_map_interface", @@ -207,8 +207,8 @@ envoy_cc_library( name = "header_formatter_lib", srcs = ["header_formatter.cc"], hdrs = ["header_formatter.h"], + external_deps = ["abseil_optional"], deps = [ - "//include/envoy/common:optional", "//source/common/access_log:access_log_formatter_lib", "//source/common/common:logger_lib", "//source/common/common:utility_lib", diff --git a/source/common/router/config_impl.cc b/source/common/router/config_impl.cc index c924fa28b075..136f48aac22d 100644 --- a/source/common/router/config_impl.cc +++ b/source/common/router/config_impl.cc @@ -55,7 +55,7 @@ CorsPolicyImpl::CorsPolicyImpl(const envoy::api::v2::route::CorsPolicy& config) expose_headers_ = config.expose_headers(); max_age_ = config.max_age(); if (config.has_allow_credentials()) { - allow_credentials_.value(PROTOBUF_GET_WRAPPED_REQUIRED(config, allow_credentials)); + allow_credentials_ = PROTOBUF_GET_WRAPPED_REQUIRED(config, allow_credentials); } enabled_ = PROTOBUF_GET_WRAPPED_OR_DEFAULT(config, enabled, true); } @@ -73,13 +73,13 @@ class HeaderHashMethod : public HashPolicyImpl::HashMethod { public: HeaderHashMethod(const std::string& header_name) : header_name_(header_name) {} - Optional evaluate(const std::string&, const Http::HeaderMap& headers, - const HashPolicy::AddCookieCallback) const override { - Optional hash; + absl::optional evaluate(const std::string&, const Http::HeaderMap& headers, + const HashPolicy::AddCookieCallback) const override { + absl::optional hash; const Http::HeaderEntry* header = headers.get(header_name_); if (header) { - hash.value(HashUtil::xxHash64(header->value().c_str())); + hash = HashUtil::xxHash64(header->value().c_str()); } return hash; } @@ -92,17 +92,17 @@ class CookieHashMethod : public HashPolicyImpl::HashMethod { public: CookieHashMethod(const std::string& key, long ttl) : key_(key), ttl_(ttl) {} - Optional evaluate(const std::string&, const Http::HeaderMap& headers, - const HashPolicy::AddCookieCallback add_cookie) const override { - Optional hash; + absl::optional evaluate(const std::string&, const Http::HeaderMap& headers, + const HashPolicy::AddCookieCallback add_cookie) const override { + absl::optional hash; std::string value = Http::Utility::parseCookieValue(headers, key_); if (value.empty() && ttl_ != std::chrono::seconds(0)) { value = add_cookie(key_, ttl_); - hash.value(HashUtil::xxHash64(value)); + hash = HashUtil::xxHash64(value); } else if (!value.empty()) { - hash.value(HashUtil::xxHash64(value)); + hash = HashUtil::xxHash64(value); } return hash; } @@ -114,11 +114,11 @@ class CookieHashMethod : public HashPolicyImpl::HashMethod { class IpHashMethod : public HashPolicyImpl::HashMethod { public: - Optional evaluate(const std::string& downstream_addr, const Http::HeaderMap&, - const HashPolicy::AddCookieCallback) const override { - Optional hash; + absl::optional evaluate(const std::string& downstream_addr, const Http::HeaderMap&, + const HashPolicy::AddCookieCallback) const override { + absl::optional hash; if (!downstream_addr.empty()) { - hash.value(HashUtil::xxHash64(downstream_addr)); + hash = HashUtil::xxHash64(downstream_addr); } return hash; } @@ -151,17 +151,18 @@ HashPolicyImpl::HashPolicyImpl( } } -Optional HashPolicyImpl::generateHash(const std::string& downstream_addr, - const Http::HeaderMap& headers, - const AddCookieCallback add_cookie) const { - Optional hash; +absl::optional HashPolicyImpl::generateHash(const std::string& downstream_addr, + const Http::HeaderMap& headers, + const AddCookieCallback add_cookie) const { + absl::optional hash; for (const HashMethodPtr& hash_impl : hash_impls_) { - const Optional new_hash = hash_impl->evaluate(downstream_addr, headers, add_cookie); - if (new_hash.valid()) { + const absl::optional new_hash = + hash_impl->evaluate(downstream_addr, headers, add_cookie); + if (new_hash) { // Rotating the old value prevents duplicate hash rules from cancelling each other out // and preserves all of the entropy - const uint64_t old_value = hash.valid() ? ((hash.value() << 1) | (hash.value() >> 63)) : 0; - hash.value(old_value ^ new_hash.value()); + const uint64_t old_value = hash ? ((hash.value() << 1) | (hash.value() >> 63)) : 0; + hash = old_value ^ new_hash.value(); } } return hash; @@ -324,7 +325,7 @@ RouteEntryImplBase::RouteEntryImplBase(const VirtualHostImpl& vhost, bool RouteEntryImplBase::matchRoute(const Http::HeaderMap& headers, uint64_t random_value) const { bool matches = true; - if (runtime_.valid()) { + if (runtime_) { matches &= loader_.snapshot().featureEnabled(runtime_.value().key_, runtime_.value().default_, random_value); } @@ -361,14 +362,14 @@ void RouteEntryImplBase::finalizeResponseHeaders( vhost_.globalRouteConfig().responseHeaderParser().evaluateHeaders(headers, request_info); } -Optional +absl::optional RouteEntryImplBase::loadRuntimeData(const envoy::api::v2::route::RouteMatch& route_match) { - Optional runtime; + absl::optional runtime; if (route_match.has_runtime()) { RuntimeData data; data.key_ = route_match.runtime().runtime_key(); data.default_ = route_match.runtime().default_value(); - runtime.value(data); + runtime = data; } return runtime; @@ -820,7 +821,7 @@ const VirtualCluster* VirtualHostImpl::virtualClusterFromEntries(const Http::HeaderMap& headers) const { for (const VirtualClusterEntry& entry : virtual_clusters_) { bool method_matches = - !entry.method_.valid() || headers.Method()->value().c_str() == entry.method_.value(); + !entry.method_ || headers.Method()->value().c_str() == entry.method_.value(); if (method_matches && std::regex_match(headers.Path()->value().c_str(), entry.pattern_)) { return &entry; diff --git a/source/common/router/config_impl.h b/source/common/router/config_impl.h index be2b7f6a268b..5973f4cfe6f8 100644 --- a/source/common/router/config_impl.h +++ b/source/common/router/config_impl.h @@ -12,7 +12,6 @@ #include "envoy/api/v2/rds.pb.h" #include "envoy/api/v2/route/route.pb.h" -#include "envoy/common/optional.h" #include "envoy/router/router.h" #include "envoy/runtime/runtime.h" #include "envoy/upstream/cluster_manager.h" @@ -22,6 +21,8 @@ #include "common/router/header_parser.h" #include "common/router/router_ratelimit.h" +#include "absl/types/optional.h" + namespace Envoy { namespace Router { @@ -83,7 +84,7 @@ class CorsPolicyImpl : public CorsPolicy { const std::string& allowHeaders() const override { return allow_headers_; }; const std::string& exposeHeaders() const override { return expose_headers_; }; const std::string& maxAge() const override { return max_age_; }; - const Optional& allowCredentials() const override { return allow_credentials_; }; + const absl::optional& allowCredentials() const override { return allow_credentials_; }; bool enabled() const override { return enabled_; }; private: @@ -92,7 +93,7 @@ class CorsPolicyImpl : public CorsPolicy { std::string allow_headers_; std::string expose_headers_; std::string max_age_{}; - Optional allow_credentials_{}; + absl::optional allow_credentials_{}; bool enabled_; }; @@ -129,7 +130,7 @@ class VirtualHostImpl : public VirtualHost { const std::string& name() const override { return name_; } std::regex pattern_; - Optional method_; + absl::optional method_; std::string name_; }; @@ -201,16 +202,16 @@ class HashPolicyImpl : public HashPolicy { hash_policy); // Router::HashPolicy - Optional generateHash(const std::string& downstream_addr, - const Http::HeaderMap& headers, - const AddCookieCallback add_cookie) const override; + absl::optional generateHash(const std::string& downstream_addr, + const Http::HeaderMap& headers, + const AddCookieCallback add_cookie) const override; class HashMethod { public: virtual ~HashMethod() {} - virtual Optional evaluate(const std::string& downstream_addr, - const Http::HeaderMap& headers, - const AddCookieCallback add_cookie) const PURE; + virtual absl::optional evaluate(const std::string& downstream_addr, + const Http::HeaderMap& headers, + const AddCookieCallback add_cookie) const PURE; }; typedef std::unique_ptr HashMethodPtr; @@ -301,7 +302,7 @@ class RouteEntryImplBase : public RouteEntry, RouteEntryImplBase(const VirtualHostImpl& vhost, const envoy::api::v2::route::Route& route, Runtime::Loader& loader); - bool isDirectResponse() const { return direct_response_code_.valid(); } + bool isDirectResponse() const { return direct_response_code_.has_value(); } bool isRedirect() const { if (!isDirectResponse()) { @@ -469,7 +470,8 @@ class RouteEntryImplBase : public RouteEntry, typedef std::shared_ptr WeightedClusterEntrySharedPtr; - static Optional loadRuntimeData(const envoy::api::v2::route::RouteMatch& route); + static absl::optional + loadRuntimeData(const envoy::api::v2::route::RouteMatch& route); static std::multimap parseOpaqueConfig(const envoy::api::v2::route::Route& route); @@ -488,7 +490,7 @@ class RouteEntryImplBase : public RouteEntry, const Http::LowerCaseString cluster_header_name_; const Http::Code cluster_not_found_response_code_; const std::chrono::milliseconds timeout_; - const Optional runtime_; + const absl::optional runtime_; Runtime::Loader& loader_; const std::string host_redirect_; const std::string path_redirect_; @@ -513,7 +515,7 @@ class RouteEntryImplBase : public RouteEntry, const std::multimap opaque_config_; const DecoratorConstPtr decorator_; - const Optional direct_response_code_; + const absl::optional direct_response_code_; std::string direct_response_body_; }; diff --git a/source/common/router/config_utility.cc b/source/common/router/config_utility.cc index 43a97f287254..26bf1627e609 100644 --- a/source/common/router/config_utility.cc +++ b/source/common/router/config_utility.cc @@ -159,14 +159,14 @@ Http::Code ConfigUtility::parseRedirectResponseCode( } } -Optional +absl::optional ConfigUtility::parseDirectResponseCode(const envoy::api::v2::route::Route& route) { if (route.has_redirect()) { return parseRedirectResponseCode(route.redirect().response_code()); } else if (route.has_direct_response()) { return static_cast(route.direct_response().status()); } - return Optional(); + return absl::optional(); } std::string ConfigUtility::parseDirectResponseBody(const envoy::api::v2::route::Route& route) { diff --git a/source/common/router/config_utility.h b/source/common/router/config_utility.h index 6fde1debb86e..b9069007425d 100644 --- a/source/common/router/config_utility.h +++ b/source/common/router/config_utility.h @@ -7,7 +7,6 @@ #include #include "envoy/api/v2/route/route.pb.h" -#include "envoy/common/optional.h" #include "envoy/http/codes.h" #include "envoy/json/json_object.h" #include "envoy/upstream/resource_manager.h" @@ -19,6 +18,8 @@ #include "common/http/utility.h" #include "common/protobuf/utility.h" +#include "absl/types/optional.h" + namespace Envoy { namespace Router { @@ -105,16 +106,17 @@ class ConfigUtility { /** * Returns the HTTP Status Code enum parsed from the route's redirect or direct_response. * @param route supplies the Route configuration. - * @return Optional the HTTP status from the route's direct_response if specified, - * or the HTTP status code from the route's redirect if specified, - * or an empty Option otherwise. + * @return absl::optional the HTTP status from the route's direct_response if + * specified, or the HTTP status code from the route's redirect if specified, or an empty + * absl::optional otherwise. */ - static Optional parseDirectResponseCode(const envoy::api::v2::route::Route& route); + static absl::optional + parseDirectResponseCode(const envoy::api::v2::route::Route& route); /** * Returns the content of the response body to send with direct responses from a route. * @param route supplies the Route configuration. - * @return Optional the response body provided inline in the route's + * @return absl::optional the response body provided inline in the route's * direct_response if specified, or the contents of the file named in the * route's direct_response if specified, or an empty string otherwise. * @throw EnvoyException if the route configuration contains an error. diff --git a/source/common/router/header_formatter.cc b/source/common/router/header_formatter.cc index 776c9fc98e77..8770534d42cd 100644 --- a/source/common/router/header_formatter.cc +++ b/source/common/router/header_formatter.cc @@ -2,8 +2,6 @@ #include -#include "envoy/common/optional.h" - #include "common/access_log/access_log_formatter.h" #include "common/common/fmt.h" #include "common/common/logger.h" @@ -12,6 +10,8 @@ #include "common/json/json_loader.h" #include "common/request_info/utility.h" +#include "absl/types/optional.h" + namespace Envoy { namespace Router { diff --git a/source/common/router/retry_state_impl.cc b/source/common/router/retry_state_impl.cc index 2f7ea9e33848..9f6fea4b9039 100644 --- a/source/common/router/retry_state_impl.cc +++ b/source/common/router/retry_state_impl.cc @@ -130,9 +130,10 @@ void RetryStateImpl::resetRetry() { } RetryStatus RetryStateImpl::shouldRetry(const Http::HeaderMap* response_headers, - const Optional& reset_reason, + const absl::optional& reset_reason, DoRetryCallback callback) { - ASSERT((response_headers != nullptr) ^ reset_reason.valid()); + + ASSERT((response_headers != nullptr) ^ reset_reason.has_value()); if (callback_ && !wouldRetry(response_headers, reset_reason)) { cluster_.stats().upstream_rq_retry_success_.inc(); @@ -167,14 +168,14 @@ RetryStatus RetryStateImpl::shouldRetry(const Http::HeaderMap* response_headers, } bool RetryStateImpl::wouldRetry(const Http::HeaderMap* response_headers, - const Optional& reset_reason) { + const absl::optional& reset_reason) { // We never retry if the overloaded header is set. if (response_headers != nullptr && response_headers->EnvoyOverloaded() != nullptr) { return false; } // we never retry if the reset reason is overflow. - if (reset_reason.valid() && reset_reason.value() == Http::StreamResetReason::Overflow) { + if (reset_reason && reset_reason.value() == Http::StreamResetReason::Overflow) { return false; } @@ -195,12 +196,12 @@ bool RetryStateImpl::wouldRetry(const Http::HeaderMap* response_headers, } } - if ((retry_on_ & RetryPolicy::RETRY_ON_REFUSED_STREAM) && reset_reason.valid() && + if ((retry_on_ & RetryPolicy::RETRY_ON_REFUSED_STREAM) && reset_reason && reset_reason.value() == Http::StreamResetReason::RemoteRefusedStreamReset) { return true; } - if ((retry_on_ & RetryPolicy::RETRY_ON_CONNECT_FAILURE) && reset_reason.valid() && + if ((retry_on_ & RetryPolicy::RETRY_ON_CONNECT_FAILURE) && reset_reason && reset_reason.value() == Http::StreamResetReason::ConnectionFailure) { return true; } @@ -216,8 +217,9 @@ bool RetryStateImpl::wouldRetry(const Http::HeaderMap* response_headers, (RetryPolicy::RETRY_ON_GRPC_CANCELLED | RetryPolicy::RETRY_ON_GRPC_DEADLINE_EXCEEDED | RetryPolicy::RETRY_ON_GRPC_RESOURCE_EXHAUSTED) && response_headers) { - Optional status = Grpc::Common::getGrpcStatus(*response_headers); - if (status.valid()) { + absl::optional status = + Grpc::Common::getGrpcStatus(*response_headers); + if (status) { if ((status.value() == Grpc::Status::Canceled && (retry_on_ & RetryPolicy::RETRY_ON_GRPC_CANCELLED)) || (status.value() == Grpc::Status::DeadlineExceeded && diff --git a/source/common/router/retry_state_impl.h b/source/common/router/retry_state_impl.h index f92235ad9925..8f01320b83a3 100644 --- a/source/common/router/retry_state_impl.h +++ b/source/common/router/retry_state_impl.h @@ -3,7 +3,6 @@ #include #include -#include "envoy/common/optional.h" #include "envoy/event/timer.h" #include "envoy/http/codec.h" #include "envoy/http/header_map.h" @@ -12,6 +11,7 @@ #include "envoy/upstream/upstream.h" #include "absl/strings/string_view.h" +#include "absl/types/optional.h" namespace Envoy { namespace Router { @@ -35,7 +35,7 @@ class RetryStateImpl : public RetryState { // Router::RetryState bool enabled() override { return retry_on_ != 0; } RetryStatus shouldRetry(const Http::HeaderMap* response_headers, - const Optional& reset_reason, + const absl::optional& reset_reason, DoRetryCallback callback) override; private: @@ -47,7 +47,7 @@ class RetryStateImpl : public RetryState { void enableBackoffTimer(); void resetRetry(); bool wouldRetry(const Http::HeaderMap* response_headers, - const Optional& reset_reason); + const absl::optional& reset_reason); const Upstream::ClusterInfo& cluster_; Runtime::Loader& runtime_; diff --git a/source/common/router/router.cc b/source/common/router/router.cc index de91e4f46f9e..3357124c0221 100644 --- a/source/common/router/router.cc +++ b/source/common/router/router.cc @@ -454,11 +454,11 @@ void Filter::onResponseTimeout() { upstream_request_->resetStream(); } - onUpstreamReset(UpstreamResetType::GlobalTimeout, Optional()); + onUpstreamReset(UpstreamResetType::GlobalTimeout, absl::optional()); } void Filter::onUpstreamReset(UpstreamResetType type, - const Optional& reset_reason) { + const absl::optional& reset_reason) { ASSERT(type == UpstreamResetType::GlobalTimeout || upstream_request_); if (type == UpstreamResetType::Reset) { ENVOY_STREAM_LOG(debug, "upstream reset", *callbacks_); @@ -515,8 +515,7 @@ void Filter::onUpstreamReset(UpstreamResetType type, body = "upstream connect error or disconnect/reset before headers"; } - const bool dropped = - reset_reason.valid() && reset_reason.value() == Http::StreamResetReason::Overflow; + const bool dropped = reset_reason && reset_reason.value() == Http::StreamResetReason::Overflow; chargeUpstreamCode(code, upstream_host, dropped); // If we had non-5xx but still have been reset by backend or timeout before // starting response, we treat this as an error. We only get non-5xx when @@ -558,8 +557,8 @@ void Filter::handleNon5xxResponseHeaders(const Http::HeaderMap& headers, bool en // the trailers. if (grpc_request_) { if (end_stream) { - Optional grpc_status = Grpc::Common::getGrpcStatus(headers); - if (grpc_status.valid() && + absl::optional grpc_status = Grpc::Common::getGrpcStatus(headers); + if (grpc_status && !Http::CodeUtility::is5xx(Grpc::Common::grpcToHttpStatus(grpc_status.value()))) { upstream_request_->upstream_host_->stats().rq_success_.inc(); } else { @@ -598,7 +597,7 @@ void Filter::onUpstreamHeaders(const uint64_t response_code, Http::HeaderMapPtr& if (retry_state_) { RetryStatus retry_status = retry_state_->shouldRetry( - headers.get(), Optional(), [this]() -> void { doRetry(); }); + headers.get(), absl::optional(), [this]() -> void { doRetry(); }); // Capture upstream_host since setupRetry() in the following line will clear // upstream_request_. const auto upstream_host = upstream_request_->upstream_host_; @@ -665,8 +664,8 @@ void Filter::onUpstreamData(Buffer::Instance& data, bool end_stream) { void Filter::onUpstreamTrailers(Http::HeaderMapPtr&& trailers) { if (upstream_request_->grpc_rq_success_deferred_) { - Optional grpc_status = Grpc::Common::getGrpcStatus(*trailers); - if (grpc_status.valid() && + absl::optional grpc_status = Grpc::Common::getGrpcStatus(*trailers); + if (grpc_status && !Http::CodeUtility::is5xx(Grpc::Common::grpcToHttpStatus(grpc_status.value()))) { upstream_request_->upstream_host_->stats().rq_success_.inc(); } else { @@ -820,7 +819,7 @@ void Filter::UpstreamRequest::decodeHeaders(Http::HeaderMapPtr&& headers, bool e upstream_headers_ = headers.get(); const uint64_t response_code = Http::Utility::getResponseStatus(*headers); - request_info_.response_code_.value(static_cast(response_code)); + request_info_.response_code_ = static_cast(response_code); parent_.onUpstreamHeaders(response_code, std::move(headers), end_stream); } @@ -896,7 +895,8 @@ void Filter::UpstreamRequest::onResetStream(Http::StreamResetReason reason) { clearRequestEncoder(); if (!calling_encode_headers_) { request_info_.setResponseFlag(parent_.streamResetReasonToResponseFlag(reason)); - parent_.onUpstreamReset(UpstreamResetType::Reset, Optional(reason)); + parent_.onUpstreamReset(UpstreamResetType::Reset, + absl::optional(reason)); } else { deferred_reset_reason_ = reason; } @@ -934,8 +934,9 @@ void Filter::UpstreamRequest::onPerTryTimeout() { } resetStream(); request_info_.setResponseFlag(RequestInfo::ResponseFlag::UpstreamRequestTimeout); - parent_.onUpstreamReset(UpstreamResetType::PerTryTimeout, - Optional(Http::StreamResetReason::LocalReset)); + parent_.onUpstreamReset( + UpstreamResetType::PerTryTimeout, + absl::optional(Http::StreamResetReason::LocalReset)); } void Filter::UpstreamRequest::onPoolFailure(Http::ConnectionPool::PoolFailureReason reason, @@ -984,7 +985,7 @@ void Filter::UpstreamRequest::onPoolReady(Http::StreamEncoder& request_encoder, // but it's unclear if we have covered all cases so protect against it and test for it. One // specific example of a case where this happens is if we try to encode a total header size that // is too big in HTTP/2 (64K currently). - if (deferred_reset_reason_.valid()) { + if (deferred_reset_reason_) { onResetStream(deferred_reset_reason_.value()); } else { if (buffered_request_body_) { diff --git a/source/common/router/router.h b/source/common/router/router.h index ea8e91f66e64..930ccc4eb519 100644 --- a/source/common/router/router.h +++ b/source/common/router/router.h @@ -148,7 +148,7 @@ class Filter : Logger::Loggable, void setDecoderFilterCallbacks(Http::StreamDecoderFilterCallbacks& callbacks) override; // Upstream::LoadBalancerContext - Optional computeHashKey() override { + absl::optional computeHashKey() override { if (route_entry_ && downstream_headers_) { auto hash_policy = route_entry_->hashPolicy(); if (hash_policy) { @@ -265,7 +265,7 @@ class Filter : Logger::Loggable, Event::TimerPtr per_try_timeout_; Http::ConnectionPool::Cancellable* conn_pool_stream_handle_{}; Http::StreamEncoder* request_encoder_{}; - Optional deferred_reset_reason_; + absl::optional deferred_reset_reason_; Buffer::WatermarkBufferPtr buffered_request_body_; Upstream::HostDescriptionConstSharedPtr upstream_host_; DownstreamWatermarkManager downstream_watermark_manager_{*this}; @@ -307,7 +307,7 @@ class Filter : Logger::Loggable, void onUpstreamTrailers(Http::HeaderMapPtr&& trailers); void onUpstreamComplete(); void onUpstreamReset(UpstreamResetType type, - const Optional& reset_reason); + const absl::optional& reset_reason); void sendNoHealthyUpstreamResponse(); bool setupRetry(bool end_stream); void doRetry(); diff --git a/source/common/router/shadow_writer_impl.cc b/source/common/router/shadow_writer_impl.cc index 7608aca36fef..b54266ea6aba 100644 --- a/source/common/router/shadow_writer_impl.cc +++ b/source/common/router/shadow_writer_impl.cc @@ -23,7 +23,7 @@ void ShadowWriterImpl::shadow(const std::string& cluster, Http::MessagePtr&& req // Configuration should guarantee that cluster exists before calling here. This is basically // fire and forget. We don't handle cancelling. cm_.httpAsyncClientForCluster(cluster).send(std::move(request), *this, - Optional(timeout)); + absl::optional(timeout)); } } // namespace Router diff --git a/source/common/runtime/runtime_impl.cc b/source/common/runtime/runtime_impl.cc index 21f8cb5d6ba7..8d673d6a1b09 100644 --- a/source/common/runtime/runtime_impl.cc +++ b/source/common/runtime/runtime_impl.cc @@ -181,7 +181,7 @@ const std::string& SnapshotImpl::get(const std::string& key) const { uint64_t SnapshotImpl::getInteger(const std::string& key, uint64_t default_value) const { auto entry = values_.find(key); - if (entry == values_.end() || !entry->second.uint_value_.valid()) { + if (entry == values_.end() || !entry->second.uint_value_) { return default_value; } else { return entry->second.uint_value_.value(); @@ -250,7 +250,7 @@ void SnapshotImpl::walkDirectory(const std::string& path, const std::string& pre // succeed that's fine. uint64_t converted; if (StringUtil::atoul(entry.string_value_.c_str(), converted)) { - entry.uint_value_.value(converted); + entry.uint_value_ = converted; } // Separate erase/insert calls required due to the value type being constant; this prevents diff --git a/source/common/tracing/http_tracer_impl.cc b/source/common/tracing/http_tracer_impl.cc index d0615391d9db..33f8de70b7d5 100644 --- a/source/common/tracing/http_tracer_impl.cc +++ b/source/common/tracing/http_tracer_impl.cc @@ -19,7 +19,7 @@ namespace Tracing { // TODO(mattklein123) PERF: Avoid string creations/copies in this entire file. static std::string buildResponseCode(const RequestInfo::RequestInfo& info) { - return info.responseCode().valid() ? std::to_string(info.responseCode().value()) : "0"; + return info.responseCode() ? std::to_string(info.responseCode().value()) : "0"; } static std::string valueOrDefault(const Http::HeaderEntry* header, const char* default_value) { @@ -156,7 +156,7 @@ void HttpTracerUtility::finalizeSpan(Span& span, const Http::HeaderMap* request_ span.setTag(Tracing::Tags::get().RESPONSE_FLAGS, RequestInfo::ResponseFlagUtils::toShortString(request_info)); - if (!request_info.responseCode().valid() || + if (!request_info.responseCode() || Http::CodeUtility::is5xx(request_info.responseCode().value())) { span.setTag(Tracing::Tags::get().ERROR, Tracing::Tags::get().TRUE); } diff --git a/source/common/tracing/zipkin/BUILD b/source/common/tracing/zipkin/BUILD index 52c1ea52d1dc..022f303f1ac3 100644 --- a/source/common/tracing/zipkin/BUILD +++ b/source/common/tracing/zipkin/BUILD @@ -29,9 +29,11 @@ envoy_cc_library( "zipkin_json_field_names.h", "zipkin_tracer_impl.h", ], - external_deps = ["rapidjson"], + external_deps = [ + "rapidjson", + "abseil_optional", + ], deps = [ - "//include/envoy/common:optional", "//include/envoy/common:time_interface", "//include/envoy/local_info:local_info_interface", "//include/envoy/network:address_interface", diff --git a/source/common/tracing/zipkin/zipkin_core_types.cc b/source/common/tracing/zipkin/zipkin_core_types.cc index fae733aad431..dea796209914 100644 --- a/source/common/tracing/zipkin/zipkin_core_types.cc +++ b/source/common/tracing/zipkin/zipkin_core_types.cc @@ -73,7 +73,7 @@ Annotation& Annotation::operator=(const Annotation& ann) { } void Annotation::changeEndpointServiceName(const std::string& service_name) { - if (endpoint_.valid()) { + if (endpoint_) { endpoint_.value().setServiceName(service_name); } } @@ -90,7 +90,7 @@ const std::string Annotation::toJson() { std::string json_string = s.GetString(); - if (endpoint_.valid()) { + if (endpoint_) { Util::mergeJsons(json_string, static_cast(endpoint_.value()).toJson(), ZipkinJsonFieldNames::get().ANNOTATION_ENDPOINT.c_str()); } @@ -130,7 +130,7 @@ const std::string BinaryAnnotation::toJson() { std::string json_string = s.GetString(); - if (endpoint_.valid()) { + if (endpoint_) { Util::mergeJsons(json_string, static_cast(endpoint_.value()).toJson(), ZipkinJsonFieldNames::get().BINARY_ANNOTATION_ENDPOINT.c_str()); } @@ -180,17 +180,17 @@ const std::string Span::toJson() { writer.Key(ZipkinJsonFieldNames::get().SPAN_ID.c_str()); writer.String(Hex::uint64ToHex(id_).c_str()); - if (parent_id_.valid() && parent_id_.value()) { + if (parent_id_ && parent_id_.value()) { writer.Key(ZipkinJsonFieldNames::get().SPAN_PARENT_ID.c_str()); writer.String(Hex::uint64ToHex(parent_id_.value()).c_str()); } - if (timestamp_.valid()) { + if (timestamp_) { writer.Key(ZipkinJsonFieldNames::get().SPAN_TIMESTAMP.c_str()); writer.Int64(timestamp_.value()); } - if (duration_.valid()) { + if (duration_) { writer.Key(ZipkinJsonFieldNames::get().SPAN_DURATION.c_str()); writer.Int64(duration_.value()); } diff --git a/source/common/tracing/zipkin/zipkin_core_types.h b/source/common/tracing/zipkin/zipkin_core_types.h index b0ba07ace454..b35cddcc0b09 100644 --- a/source/common/tracing/zipkin/zipkin_core_types.h +++ b/source/common/tracing/zipkin/zipkin_core_types.h @@ -2,7 +2,6 @@ #include -#include "envoy/common/optional.h" #include "envoy/common/pure.h" #include "envoy/network/address.h" @@ -10,6 +9,8 @@ #include "common/tracing/zipkin/tracer_interface.h" #include "common/tracing/zipkin/util.h" +#include "absl/types/optional.h" + namespace Envoy { namespace Zipkin { @@ -133,12 +134,12 @@ class Annotation : public ZipkinBase { /** * Sets the annotation's endpoint attribute (copy semantics). */ - void setEndpoint(const Endpoint& endpoint) { endpoint_.value(endpoint); } + void setEndpoint(const Endpoint& endpoint) { endpoint_ = endpoint; } /** * Sets the annotation's endpoint attribute (move semantics). */ - void setEndpoint(const Endpoint&& endpoint) { endpoint_.value(endpoint); } + void setEndpoint(const Endpoint&& endpoint) { endpoint_ = endpoint; } /** * Replaces the endpoint's service-name attribute value with the given value. @@ -171,7 +172,7 @@ class Annotation : public ZipkinBase { /** * @return true if the endpoint attribute is set, or false otherwise. */ - bool isSetEndpoint() const { return endpoint_.valid(); } + bool isSetEndpoint() const { return endpoint_.has_value(); } /** * Serializes the annotation as a Zipkin-compliant JSON representation as a string. @@ -183,7 +184,7 @@ class Annotation : public ZipkinBase { private: uint64_t timestamp_; std::string value_; - Optional endpoint_; + absl::optional endpoint_; }; /** @@ -240,18 +241,17 @@ class BinaryAnnotation : public ZipkinBase { /** * Sets the annotation's endpoint attribute (copy semantics). */ - void setEndpoint(const Endpoint& endpoint) { endpoint_.value(endpoint); } + void setEndpoint(const Endpoint& endpoint) { endpoint_ = endpoint; } /** * Sets the annotation's endpoint attribute (move semantics). */ - void setEndpoint(const Endpoint&& endpoint) { endpoint_.value(endpoint); } + void setEndpoint(const Endpoint&& endpoint) { endpoint_ = endpoint; } /** - * @return true of the endpoint attribute has been set, or false otherwise. + * @return true if the endpoint attribute is set, or false otherwise. */ - bool isSetEndpoint() const { return endpoint_.valid(); } - + bool isSetEndpoint() const { return endpoint_.has_value(); } /** * @return the key attribute. */ @@ -282,7 +282,7 @@ class BinaryAnnotation : public ZipkinBase { private: std::string key_; std::string value_; - Optional endpoint_; + absl::optional endpoint_; AnnotationType annotation_type_; }; @@ -322,12 +322,12 @@ class Span : public ZipkinBase { /** * Sets the span's parent id. */ - void setParentId(const uint64_t val) { parent_id_.value(val); } + void setParentId(const uint64_t val) { parent_id_ = val; } /** * @return Whether or not the parent_id attribute is set. */ - bool isSetParentId() const { return parent_id_.valid(); } + bool isSetParentId() const { return parent_id_.has_value(); } /** * @return a vector with all annotations added to the span. @@ -372,33 +372,33 @@ class Span : public ZipkinBase { /** * Sets the span's timestamp attribute. */ - void setTimestamp(const int64_t val) { timestamp_.value(val); } + void setTimestamp(const int64_t val) { timestamp_ = val; } /** * @return Whether or not the timestamp attribute is set. */ - bool isSetTimestamp() const { return timestamp_.valid(); } + bool isSetTimestamp() const { return timestamp_.has_value(); } /** * Sets the span's duration attribute. */ - void setDuration(const int64_t val) { duration_.value(val); } + void setDuration(const int64_t val) { duration_ = val; } /** * @return Whether or not the duration attribute is set. */ - bool isSetDuration() const { return duration_.valid(); } + bool isSetDuration() const { return duration_.has_value(); } /** * Sets the higher 64 bits of the span's 128-bit trace id. * Note that this is optional, since 64-bit trace ids are valid. */ - void setTraceIdHigh(const uint64_t val) { trace_id_high_.value(val); } + void setTraceIdHigh(const uint64_t val) { trace_id_high_ = val; } /** * @return whether or not the trace_id_high attribute is set. */ - bool isSetTraceIdHigh() const { return trace_id_high_.valid(); } + bool isSetTraceIdHigh() const { return trace_id_high_.has_value(); } /** * Sets the span start-time attribute (monotonic, used to calculate duration). @@ -444,7 +444,7 @@ class Span : public ZipkinBase { * @return the span's parent id as a hexadecimal string. */ const std::string parentIdAsHexString() const { - return parent_id_.valid() ? Hex::uint64ToHex(parent_id_.value()) : EMPTY_HEX_STRING_; + return parent_id_ ? Hex::uint64ToHex(parent_id_.value()) : EMPTY_HEX_STRING_; } /** @@ -533,13 +533,13 @@ class Span : public ZipkinBase { uint64_t trace_id_; std::string name_; uint64_t id_; - Optional parent_id_; + absl::optional parent_id_; bool debug_; std::vector annotations_; std::vector binary_annotations_; - Optional timestamp_; - Optional duration_; - Optional trace_id_high_; + absl::optional timestamp_; + absl::optional duration_; + absl::optional trace_id_high_; int64_t monotonic_start_time_; TracerInterface* tracer_; }; diff --git a/source/common/upstream/cds_api_impl.cc b/source/common/upstream/cds_api_impl.cc index da9844f78912..c8d97279b3b2 100644 --- a/source/common/upstream/cds_api_impl.cc +++ b/source/common/upstream/cds_api_impl.cc @@ -16,7 +16,7 @@ namespace Envoy { namespace Upstream { CdsApiPtr CdsApiImpl::create(const envoy::api::v2::core::ConfigSource& cds_config, - const Optional& eds_config, + const absl::optional& eds_config, ClusterManager& cm, Event::Dispatcher& dispatcher, Runtime::RandomGenerator& random, const LocalInfo::LocalInfo& local_info, Stats::Scope& scope) { @@ -25,7 +25,7 @@ CdsApiPtr CdsApiImpl::create(const envoy::api::v2::core::ConfigSource& cds_confi } CdsApiImpl::CdsApiImpl(const envoy::api::v2::core::ConfigSource& cds_config, - const Optional& eds_config, + const absl::optional& eds_config, ClusterManager& cm, Event::Dispatcher& dispatcher, Runtime::RandomGenerator& random, const LocalInfo::LocalInfo& local_info, Stats::Scope& scope) diff --git a/source/common/upstream/cds_api_impl.h b/source/common/upstream/cds_api_impl.h index 8585c5ed2af3..273cd1270ce7 100644 --- a/source/common/upstream/cds_api_impl.h +++ b/source/common/upstream/cds_api_impl.h @@ -21,7 +21,7 @@ class CdsApiImpl : public CdsApi, Logger::Loggable { public: static CdsApiPtr create(const envoy::api::v2::core::ConfigSource& cds_config, - const Optional& eds_config, + const absl::optional& eds_config, ClusterManager& cm, Event::Dispatcher& dispatcher, Runtime::RandomGenerator& random, const LocalInfo::LocalInfo& local_info, Stats::Scope& scope); @@ -42,8 +42,8 @@ class CdsApiImpl : public CdsApi, private: CdsApiImpl(const envoy::api::v2::core::ConfigSource& cds_config, - const Optional& eds_config, ClusterManager& cm, - Event::Dispatcher& dispatcher, Runtime::RandomGenerator& random, + const absl::optional& eds_config, + ClusterManager& cm, Event::Dispatcher& dispatcher, Runtime::RandomGenerator& random, const LocalInfo::LocalInfo& local_info, Stats::Scope& scope); void runInitializeCallbackIfAny(); diff --git a/source/common/upstream/cds_subscription.cc b/source/common/upstream/cds_subscription.cc index 05701e4341c4..942417a59f29 100644 --- a/source/common/upstream/cds_subscription.cc +++ b/source/common/upstream/cds_subscription.cc @@ -12,12 +12,11 @@ namespace Envoy { namespace Upstream { -CdsSubscription::CdsSubscription(Config::SubscriptionStats stats, - const envoy::api::v2::core::ConfigSource& cds_config, - const Optional& eds_config, - ClusterManager& cm, Event::Dispatcher& dispatcher, - Runtime::RandomGenerator& random, - const LocalInfo::LocalInfo& local_info) +CdsSubscription::CdsSubscription( + Config::SubscriptionStats stats, const envoy::api::v2::core::ConfigSource& cds_config, + const absl::optional& eds_config, ClusterManager& cm, + Event::Dispatcher& dispatcher, Runtime::RandomGenerator& random, + const LocalInfo::LocalInfo& local_info) : RestApiFetcher(cm, cds_config.api_config_source().cluster_names()[0], dispatcher, random, Config::Utility::apiConfigSourceRefreshDelay(cds_config.api_config_source())), local_info_(local_info), stats_(stats), eds_config_(eds_config) { diff --git a/source/common/upstream/cds_subscription.h b/source/common/upstream/cds_subscription.h index 8904d8b7cc9d..6b47e0363d88 100644 --- a/source/common/upstream/cds_subscription.h +++ b/source/common/upstream/cds_subscription.h @@ -24,7 +24,7 @@ class CdsSubscription : public Http::RestApiFetcher, public: CdsSubscription(Config::SubscriptionStats stats, const envoy::api::v2::core::ConfigSource& cds_config, - const Optional& eds_config, + const absl::optional& eds_config, ClusterManager& cm, Event::Dispatcher& dispatcher, Runtime::RandomGenerator& random, const LocalInfo::LocalInfo& local_info); @@ -58,7 +58,7 @@ class CdsSubscription : public Http::RestApiFetcher, const LocalInfo::LocalInfo& local_info_; Config::SubscriptionCallbacks* callbacks_ = nullptr; Config::SubscriptionStats stats_; - const Optional& eds_config_; + const absl::optional& eds_config_; }; } // namespace Upstream diff --git a/source/common/upstream/cluster_manager_impl.cc b/source/common/upstream/cluster_manager_impl.cc index 0c1c29b6a321..e9a6047cb7ab 100644 --- a/source/common/upstream/cluster_manager_impl.cc +++ b/source/common/upstream/cluster_manager_impl.cc @@ -185,7 +185,7 @@ ClusterManagerImpl::ClusterManagerImpl(const envoy::config::bootstrap::v2::Boots } if (bootstrap.dynamic_resources().deprecated_v1().has_sds_config()) { - eds_config_.value(bootstrap.dynamic_resources().deprecated_v1().sds_config()); + eds_config_ = bootstrap.dynamic_resources().deprecated_v1().sds_config(); } if (bootstrap.cluster_manager().upstream_bind_config().has_source_address()) { @@ -253,10 +253,10 @@ ClusterManagerImpl::ClusterManagerImpl(const envoy::config::bootstrap::v2::Boots } } - Optional local_cluster_name; + absl::optional local_cluster_name; if (!cm_config.local_cluster_name().empty()) { local_cluster_name_ = cm_config.local_cluster_name(); - local_cluster_name.value(cm_config.local_cluster_name()); + local_cluster_name = cm_config.local_cluster_name(); if (primary_clusters_.find(local_cluster_name.value()) == primary_clusters_.end()) { throw EnvoyException( fmt::format("local cluster '{}' must be defined", local_cluster_name.value())); @@ -550,23 +550,23 @@ const std::string ClusterManagerImpl::versionInfo() const { ClusterManagerImpl::ThreadLocalClusterManagerImpl::ThreadLocalClusterManagerImpl( ClusterManagerImpl& parent, Event::Dispatcher& dispatcher, - const Optional& local_cluster_name) + const absl::optional& local_cluster_name) : parent_(parent), thread_local_dispatcher_(dispatcher) { // If local cluster is defined then we need to initialize it first. - if (local_cluster_name.valid()) { + if (local_cluster_name) { ENVOY_LOG(debug, "adding TLS local cluster {}", local_cluster_name.value()); auto& local_cluster = parent.primary_clusters_.at(local_cluster_name.value()); thread_local_clusters_[local_cluster_name.value()].reset(new ClusterEntry( *this, local_cluster.cluster_->info(), local_cluster.loadBalancerFactory())); } - local_priority_set_ = local_cluster_name.valid() + local_priority_set_ = local_cluster_name ? &thread_local_clusters_[local_cluster_name.value()]->priority_set_ : nullptr; for (auto& cluster : parent.primary_clusters_) { // If local cluster name is set then we already initialized this cluster. - if (local_cluster_name.valid() && local_cluster_name.value() == cluster.first) { + if (local_cluster_name && local_cluster_name.value() == cluster.first) { continue; } @@ -758,7 +758,7 @@ ClusterManagerImpl::ThreadLocalClusterManagerImpl::ClusterEntry::connPool( } // Inherit socket options from downstream connection, if set. - Optional hash_key; + absl::optional hash_key; // Use downstream connection socket options for computing connection pool hash key, if any. // This allows socket options to control connection pooling so that connections with @@ -767,16 +767,16 @@ ClusterManagerImpl::ThreadLocalClusterManagerImpl::ClusterEntry::connPool( const Network::ConnectionSocket::OptionsSharedPtr& options = context->downstreamConnection()->socketOptions(); if (options) { - hash_key.value(options->hashKey()); + hash_key = options->hashKey(); } } ConnPoolsContainer& container = parent_.host_http_conn_pool_map_[host]; - const auto key = container.key(priority, protocol, hash_key.valid() ? hash_key.value() : 0); + const auto key = container.key(priority, protocol, hash_key ? hash_key.value() : 0); if (!container.pools_[key]) { container.pools_[key] = parent_.parent_.factory_.allocateConnPool( parent_.thread_local_dispatcher_, host, priority, protocol, - hash_key.valid() ? context->downstreamConnection()->socketOptions() : nullptr); + hash_key ? context->downstreamConnection()->socketOptions() : nullptr); } return container.pools_[key].get(); @@ -811,10 +811,9 @@ ClusterSharedPtr ProdClusterManagerFactory::clusterFromProto( outlier_event_logger, added_via_api); } -CdsApiPtr -ProdClusterManagerFactory::createCds(const envoy::api::v2::core::ConfigSource& cds_config, - const Optional& eds_config, - ClusterManager& cm) { +CdsApiPtr ProdClusterManagerFactory::createCds( + const envoy::api::v2::core::ConfigSource& cds_config, + const absl::optional& eds_config, ClusterManager& cm) { return CdsApiImpl::create(cds_config, eds_config, cm, primary_dispatcher_, random_, local_info_, stats_); } diff --git a/source/common/upstream/cluster_manager_impl.h b/source/common/upstream/cluster_manager_impl.h index 656f6bc02e35..f1eded22a70c 100644 --- a/source/common/upstream/cluster_manager_impl.h +++ b/source/common/upstream/cluster_manager_impl.h @@ -54,7 +54,7 @@ class ProdClusterManagerFactory : public ClusterManagerFactory { Outlier::EventLoggerSharedPtr outlier_event_logger, bool added_via_api) override; CdsApiPtr createCds(const envoy::api::v2::core::ConfigSource& cds_config, - const Optional& eds_config, + const absl::optional& eds_config, ClusterManager& cm) override; protected: @@ -241,7 +241,7 @@ class ClusterManagerImpl : public ClusterManager, Logger::Loggable ClusterEntryPtr; ThreadLocalClusterManagerImpl(ClusterManagerImpl& parent, Event::Dispatcher& dispatcher, - const Optional& local_cluster_name); + const absl::optional& local_cluster_name); ~ThreadLocalClusterManagerImpl(); void drainConnPools(const HostVector& hosts); void drainConnPools(HostSharedPtr old_host, ConnPoolsContainer& container); @@ -293,7 +293,7 @@ class ClusterManagerImpl : public ClusterManager, Logger::Loggable primary_clusters_; - Optional eds_config_; + absl::optional eds_config_; Network::Address::InstanceConstSharedPtr source_address_; Outlier::EventLoggerSharedPtr outlier_event_logger_; const LocalInfo::LocalInfo& local_info_; diff --git a/source/common/upstream/health_checker_impl.cc b/source/common/upstream/health_checker_impl.cc index fab50df00502..3c5a3bc06e44 100644 --- a/source/common/upstream/health_checker_impl.cc +++ b/source/common/upstream/health_checker_impl.cc @@ -284,7 +284,7 @@ HttpHealthCheckerImpl::HttpHealthCheckerImpl(const Cluster& cluster, : HealthCheckerImplBase(cluster, config, dispatcher, runtime, random), path_(config.http_health_check().path()), host_value_(config.http_health_check().host()) { if (!config.http_health_check().service_name().empty()) { - service_name_.value(config.http_health_check().service_name()); + service_name_ = config.http_health_check().service_name(); } } @@ -361,7 +361,7 @@ bool HttpHealthCheckerImpl::HttpActiveHealthCheckSession::isHealthCheckSucceeded return false; } - if (parent_.service_name_.valid() && + if (parent_.service_name_ && parent_.runtime_.snapshot().featureEnabled("health_check.verify_cluster", 100UL)) { parent_.stats_.verify_cluster_.inc(); std::string service_cluster_healthchecked = @@ -646,7 +646,7 @@ GrpcHealthCheckerImpl::GrpcHealthCheckerImpl(const Cluster& cluster, service_method_(*Protobuf::DescriptorPool::generated_pool()->FindMethodByName( "grpc.health.v1.Health.Check")) { if (!config.grpc_health_check().service_name().empty()) { - service_name_.value(config.grpc_health_check().service_name()); + service_name_ = config.grpc_health_check().service_name(); } } @@ -670,7 +670,7 @@ void GrpcHealthCheckerImpl::GrpcActiveHealthCheckSession::decodeHeaders( // grpc-status be used if available. if (end_stream) { const auto grpc_status = Grpc::Common::getGrpcStatus(*headers); - if (grpc_status.valid()) { + if (grpc_status) { onRpcComplete(grpc_status.value(), Grpc::Common::getGrpcMessage(*headers), true); return; } @@ -687,7 +687,7 @@ void GrpcHealthCheckerImpl::GrpcActiveHealthCheckSession::decodeHeaders( // This is how, for instance, grpc-go signals about missing service - HTTP/2 200 OK with // 'unimplemented' gRPC status. const auto grpc_status = Grpc::Common::getGrpcStatus(*headers); - if (grpc_status.valid()) { + if (grpc_status) { onRpcComplete(grpc_status.value(), Grpc::Common::getGrpcMessage(*headers), true); return; } @@ -733,9 +733,9 @@ void GrpcHealthCheckerImpl::GrpcActiveHealthCheckSession::decodeTrailers( Http::HeaderMapPtr&& trailers) { auto maybe_grpc_status = Grpc::Common::getGrpcStatus(*trailers); auto grpc_status = - maybe_grpc_status.valid() ? maybe_grpc_status.value() : Grpc::Status::GrpcStatus::Internal; + maybe_grpc_status ? maybe_grpc_status.value() : Grpc::Status::GrpcStatus::Internal; const std::string grpc_message = - maybe_grpc_status.valid() ? Grpc::Common::getGrpcMessage(*trailers) : "invalid gRPC status"; + maybe_grpc_status ? Grpc::Common::getGrpcMessage(*trailers) : "invalid gRPC status"; onRpcComplete(grpc_status, grpc_message, true); } @@ -771,7 +771,7 @@ void GrpcHealthCheckerImpl::GrpcActiveHealthCheckSession::onInterval() { request_encoder_->encodeHeaders(headers_message->headers(), false); grpc::health::v1::HealthCheckRequest request; - if (parent_.service_name_.valid()) { + if (parent_.service_name_) { request.set_service(parent_.service_name_.value()); } diff --git a/source/common/upstream/health_checker_impl.h b/source/common/upstream/health_checker_impl.h index bb0c6fd2b601..8478612aedaf 100644 --- a/source/common/upstream/health_checker_impl.h +++ b/source/common/upstream/health_checker_impl.h @@ -233,7 +233,7 @@ class HttpHealthCheckerImpl : public HealthCheckerImplBase { const std::string path_; const std::string host_value_; - Optional service_name_; + absl::optional service_name_; }; /** @@ -514,7 +514,7 @@ class GrpcHealthCheckerImpl : public HealthCheckerImplBase { } const Protobuf::MethodDescriptor& service_method_; - Optional service_name_; + absl::optional service_name_; }; /** diff --git a/source/common/upstream/outlier_detection_impl.cc b/source/common/upstream/outlier_detection_impl.cc index 51b379706c5e..455fa3e787c2 100644 --- a/source/common/upstream/outlier_detection_impl.cc +++ b/source/common/upstream/outlier_detection_impl.cc @@ -34,11 +34,11 @@ void DetectorHostMonitorImpl::eject(MonotonicTime ejection_time) { ASSERT(!host_.lock()->healthFlagGet(Host::HealthFlag::FAILED_OUTLIER_CHECK)); host_.lock()->healthFlagSet(Host::HealthFlag::FAILED_OUTLIER_CHECK); num_ejections_++; - last_ejection_time_.value(ejection_time); + last_ejection_time_ = ejection_time; } void DetectorHostMonitorImpl::uneject(MonotonicTime unejection_time) { - last_unejection_time_.value(unejection_time); + last_unejection_time_ = (unejection_time); } void DetectorHostMonitorImpl::updateCurrentSuccessRateBucket() { @@ -399,10 +399,10 @@ void DetectorImpl::processSuccessRateEjections() { for (const auto& host : host_monitors_) { // Don't do work if the host is already ejected. if (!host.first->healthFlagGet(Host::HealthFlag::FAILED_OUTLIER_CHECK)) { - Optional host_success_rate = + absl::optional host_success_rate = host.second->successRateAccumulator().getSuccessRate(success_rate_request_volume); - if (host_success_rate.valid()) { + if (host_success_rate) { valid_success_rate_hosts.emplace_back( HostSuccessRatePair(host.first, host_success_rate.value())); success_rate_sum += host_success_rate.value(); @@ -542,9 +542,9 @@ std::string EventLoggerImpl::typeToString(EjectionType type) { NOT_REACHED; } -int EventLoggerImpl::secsSinceLastAction(const Optional& lastActionTime, +int EventLoggerImpl::secsSinceLastAction(const absl::optional& lastActionTime, MonotonicTime now) { - if (lastActionTime.valid()) { + if (lastActionTime) { return std::chrono::duration_cast(now - lastActionTime.value()).count(); } return -1; @@ -560,13 +560,14 @@ SuccessRateAccumulatorBucket* SuccessRateAccumulator::updateCurrentWriter() { return current_success_rate_bucket_.get(); } -Optional SuccessRateAccumulator::getSuccessRate(uint64_t success_rate_request_volume) { +absl::optional +SuccessRateAccumulator::getSuccessRate(uint64_t success_rate_request_volume) { if (backup_success_rate_bucket_->total_request_counter_ < success_rate_request_volume) { - return Optional(); + return absl::optional(); } - return Optional(backup_success_rate_bucket_->success_request_counter_ * 100.0 / - backup_success_rate_bucket_->total_request_counter_); + return absl::optional(backup_success_rate_bucket_->success_request_counter_ * 100.0 / + backup_success_rate_bucket_->total_request_counter_); } } // namespace Outlier diff --git a/source/common/upstream/outlier_detection_impl.h b/source/common/upstream/outlier_detection_impl.h index c90bb8c53a30..b273394de099 100644 --- a/source/common/upstream/outlier_detection_impl.h +++ b/source/common/upstream/outlier_detection_impl.h @@ -31,12 +31,12 @@ class DetectorHostMonitorNullImpl : public DetectorHostMonitor { void putHttpResponseCode(uint64_t) override {} void putResult(Result) override {} void putResponseTime(std::chrono::milliseconds) override {} - const Optional& lastEjectionTime() override { return time_; } - const Optional& lastUnejectionTime() override { return time_; } + const absl::optional& lastEjectionTime() override { return time_; } + const absl::optional& lastUnejectionTime() override { return time_; } double successRate() const override { return -1; } private: - const Optional time_; + const absl::optional time_; }; /** @@ -87,10 +87,10 @@ class SuccessRateAccumulator { * implementation it is a fixed time window. * @param success_rate_request_volume the threshold of requests an accumulator has to have in * order to be able to return a significant success rate value. - * @return a valid Optional with the success rate. If there were not enough requests, an - * invalid Optional is returned. + * @return a valid absl::optional with the success rate. If there were not enough + * requests, an invalid absl::optional is returned. */ - Optional getSuccessRate(uint64_t success_rate_request_volume); + absl::optional getSuccessRate(uint64_t success_rate_request_volume); private: std::unique_ptr current_success_rate_bucket_; @@ -124,8 +124,10 @@ class DetectorHostMonitorImpl : public DetectorHostMonitor { void putHttpResponseCode(uint64_t response_code) override; void putResult(Result result) override; void putResponseTime(std::chrono::milliseconds) override {} - const Optional& lastEjectionTime() override { return last_ejection_time_; } - const Optional& lastUnejectionTime() override { return last_unejection_time_; } + const absl::optional& lastEjectionTime() override { return last_ejection_time_; } + const absl::optional& lastUnejectionTime() override { + return last_unejection_time_; + } double successRate() const override { return success_rate_; } private: @@ -133,8 +135,8 @@ class DetectorHostMonitorImpl : public DetectorHostMonitor { std::weak_ptr host_; std::atomic consecutive_5xx_{0}; std::atomic consecutive_gateway_failure_{0}; - Optional last_ejection_time_; - Optional last_unejection_time_; + absl::optional last_ejection_time_; + absl::optional last_unejection_time_; uint32_t num_ejections_{}; SuccessRateAccumulator success_rate_accumulator_; std::atomic success_rate_accumulator_bucket_; @@ -269,7 +271,7 @@ class EventLoggerImpl : public EventLogger { private: std::string typeToString(EjectionType type); - int secsSinceLastAction(const Optional& lastActionTime, MonotonicTime now); + int secsSinceLastAction(const absl::optional& lastActionTime, MonotonicTime now); Filesystem::FileSharedPtr file_; SystemTimeSource& time_source_; diff --git a/source/common/upstream/ring_hash_lb.cc b/source/common/upstream/ring_hash_lb.cc index 2cb655421cfd..389e3db9855e 100644 --- a/source/common/upstream/ring_hash_lb.cc +++ b/source/common/upstream/ring_hash_lb.cc @@ -15,7 +15,7 @@ namespace Upstream { RingHashLoadBalancer::RingHashLoadBalancer( PrioritySet& priority_set, ClusterStats& stats, Runtime::Loader& runtime, Runtime::RandomGenerator& random, - const Optional& config, + const absl::optional& config, const envoy::api::v2::Cluster::CommonLbConfig& common_config) : ThreadAwareLoadBalancerBase(priority_set, stats, runtime, random, common_config), config_(config) {} @@ -57,8 +57,9 @@ HostConstSharedPtr RingHashLoadBalancer::Ring::chooseHost(uint64_t h) const { } } -RingHashLoadBalancer::Ring::Ring(const Optional& config, - const HostVector& hosts) { +RingHashLoadBalancer::Ring::Ring( + const absl::optional& config, + const HostVector& hosts) { ENVOY_LOG(trace, "ring hash: building ring"); if (hosts.empty()) { return; @@ -73,8 +74,7 @@ RingHashLoadBalancer::Ring::Ring(const Optional& config, + const absl::optional& config, const envoy::api::v2::Cluster::CommonLbConfig& common_config); private: @@ -34,7 +34,7 @@ class RingHashLoadBalancer : public ThreadAwareLoadBalancerBase, }; struct Ring : public HashingLoadBalancer { - Ring(const Optional& config, + Ring(const absl::optional& config, const HostVector& hosts); // ThreadAwareLoadBalancerBase::HashingLoadBalancer @@ -49,7 +49,7 @@ class RingHashLoadBalancer : public ThreadAwareLoadBalancerBase, return std::make_shared(config_, hosts); } - const Optional& config_; + const absl::optional& config_; }; } // namespace Upstream diff --git a/source/common/upstream/subset_lb.cc b/source/common/upstream/subset_lb.cc index 1ea3da85ed2a..87a282a0bf35 100644 --- a/source/common/upstream/subset_lb.cc +++ b/source/common/upstream/subset_lb.cc @@ -20,7 +20,7 @@ SubsetLoadBalancer::SubsetLoadBalancer( LoadBalancerType lb_type, PrioritySet& priority_set, const PrioritySet* local_priority_set, ClusterStats& stats, Runtime::Loader& runtime, Runtime::RandomGenerator& random, const LoadBalancerSubsetInfo& subsets, - const Optional& lb_ring_hash_config, + const absl::optional& lb_ring_hash_config, const envoy::api::v2::Cluster::CommonLbConfig& common_config) : lb_type_(lb_type), lb_ring_hash_config_(lb_ring_hash_config), common_config_(common_config), stats_(stats), runtime_(runtime), random_(random), fallback_policy_(subsets.fallbackPolicy()), diff --git a/source/common/upstream/subset_lb.h b/source/common/upstream/subset_lb.h index 283c6ba0a971..40424b8519da 100644 --- a/source/common/upstream/subset_lb.h +++ b/source/common/upstream/subset_lb.h @@ -6,7 +6,6 @@ #include #include -#include "envoy/common/optional.h" #include "envoy/runtime/runtime.h" #include "envoy/upstream/load_balancer.h" @@ -15,17 +14,19 @@ #include "common/protobuf/utility.h" #include "common/upstream/upstream_impl.h" +#include "absl/types/optional.h" + namespace Envoy { namespace Upstream { class SubsetLoadBalancer : public LoadBalancer, Logger::Loggable { public: - SubsetLoadBalancer(LoadBalancerType lb_type, PrioritySet& priority_set, - const PrioritySet* local_priority_set, ClusterStats& stats, - Runtime::Loader& runtime, Runtime::RandomGenerator& random, - const LoadBalancerSubsetInfo& subsets, - const Optional& lb_ring_hash_config, - const envoy::api::v2::Cluster::CommonLbConfig& common_config); + SubsetLoadBalancer( + LoadBalancerType lb_type, PrioritySet& priority_set, const PrioritySet* local_priority_set, + ClusterStats& stats, Runtime::Loader& runtime, Runtime::RandomGenerator& random, + const LoadBalancerSubsetInfo& subsets, + const absl::optional& lb_ring_hash_config, + const envoy::api::v2::Cluster::CommonLbConfig& common_config); // Upstream::LoadBalancer HostConstSharedPtr chooseHost(LoadBalancerContext* context) override; @@ -128,7 +129,7 @@ class SubsetLoadBalancer : public LoadBalancer, Logger::Loggable& subset_keys, const Host& host); const LoadBalancerType lb_type_; - const Optional lb_ring_hash_config_; + const absl::optional lb_ring_hash_config_; const envoy::api::v2::Cluster::CommonLbConfig common_config_; ClusterStats& stats_; Runtime::Loader& runtime_; diff --git a/source/common/upstream/thread_aware_lb_impl.cc b/source/common/upstream/thread_aware_lb_impl.cc index 836e79496391..057bbefb6249 100644 --- a/source/common/upstream/thread_aware_lb_impl.cc +++ b/source/common/upstream/thread_aware_lb_impl.cc @@ -53,11 +53,11 @@ ThreadAwareLoadBalancerBase::LoadBalancerImpl::chooseHost(LoadBalancerContext* c // If there is no hash in the context, just choose a random value (this effectively becomes // the random LB but it won't crash if someone configures it this way). // computeHashKey() may be computed on demand, so get it only once. - Optional hash; + absl::optional hash; if (context) { hash = context->computeHashKey(); } - const uint64_t h = hash.valid() ? hash.value() : random_.random(); + const uint64_t h = hash ? hash.value() : random_.random(); const uint32_t priority = LoadBalancerBase::choosePriority(h, *per_priority_load_); const auto& per_priority_state = (*per_priority_state_)[priority]; diff --git a/source/common/upstream/upstream_impl.h b/source/common/upstream/upstream_impl.h index 95a2facdd693..4edfd7688b5d 100644 --- a/source/common/upstream/upstream_impl.h +++ b/source/common/upstream/upstream_impl.h @@ -314,7 +314,8 @@ class ClusterInfoImpl : public ClusterInfo, const Http::Http2Settings& http2Settings() const override { return http2_settings_; } LoadBalancerType lbType() const override { return lb_type_; } envoy::api::v2::Cluster::DiscoveryType type() const override { return type_; } - const Optional& lbRingHashConfig() const override { + const absl::optional& + lbRingHashConfig() const override { return lb_ring_hash_config_; } bool maintenanceMode() const override; @@ -368,7 +369,7 @@ class ClusterInfoImpl : public ClusterInfo, const std::string maintenance_mode_runtime_key_; const Network::Address::InstanceConstSharedPtr source_address_; LoadBalancerType lb_type_; - Optional lb_ring_hash_config_; + absl::optional lb_ring_hash_config_; Ssl::ContextManager& ssl_context_manager_; const bool added_via_api_; LoadBalancerSubsetInfoImpl lb_subset_; diff --git a/source/server/BUILD b/source/server/BUILD index ffe0299bfe1d..ca9b1dcb5b35 100644 --- a/source/server/BUILD +++ b/source/server/BUILD @@ -89,9 +89,9 @@ envoy_cc_library( name = "guarddog_lib", srcs = ["guarddog_impl.cc"], hdrs = ["guarddog_impl.h"], + external_deps = ["abseil_optional"], deps = [ ":watchdog_lib", - "//include/envoy/common:optional", "//include/envoy/event:dispatcher_interface", "//include/envoy/server:configuration_interface", "//include/envoy/server:guarddog_interface", @@ -237,6 +237,7 @@ envoy_cc_library( name = "server_lib", srcs = ["server.cc"], hdrs = ["server.h"], + external_deps = ["abseil_optional"], deps = [ ":configuration_lib", ":connection_handler_lib", @@ -245,7 +246,6 @@ envoy_cc_library( ":listener_manager_lib", ":test_hooks_lib", ":worker_lib", - "//include/envoy/common:optional", "//include/envoy/event:dispatcher_interface", "//include/envoy/event:signal_interface", "//include/envoy/event:timer_interface", diff --git a/source/server/config/network/http_connection_manager.cc b/source/server/config/network/http_connection_manager.cc index d563c2a39b94..499961e4c2b1 100644 --- a/source/server/config/network/http_connection_manager.cc +++ b/source/server/config/network/http_connection_manager.cc @@ -171,7 +171,7 @@ HttpConnectionManagerConfig::HttpConnectionManagerConfig( } if (config.has_add_user_agent() && config.add_user_agent().value()) { - user_agent_.value(context_.localInfo().clusterName()); + user_agent_ = context_.localInfo().clusterName(); } if (config.has_tracing()) { @@ -202,7 +202,7 @@ HttpConnectionManagerConfig::HttpConnectionManagerConfig( } if (config.has_idle_timeout()) { - idle_timeout_.value(std::chrono::milliseconds(PROTOBUF_GET_MS_REQUIRED(config, idle_timeout))); + idle_timeout_ = std::chrono::milliseconds(PROTOBUF_GET_MS_REQUIRED(config, idle_timeout)); } for (const auto& access_log : config.access_log()) { diff --git a/source/server/config/network/http_connection_manager.h b/source/server/config/network/http_connection_manager.h index 5dd71a1eb070..d4222eec5576 100644 --- a/source/server/config/network/http_connection_manager.h +++ b/source/server/config/network/http_connection_manager.h @@ -84,7 +84,7 @@ class HttpConnectionManagerConfig : Logger::Loggable, std::chrono::milliseconds drainTimeout() override { return drain_timeout_; } FilterChainFactory& filterFactory() override { return *this; } bool generateRequestId() override { return generate_request_id_; } - const Optional& idleTimeout() override { return idle_timeout_; } + const absl::optional& idleTimeout() override { return idle_timeout_; } Router::RouteConfigProvider& routeConfigProvider() override { return *route_config_provider_; } const std::string& serverName() override { return server_name_; } Http::ConnectionManagerStats& stats() override { return stats_; } @@ -99,7 +99,7 @@ class HttpConnectionManagerConfig : Logger::Loggable, return tracing_config_.get(); } const Network::Address::Instance& localAddress() override; - const Optional& userAgent() override { return user_agent_; } + const absl::optional& userAgent() override { return user_agent_; } Http::ConnectionManagerListenerStats& listenerStats() override { return listener_stats_; } bool proxy100Continue() const override { return proxy_100_continue_; } @@ -124,8 +124,8 @@ class HttpConnectionManagerConfig : Logger::Loggable, const Http::Http1Settings http1_settings_; std::string server_name_; Http::TracingConnectionManagerConfigPtr tracing_config_; - Optional user_agent_; - Optional idle_timeout_; + absl::optional user_agent_; + absl::optional idle_timeout_; Router::RouteConfigProviderSharedPtr route_config_provider_; std::chrono::milliseconds drain_timeout_; bool generate_request_id_; diff --git a/source/server/config_validation/BUILD b/source/server/config_validation/BUILD index 75789426b4a5..706a9a9e73d9 100644 --- a/source/server/config_validation/BUILD +++ b/source/server/config_validation/BUILD @@ -74,12 +74,12 @@ envoy_cc_library( name = "server_lib", srcs = ["server.cc"], hdrs = ["server.h"], + external_deps = ["abseil_optional"], deps = [ ":admin_lib", ":api_lib", ":cluster_manager_lib", ":dns_lib", - "//include/envoy/common:optional", "//include/envoy/server:drain_manager_interface", "//include/envoy/server:instance_interface", "//include/envoy/ssl:context_manager_interface", diff --git a/source/server/config_validation/async_client.cc b/source/server/config_validation/async_client.cc index 0d5d9df99176..d29fcefa2d32 100644 --- a/source/server/config_validation/async_client.cc +++ b/source/server/config_validation/async_client.cc @@ -3,13 +3,15 @@ namespace Envoy { namespace Http { -AsyncClient::Request* ValidationAsyncClient::send(MessagePtr&&, Callbacks&, - const Optional&) { +AsyncClient::Request* +ValidationAsyncClient::send(MessagePtr&&, Callbacks&, + const absl::optional&) { return nullptr; } -AsyncClient::Stream* -ValidationAsyncClient::start(StreamCallbacks&, const Optional&, bool) { +AsyncClient::Stream* ValidationAsyncClient::start(StreamCallbacks&, + const absl::optional&, + bool) { return nullptr; } diff --git a/source/server/config_validation/async_client.h b/source/server/config_validation/async_client.h index 48c485d38d9c..a5050b2acef7 100644 --- a/source/server/config_validation/async_client.h +++ b/source/server/config_validation/async_client.h @@ -21,9 +21,9 @@ class ValidationAsyncClient : public AsyncClient { public: // Http::AsyncClient AsyncClient::Request* send(MessagePtr&& request, Callbacks& callbacks, - const Optional& timeout) override; + const absl::optional& timeout) override; AsyncClient::Stream* start(StreamCallbacks& callbacks, - const Optional& timeout, + const absl::optional& timeout, bool buffer_body_for_retry) override; Event::Dispatcher& dispatcher() override { return dispatcher_; } diff --git a/source/server/config_validation/cluster_manager.cc b/source/server/config_validation/cluster_manager.cc index 3e0e2adf53e5..69f95540f4ae 100644 --- a/source/server/config_validation/cluster_manager.cc +++ b/source/server/config_validation/cluster_manager.cc @@ -21,7 +21,7 @@ ClusterManagerPtr ValidationClusterManagerFactory::clusterManagerFromProto( CdsApiPtr ValidationClusterManagerFactory::createCds( const envoy::api::v2::core::ConfigSource& cds_config, - const Optional& eds_config, ClusterManager& cm) { + const absl::optional& eds_config, ClusterManager& cm) { // Create the CdsApiImpl... ProdClusterManagerFactory::createCds(cds_config, eds_config, cm); // ... and then throw it away, so that we don't actually connect to it. diff --git a/source/server/config_validation/cluster_manager.h b/source/server/config_validation/cluster_manager.h index 05251194645a..e888647cd0bc 100644 --- a/source/server/config_validation/cluster_manager.h +++ b/source/server/config_validation/cluster_manager.h @@ -31,7 +31,7 @@ class ValidationClusterManagerFactory : public ProdClusterManagerFactory { // Delegates to ProdClusterManagerFactory::createCds, but discards the result and returns nullptr // unconditionally. CdsApiPtr createCds(const envoy::api::v2::core::ConfigSource& cds_config, - const Optional& eds_config, + const absl::optional& eds_config, ClusterManager& cm) override; }; diff --git a/source/server/config_validation/server.h b/source/server/config_validation/server.h index 9ba652cd8ded..919613b00331 100644 --- a/source/server/config_validation/server.h +++ b/source/server/config_validation/server.h @@ -2,7 +2,6 @@ #include -#include "envoy/common/optional.h" #include "envoy/server/drain_manager.h" #include "envoy/server/instance.h" #include "envoy/ssl/context_manager.h" @@ -24,6 +23,8 @@ #include "server/listener_manager_impl.h" #include "server/server.h" +#include "absl/types/optional.h" + namespace Envoy { namespace Server { @@ -72,7 +73,7 @@ class ValidationInstance : Logger::Loggable, ListenerManager& listenerManager() override { return listener_manager_; } Runtime::RandomGenerator& random() override { return random_generator_; } RateLimit::ClientPtr - rateLimitClient(const Optional& timeout) override { + rateLimitClient(const absl::optional& timeout) override { return config_->rateLimitClientFactory().create(timeout); } Runtime::Loader& runtime() override { return *runtime_loader_; } diff --git a/source/server/configuration_impl.cc b/source/server/configuration_impl.cc index 38c530a38837..7ffa6e4dbeaa 100644 --- a/source/server/configuration_impl.cc +++ b/source/server/configuration_impl.cc @@ -136,7 +136,7 @@ InitialImpl::InitialImpl(const envoy::config::bootstrap::v2::Bootstrap& bootstra admin_.address_ = Network::Address::resolveProtoAddress(admin.address()); if (!bootstrap.flags_path().empty()) { - flags_path_.value(bootstrap.flags_path()); + flags_path_ = bootstrap.flags_path(); } if (bootstrap.has_runtime()) { diff --git a/source/server/configuration_impl.h b/source/server/configuration_impl.h index 0cdcb664415c..8c25359093e3 100644 --- a/source/server/configuration_impl.h +++ b/source/server/configuration_impl.h @@ -173,7 +173,7 @@ class InitialImpl : public Initial { // Server::Configuration::Initial Admin& admin() override { return admin_; } - Optional flagsPath() override { return flags_path_; } + absl::optional flagsPath() override { return flags_path_; } Runtime* runtime() override { return runtime_.get(); } private: @@ -200,7 +200,7 @@ class InitialImpl : public Initial { }; AdminImpl admin_; - Optional flags_path_; + absl::optional flags_path_; std::unique_ptr runtime_; }; diff --git a/source/server/guarddog_impl.cc b/source/server/guarddog_impl.cc index 109a2bc25b5b..898a1bc769b9 100644 --- a/source/server/guarddog_impl.cc +++ b/source/server/guarddog_impl.cc @@ -41,21 +41,21 @@ void GuardDogImpl::threadRoutine() { for (auto& watched_dog : watched_dogs_) { const auto ltt = watched_dog.dog_->lastTouchTime(); const auto delta = now - ltt; - if (watched_dog.last_alert_time_.valid() && watched_dog.last_alert_time_.value() < ltt) { + if (watched_dog.last_alert_time_ && watched_dog.last_alert_time_.value() < ltt) { watched_dog.miss_alerted_ = false; watched_dog.megamiss_alerted_ = false; } if (delta > miss_timeout_) { if (!watched_dog.miss_alerted_) { watchdog_miss_counter_.inc(); - watched_dog.last_alert_time_.value(ltt); + watched_dog.last_alert_time_ = ltt; watched_dog.miss_alerted_ = true; } } if (delta > megamiss_timeout_) { if (!watched_dog.megamiss_alerted_) { watchdog_megamiss_counter_.inc(); - watched_dog.last_alert_time_.value(ltt); + watched_dog.last_alert_time_ = ltt; watched_dog.megamiss_alerted_ = true; } } diff --git a/source/server/guarddog_impl.h b/source/server/guarddog_impl.h index faa912e90be1..893647438e54 100644 --- a/source/server/guarddog_impl.h +++ b/source/server/guarddog_impl.h @@ -5,7 +5,6 @@ #include #include -#include "envoy/common/optional.h" #include "envoy/server/configuration.h" #include "envoy/server/guarddog.h" #include "envoy/server/watchdog.h" @@ -15,6 +14,8 @@ #include "common/common/thread.h" #include "common/event/libevent.h" +#include "absl/types/optional.h" + namespace Envoy { namespace Server { @@ -69,7 +70,7 @@ class GuardDogImpl : public GuardDog { struct WatchedDog { WatchDogSharedPtr dog_; - Optional last_alert_time_; + absl::optional last_alert_time_; bool miss_alerted_{}; bool megamiss_alerted_{}; }; diff --git a/source/server/http/admin.cc b/source/server/http/admin.cc index 0a3f40778107..eb839e467d45 100644 --- a/source/server/http/admin.cc +++ b/source/server/http/admin.cc @@ -559,7 +559,7 @@ std::string AdminImpl::runtimeAsJson( entry_obj.AddMember("name", {entry.first.c_str(), allocator}, allocator); Value entry_value; - if (entry.second.uint_value_.valid()) { + if (entry.second.uint_value_) { entry_value.SetUint64(entry.second.uint_value_.value()); } else { entry_value.SetString(entry.second.string_value_.c_str(), allocator); diff --git a/source/server/http/admin.h b/source/server/http/admin.h index d45715ff7506..d3fd7c3d19fd 100644 --- a/source/server/http/admin.h +++ b/source/server/http/admin.h @@ -68,7 +68,7 @@ class AdminImpl : public Admin, std::chrono::milliseconds drainTimeout() override { return std::chrono::milliseconds(100); } Http::FilterChainFactory& filterFactory() override { return *this; } bool generateRequestId() override { return false; } - const Optional& idleTimeout() override { return idle_timeout_; } + const absl::optional& idleTimeout() override { return idle_timeout_; } Router::RouteConfigProvider& routeConfigProvider() override { return route_config_provider_; } const std::string& serverName() override { return Server::Configuration::HttpConnectionManagerConfig::DEFAULT_SERVER_STRING; @@ -84,7 +84,7 @@ class AdminImpl : public Admin, return set_current_client_cert_details_; } const Network::Address::Instance& localAddress() override; - const Optional& userAgent() override { return user_agent_; } + const absl::optional& userAgent() override { return user_agent_; } const Http::TracingConnectionManagerConfig* tracingConfig() override { return nullptr; } Http::ConnectionManagerListenerStats& listenerStats() override { return listener_.stats_; } bool proxy100Continue() const override { return false; } @@ -202,8 +202,8 @@ class AdminImpl : public Admin, Http::ConnectionManagerTracingStats tracing_stats_; NullRouteConfigProvider route_config_provider_; std::list handlers_; - Optional idle_timeout_; - Optional user_agent_; + absl::optional idle_timeout_; + absl::optional user_agent_; Http::SlowDateProviderImpl date_provider_; std::vector set_current_client_cert_details_; AdminListener listener_; diff --git a/source/server/listener_manager_impl.cc b/source/server/listener_manager_impl.cc index 653680bcc849..31f9e283d155 100644 --- a/source/server/listener_manager_impl.cc +++ b/source/server/listener_manager_impl.cc @@ -155,14 +155,14 @@ ListenerImpl::ListenerImpl(const envoy::api::v2::Listener& config, ListenerManag (config.filter_chains().size() == 1 && config.filter_chains()[0].filter_chain_match().sni_domains().empty()); - Optional filters_hash; + absl::optional filters_hash; uint32_t has_tls = 0; uint32_t has_stk = 0; for (const auto& filter_chain : config.filter_chains()) { std::vector sni_domains(filter_chain.filter_chain_match().sni_domains().begin(), filter_chain.filter_chain_match().sni_domains().end()); - if (!filters_hash.valid()) { - filters_hash.value(RepeatedPtrUtil::hash(filter_chain.filters())); + if (!filters_hash) { + filters_hash = RepeatedPtrUtil::hash(filter_chain.filters()); filter_factories_ = parent_.factory_.createNetworkFilterFactoryList(filter_chain.filters(), *this); } else if (filters_hash.value() != RepeatedPtrUtil::hash(filter_chain.filters())) { diff --git a/source/server/listener_manager_impl.h b/source/server/listener_manager_impl.h index 5925e9230eec..3b649edd6ea3 100644 --- a/source/server/listener_manager_impl.h +++ b/source/server/listener_manager_impl.h @@ -237,7 +237,7 @@ class ListenerImpl : public Network::ListenerConfig, const LocalInfo::LocalInfo& localInfo() override { return parent_.server_.localInfo(); } Envoy::Runtime::RandomGenerator& random() override { return parent_.server_.random(); } RateLimit::ClientPtr - rateLimitClient(const Optional& timeout) override { + rateLimitClient(const absl::optional& timeout) override { return parent_.server_.rateLimitClient(timeout); } Envoy::Runtime::Loader& runtime() override { return parent_.server_.runtime(); } diff --git a/source/server/server.cc b/source/server/server.cc index 7c5faaa7ff32..53c452b23d01 100644 --- a/source/server/server.cc +++ b/source/server/server.cc @@ -289,8 +289,8 @@ Runtime::LoaderPtr InstanceUtil::createRuntime(Instance& server, } } -void InstanceImpl::loadServerFlags(const Optional& flags_path) { - if (!flags_path.valid()) { +void InstanceImpl::loadServerFlags(const absl::optional& flags_path) { + if (!flags_path) { return; } diff --git a/source/server/server.h b/source/server/server.h index fa73bd9f6fb5..c99b556c5d1d 100644 --- a/source/server/server.h +++ b/source/server/server.h @@ -7,7 +7,6 @@ #include #include -#include "envoy/common/optional.h" #include "envoy/server/configuration.h" #include "envoy/server/drain_manager.h" #include "envoy/server/guarddog.h" @@ -27,6 +26,8 @@ #include "server/test_hooks.h" #include "server/worker_impl.h" +#include "absl/types/optional.h" + namespace Envoy { namespace Server { @@ -148,7 +149,7 @@ class InstanceImpl : Logger::Loggable, public Instance { ListenerManager& listenerManager() override { return *listener_manager_; } Runtime::RandomGenerator& random() override { return random_generator_; } RateLimit::ClientPtr - rateLimitClient(const Optional& timeout) override { + rateLimitClient(const absl::optional& timeout) override { return config_->rateLimitClientFactory().create(timeout); } Runtime::Loader& runtime() override; @@ -168,7 +169,7 @@ class InstanceImpl : Logger::Loggable, public Instance { void flushStats(); void initialize(Options& options, Network::Address::InstanceConstSharedPtr local_address, ComponentFactory& component_factory); - void loadServerFlags(const Optional& flags_path); + void loadServerFlags(const absl::optional& flags_path); uint64_t numConnections(); void startWorkers(); void terminate(); diff --git a/test/common/access_log/access_log_formatter_test.cc b/test/common/access_log/access_log_formatter_test.cc index 1dbc99262a35..2bd865b7db69 100644 --- a/test/common/access_log/access_log_formatter_test.cc +++ b/test/common/access_log/access_log_formatter_test.cc @@ -55,28 +55,28 @@ TEST(AccessLogFormatterTest, requestInfoFormatter) { { RequestInfoFormatter request_duration_format("REQUEST_DURATION"); - Optional dur = std::chrono::nanoseconds(5000000); + absl::optional dur = std::chrono::nanoseconds(5000000); EXPECT_CALL(request_info, lastDownstreamRxByteReceived()).WillOnce(Return(dur)); EXPECT_EQ("5", request_duration_format.format(header, header, request_info)); } { RequestInfoFormatter request_duration_format("REQUEST_DURATION"); - Optional dur; + absl::optional dur; EXPECT_CALL(request_info, lastDownstreamRxByteReceived()).WillOnce(Return(dur)); EXPECT_EQ("-", request_duration_format.format(header, header, request_info)); } { RequestInfoFormatter response_duration_format("RESPONSE_DURATION"); - Optional dur = std::chrono::nanoseconds(10000000); + absl::optional dur = std::chrono::nanoseconds(10000000); EXPECT_CALL(request_info, firstUpstreamRxByteReceived()).WillRepeatedly(Return(dur)); EXPECT_EQ("10", response_duration_format.format(header, header, request_info)); } { RequestInfoFormatter response_duration_format("RESPONSE_DURATION"); - Optional dur; + absl::optional dur; EXPECT_CALL(request_info, firstUpstreamRxByteReceived()).WillRepeatedly(Return(dur)); EXPECT_EQ("-", response_duration_format.format(header, header, request_info)); } @@ -89,21 +89,21 @@ TEST(AccessLogFormatterTest, requestInfoFormatter) { { RequestInfoFormatter protocol_format("PROTOCOL"); - Optional protocol = Http::Protocol::Http11; + absl::optional protocol = Http::Protocol::Http11; EXPECT_CALL(request_info, protocol()).WillOnce(Return(protocol)); EXPECT_EQ("HTTP/1.1", protocol_format.format(header, header, request_info)); } { RequestInfoFormatter response_format("RESPONSE_CODE"); - Optional response_code{200}; + absl::optional response_code{200}; EXPECT_CALL(request_info, responseCode()).WillRepeatedly(Return(response_code)); EXPECT_EQ("200", response_format.format(header, header, request_info)); } { RequestInfoFormatter response_code_format("RESPONSE_CODE"); - Optional response_code; + absl::optional response_code; EXPECT_CALL(request_info, responseCode()).WillRepeatedly(Return(response_code)); EXPECT_EQ("0", response_code_format.format(header, header, request_info)); } @@ -116,7 +116,7 @@ TEST(AccessLogFormatterTest, requestInfoFormatter) { { RequestInfoFormatter duration_format("DURATION"); - Optional dur = std::chrono::nanoseconds(15000000); + absl::optional dur = std::chrono::nanoseconds(15000000); EXPECT_CALL(request_info, requestComplete()).WillRepeatedly(Return(dur)); EXPECT_EQ("15", duration_format.format(header, header, request_info)); } @@ -184,22 +184,22 @@ TEST(AccessLogFormatterTest, requestHeaderFormatter) { Http::TestHeaderMapImpl response_header{{":method", "PUT"}}; { - RequestHeaderFormatter formatter(":Method", "", Optional()); + RequestHeaderFormatter formatter(":Method", "", absl::optional()); EXPECT_EQ("GET", formatter.format(request_header, response_header, request_info)); } { - RequestHeaderFormatter formatter(":path", ":method", Optional()); + RequestHeaderFormatter formatter(":path", ":method", absl::optional()); EXPECT_EQ("/", formatter.format(request_header, response_header, request_info)); } { - RequestHeaderFormatter formatter(":TEST", ":METHOD", Optional()); + RequestHeaderFormatter formatter(":TEST", ":METHOD", absl::optional()); EXPECT_EQ("GET", formatter.format(request_header, response_header, request_info)); } { - RequestHeaderFormatter formatter("does_not_exist", "", Optional()); + RequestHeaderFormatter formatter("does_not_exist", "", absl::optional()); EXPECT_EQ("-", formatter.format(request_header, response_header, request_info)); } } @@ -210,22 +210,22 @@ TEST(AccessLogFormatterTest, responseHeaderFormatter) { Http::TestHeaderMapImpl response_header{{":method", "PUT"}, {"test", "test"}}; { - ResponseHeaderFormatter formatter(":method", "", Optional()); + ResponseHeaderFormatter formatter(":method", "", absl::optional()); EXPECT_EQ("PUT", formatter.format(request_header, response_header, request_info)); } { - ResponseHeaderFormatter formatter("test", ":method", Optional()); + ResponseHeaderFormatter formatter("test", ":method", absl::optional()); EXPECT_EQ("test", formatter.format(request_header, response_header, request_info)); } { - ResponseHeaderFormatter formatter(":path", ":method", Optional()); + ResponseHeaderFormatter formatter(":path", ":method", absl::optional()); EXPECT_EQ("PUT", formatter.format(request_header, response_header, request_info)); } { - ResponseHeaderFormatter formatter("does_not_exist", "", Optional()); + ResponseHeaderFormatter formatter("does_not_exist", "", absl::optional()); EXPECT_EQ("-", formatter.format(request_header, response_header, request_info)); } } @@ -240,7 +240,7 @@ TEST(AccessLogFormatterTest, CompositeFormatterSuccess) { "%REQ(FIRST?SECOND)% %RESP(FIRST?SECOND)%[]"; FormatterImpl formatter(format); - Optional protocol = Http::Protocol::Http11; + absl::optional protocol = Http::Protocol::Http11; EXPECT_CALL(request_info, protocol()).WillRepeatedly(Return(protocol)); EXPECT_EQ("{{HTTP/1.1}} -++test GET PUT[]", diff --git a/test/common/access_log/access_log_impl_test.cc b/test/common/access_log/access_log_impl_test.cc index 97bdabe01dc5..dcfcee3048e7 100644 --- a/test/common/access_log/access_log_impl_test.cc +++ b/test/common/access_log/access_log_impl_test.cc @@ -58,16 +58,16 @@ class TestRequestInfo : public RequestInfo::RequestInfo { MonotonicTime now = std::chrono::steady_clock::now(); start_time_monotonic_ = now; - end_time_.value(now + std::chrono::milliseconds(3)); + end_time_ = now + std::chrono::milliseconds(3); } SystemTime startTime() const override { return start_time_; } MonotonicTime startTimeMonotonic() const override { return start_time_monotonic_; } uint64_t bytesReceived() const override { return 1; } - Optional protocol() const override { return protocol_; } + absl::optional protocol() const override { return protocol_; } void protocol(Http::Protocol protocol) override { protocol_ = protocol; } - Optional responseCode() const override { return response_code_; } + absl::optional responseCode() const override { return response_code_; } uint64_t bytesSent() const override { return 2; } bool getResponseFlag(Envoy::RequestInfo::ResponseFlag response_flag) const override { @@ -94,8 +94,9 @@ class TestRequestInfo : public RequestInfo::RequestInfo { const Router::RouteEntry* routeEntry() const override { return route_entry_; } - Optional duration(const Optional& time) const { - if (!time.valid()) { + absl::optional + duration(const absl::optional& time) const { + if (!time) { return {}; } @@ -103,89 +104,89 @@ class TestRequestInfo : public RequestInfo::RequestInfo { start_time_monotonic_); } - Optional lastDownstreamRxByteReceived() const override { + absl::optional lastDownstreamRxByteReceived() const override { return duration(last_rx_byte_received_); } void onLastDownstreamRxByteReceived() override { - last_rx_byte_received_.value(std::chrono::steady_clock::now()); + last_rx_byte_received_ = std::chrono::steady_clock::now(); } - Optional firstUpstreamTxByteSent() const override { + absl::optional firstUpstreamTxByteSent() const override { return duration(first_upstream_tx_byte_sent_); } void onFirstUpstreamTxByteSent() override { - first_upstream_tx_byte_sent_.value(std::chrono::steady_clock::now()); + first_upstream_tx_byte_sent_ = std::chrono::steady_clock::now(); } - Optional lastUpstreamTxByteSent() const override { + absl::optional lastUpstreamTxByteSent() const override { return duration(last_upstream_tx_byte_sent_); } void onLastUpstreamTxByteSent() override { - last_upstream_tx_byte_sent_.value(std::chrono::steady_clock::now()); + last_upstream_tx_byte_sent_ = std::chrono::steady_clock::now(); } - Optional firstUpstreamRxByteReceived() const override { + absl::optional firstUpstreamRxByteReceived() const override { return duration(first_upstream_rx_byte_received_); } void onFirstUpstreamRxByteReceived() override { - first_upstream_rx_byte_received_.value(std::chrono::steady_clock::now()); + first_upstream_rx_byte_received_ = std::chrono::steady_clock::now(); } - Optional lastUpstreamRxByteReceived() const override { + absl::optional lastUpstreamRxByteReceived() const override { return duration(last_upstream_rx_byte_received_); } void onLastUpstreamRxByteReceived() override { - last_upstream_rx_byte_received_.value(std::chrono::steady_clock::now()); + last_upstream_rx_byte_received_ = std::chrono::steady_clock::now(); } - Optional firstDownstreamTxByteSent() const override { + absl::optional firstDownstreamTxByteSent() const override { return duration(first_downstream_tx_byte_sent_); } void onFirstDownstreamTxByteSent() override { - first_downstream_tx_byte_sent_.value(std::chrono::steady_clock::now()); + first_downstream_tx_byte_sent_ = std::chrono::steady_clock::now(); } - Optional lastDownstreamTxByteSent() const override { + absl::optional lastDownstreamTxByteSent() const override { return duration(last_downstream_tx_byte_sent_); } void onLastDownstreamTxByteSent() override { - last_downstream_tx_byte_sent_.value(std::chrono::steady_clock::now()); + last_downstream_tx_byte_sent_ = std::chrono::steady_clock::now(); } - void onRequestComplete() override { end_time_.value(std::chrono::steady_clock::now()); } + void onRequestComplete() override { end_time_ = std::chrono::steady_clock::now(); } void resetUpstreamTimings() override { - first_upstream_tx_byte_sent_ = Optional{}; - last_upstream_tx_byte_sent_ = Optional{}; - first_upstream_rx_byte_received_ = Optional{}; - last_upstream_rx_byte_received_ = Optional{}; + first_upstream_tx_byte_sent_ = absl::optional{}; + last_upstream_tx_byte_sent_ = absl::optional{}; + first_upstream_rx_byte_received_ = absl::optional{}; + last_upstream_rx_byte_received_ = absl::optional{}; } - Optional requestComplete() const override { + absl::optional requestComplete() const override { return duration(end_time_); } SystemTime start_time_; MonotonicTime start_time_monotonic_; - Optional last_rx_byte_received_; - Optional first_upstream_tx_byte_sent_; - Optional last_upstream_tx_byte_sent_; - Optional first_upstream_rx_byte_received_; - Optional last_upstream_rx_byte_received_; - Optional first_downstream_tx_byte_sent_; - Optional last_downstream_tx_byte_sent_; - Optional end_time_; - - Optional protocol_{Http::Protocol::Http11}; - Optional response_code_; + absl::optional last_rx_byte_received_; + absl::optional first_upstream_tx_byte_sent_; + absl::optional last_upstream_tx_byte_sent_; + absl::optional first_upstream_rx_byte_received_; + absl::optional last_upstream_rx_byte_received_; + absl::optional first_downstream_tx_byte_sent_; + absl::optional last_downstream_tx_byte_sent_; + absl::optional end_time_; + + absl::optional protocol_{Http::Protocol::Http11}; + absl::optional response_code_; uint64_t response_flags_{}; Upstream::HostDescriptionConstSharedPtr upstream_host_{}; bool hc_request_{}; @@ -307,7 +308,7 @@ TEST_F(AccessLogImplTest, WithFilterMiss) { EXPECT_CALL(*file_, write(_)).Times(0); log->log(&request_headers_, &response_headers_, request_info_); - request_info_.response_code_.value(200); + request_info_.response_code_ = 200; log->log(&request_headers_, &response_headers_, request_info_); } @@ -329,12 +330,12 @@ TEST_F(AccessLogImplTest, WithFilterHit) { EXPECT_CALL(*file_, write(_)).Times(3); log->log(&request_headers_, &response_headers_, request_info_); - request_info_.response_code_.value(500); + request_info_.response_code_ = 500; log->log(&request_headers_, &response_headers_, request_info_); - request_info_.response_code_.value(200); - request_info_.end_time_.value(request_info_.startTimeMonotonic() + - std::chrono::microseconds(1001000000000000)); + request_info_.response_code_ = 200; + request_info_.end_time_ = + request_info_.startTimeMonotonic() + std::chrono::microseconds(1001000000000000); log->log(&request_headers_, &response_headers_, request_info_); } @@ -577,7 +578,7 @@ TEST_F(AccessLogImplTest, andFilter) { )EOF"; InstanceSharedPtr log = AccessLogFactory::fromProto(parseAccessLogFromJson(json), context_); - request_info_.response_code_.value(500); + request_info_.response_code_ = 500; { EXPECT_CALL(*file_, write(_)); @@ -607,7 +608,7 @@ TEST_F(AccessLogImplTest, orFilter) { )EOF"; InstanceSharedPtr log = AccessLogFactory::fromProto(parseAccessLogFromJson(json), context_); - request_info_.response_code_.value(500); + request_info_.response_code_ = 500; { EXPECT_CALL(*file_, write(_)); @@ -640,7 +641,7 @@ TEST_F(AccessLogImplTest, multipleOperators) { )EOF"; InstanceSharedPtr log = AccessLogFactory::fromProto(parseAccessLogFromJson(json), context_); - request_info_.response_code_.value(500); + request_info_.response_code_ = 500; { EXPECT_CALL(*file_, write(_)); @@ -699,21 +700,19 @@ TEST(AccessLogFilterTest, DurationWithRuntimeKey) { Http::TestHeaderMapImpl request_headers{{":method", "GET"}, {":path", "/"}}; TestRequestInfo request_info; - request_info.end_time_.value(request_info.startTimeMonotonic() + - std::chrono::microseconds(100000)); + request_info.end_time_ = request_info.startTimeMonotonic() + std::chrono::microseconds(100000); EXPECT_CALL(runtime.snapshot_, getInteger("key", 1000000)).WillOnce(Return(1)); EXPECT_TRUE(filter.evaluate(request_info, request_headers)); EXPECT_CALL(runtime.snapshot_, getInteger("key", 1000000)).WillOnce(Return(1000)); EXPECT_FALSE(filter.evaluate(request_info, request_headers)); - request_info.end_time_.value(request_info.startTimeMonotonic() + - std::chrono::microseconds(100000001000)); + request_info.end_time_ = + request_info.startTimeMonotonic() + std::chrono::microseconds(100000001000); EXPECT_CALL(runtime.snapshot_, getInteger("key", 1000000)).WillOnce(Return(100000000)); EXPECT_TRUE(filter.evaluate(request_info, request_headers)); - request_info.end_time_.value(request_info.startTimeMonotonic() + - std::chrono::microseconds(10000)); + request_info.end_time_ = request_info.startTimeMonotonic() + std::chrono::microseconds(10000); EXPECT_CALL(runtime.snapshot_, getInteger("key", 1000000)).WillOnce(Return(100000000)); EXPECT_FALSE(filter.evaluate(request_info, request_headers)); } @@ -736,7 +735,7 @@ TEST(AccessLogFilterTest, StatusCodeWithRuntimeKey) { Http::TestHeaderMapImpl request_headers{{":method", "GET"}, {":path", "/"}}; TestRequestInfo info; - info.response_code_.value(400); + info.response_code_ = 400; EXPECT_CALL(runtime.snapshot_, getInteger("key", 300)).WillOnce(Return(350)); EXPECT_TRUE(filter.evaluate(info, request_headers)); @@ -760,12 +759,12 @@ name: envoy.file_access_log InstanceSharedPtr log = AccessLogFactory::fromProto(parseAccessLogFromV2Yaml(yaml), context_); - request_info_.response_code_.value(499); + request_info_.response_code_ = 499; EXPECT_CALL(runtime_.snapshot_, getInteger("hello", 499)).WillOnce(Return(499)); EXPECT_CALL(*file_, write(_)); log->log(&request_headers_, &response_headers_, request_info_); - request_info_.response_code_.value(500); + request_info_.response_code_ = 500; EXPECT_CALL(runtime_.snapshot_, getInteger("hello", 499)).WillOnce(Return(499)); EXPECT_CALL(*file_, write(_)).Times(0); log->log(&request_headers_, &response_headers_, request_info_); diff --git a/test/common/access_log/grpc_access_log_impl_test.cc b/test/common/access_log/grpc_access_log_impl_test.cc index 6188d6672c3b..bd84dd3bbc95 100644 --- a/test/common/access_log/grpc_access_log_impl_test.cc +++ b/test/common/access_log/grpc_access_log_impl_test.cc @@ -141,7 +141,7 @@ TEST_F(HttpGrpcAccessLogTest, Marshalling) { request_info.host_ = nullptr; request_info.start_time_ = SystemTime(1h); request_info.start_time_monotonic_ = MonotonicTime(1h); - request_info.last_downstream_tx_byte_sent_.value(2ms); + request_info.last_downstream_tx_byte_sent_ = 2ms; request_info.downstream_local_address_ = std::make_shared("/foo"); @@ -170,7 +170,7 @@ TEST_F(HttpGrpcAccessLogTest, Marshalling) { NiceMock request_info; request_info.host_ = nullptr; request_info.start_time_ = SystemTime(1h); - request_info.last_downstream_tx_byte_sent_.value(std::chrono::nanoseconds(2000000)); + request_info.last_downstream_tx_byte_sent_ = std::chrono::nanoseconds(2000000); expectLog(R"EOF( http_logs: @@ -198,20 +198,20 @@ TEST_F(HttpGrpcAccessLogTest, Marshalling) { NiceMock request_info; request_info.start_time_ = SystemTime(1h); - request_info.last_downstream_rx_byte_received_.value(2ms); - request_info.first_upstream_tx_byte_sent_.value(4ms); - request_info.last_upstream_tx_byte_sent_.value(6ms); - request_info.first_upstream_rx_byte_received_.value(8ms); - request_info.last_upstream_rx_byte_received_.value(10ms); - request_info.first_downstream_tx_byte_sent_.value(12ms); - request_info.last_downstream_tx_byte_sent_.value(14ms); + request_info.last_downstream_rx_byte_received_ = 2ms; + request_info.first_upstream_tx_byte_sent_ = 4ms; + request_info.last_upstream_tx_byte_sent_ = 6ms; + request_info.first_upstream_rx_byte_received_ = 8ms; + request_info.last_upstream_rx_byte_received_ = 10ms; + request_info.first_downstream_tx_byte_sent_ = 12ms; + request_info.last_downstream_tx_byte_sent_ = 14ms; request_info.upstream_local_address_ = std::make_shared("10.0.0.2"); request_info.protocol_ = Http::Protocol::Http10; request_info.bytes_received_ = 10; request_info.bytes_sent_ = 20; - request_info.response_code_.value(200); + request_info.response_code_ = 200; ON_CALL(request_info, getResponseFlag(RequestInfo::ResponseFlag::FaultInjected)) .WillByDefault(Return(true)); diff --git a/test/common/common/BUILD b/test/common/common/BUILD index 4a4f2029152a..fdd7a773223f 100644 --- a/test/common/common/BUILD +++ b/test/common/common/BUILD @@ -10,13 +10,6 @@ load( envoy_package() -envoy_cc_fuzz_test( - name = "base64_fuzz_test", - srcs = ["base64_fuzz_test.cc"], - corpus = "base64_corpus", - deps = ["//source/common/common:base64_lib"], -) - envoy_cc_test( name = "base64_test", srcs = ["base64_test.cc"], @@ -26,6 +19,13 @@ envoy_cc_test( ], ) +envoy_cc_fuzz_test( + name = "base64_fuzz_test", + srcs = ["base64_fuzz_test.cc"], + corpus = "base64_corpus", + deps = ["//source/common/common:base64_lib"], +) + envoy_cc_test( name = "cleanup_test", srcs = ["cleanup_test.cc"], @@ -53,12 +53,6 @@ envoy_cc_test( deps = ["//source/common/common:hex_lib"], ) -envoy_cc_test( - name = "optional_test", - srcs = ["optional_test.cc"], - deps = ["//include/envoy/common:optional"], -) - envoy_cc_test( name = "log_macros_test", srcs = ["log_macros_test.cc"], diff --git a/test/common/common/optional_test.cc b/test/common/common/optional_test.cc deleted file mode 100644 index 7e6ec351b9c8..000000000000 --- a/test/common/common/optional_test.cc +++ /dev/null @@ -1,31 +0,0 @@ -#include "envoy/common/optional.h" - -#include "gtest/gtest.h" - -namespace Envoy { -TEST(Optional, All) { - Optional optional; - EXPECT_FALSE(optional.valid()); - EXPECT_THROW(optional.value(), EnvoyException); - - optional.value(5); - EXPECT_TRUE(optional.valid()); - EXPECT_EQ(5, optional.value()); - - Optional optional_op; - EXPECT_FALSE(optional_op.valid()); - EXPECT_THROW(optional_op.value(), EnvoyException); - - optional_op = 7; - EXPECT_TRUE(optional_op.valid()); - EXPECT_EQ(7, optional_op.value()); - - const Optional optional_const; - EXPECT_FALSE(optional_const.valid()); - EXPECT_THROW(optional_const.value(), EnvoyException); - - const Optional optional_const_2(10); - EXPECT_TRUE(optional_const_2.valid()); - EXPECT_EQ(10, optional_const_2.value()); -} -} // namespace Envoy diff --git a/test/common/config/http_subscription_test_harness.h b/test/common/config/http_subscription_test_harness.h index 9f7df13538b3..0d95a1299f57 100644 --- a/test/common/config/http_subscription_test_harness.h +++ b/test/common/config/http_subscription_test_harness.h @@ -55,7 +55,7 @@ class HttpSubscriptionTestHarness : public SubscriptionTestHarness { EXPECT_CALL(cm_.async_client_, send_(_, _, _)) .WillOnce(Invoke([this, cluster_names, version]( Http::MessagePtr& request, Http::AsyncClient::Callbacks& callbacks, - const Optional& timeout) { + const absl::optional& timeout) { http_callbacks_ = &callbacks; UNREFERENCED_PARAMETER(timeout); EXPECT_EQ("POST", std::string(request->headers().Method()->value().c_str())); diff --git a/test/common/config/subscription_factory_test.cc b/test/common/config/subscription_factory_test.cc index 13a6da030a81..151a14321ccb 100644 --- a/test/common/config/subscription_factory_test.cc +++ b/test/common/config/subscription_factory_test.cc @@ -126,7 +126,7 @@ TEST_F(SubscriptionFactoryTest, HttpSubscription) { EXPECT_CALL(cm_, httpAsyncClientForCluster("eds_cluster")); EXPECT_CALL(cm_.async_client_, send_(_, _, _)) .WillOnce(Invoke([this](Http::MessagePtr& request, Http::AsyncClient::Callbacks& callbacks, - const Optional& timeout) { + const absl::optional& timeout) { UNREFERENCED_PARAMETER(callbacks); UNREFERENCED_PARAMETER(timeout); EXPECT_EQ("POST", std::string(request->headers().Method()->value().c_str())); diff --git a/test/common/ext_authz/ext_authz_impl_test.cc b/test/common/ext_authz/ext_authz_impl_test.cc index e8aae336b523..e7290f40a184 100644 --- a/test/common/ext_authz/ext_authz_impl_test.cc +++ b/test/common/ext_authz/ext_authz_impl_test.cc @@ -40,7 +40,7 @@ class ExtAuthzGrpcClientTest : public testing::Test { public: ExtAuthzGrpcClientTest() : async_client_(new Grpc::MockAsyncClient()), - client_(Grpc::AsyncClientPtr{async_client_}, Optional()) {} + client_(Grpc::AsyncClientPtr{async_client_}, absl::optional()) {} Grpc::MockAsyncClient* async_client_; Grpc::MockAsyncRequest async_request_; @@ -75,7 +75,7 @@ TEST_F(ExtAuthzGrpcClientTest, BasicDenied) { .WillOnce( Invoke([this](const Protobuf::MethodDescriptor& service_method, const Protobuf::Message&, Grpc::AsyncRequestCallbacks&, Tracing::Span&, - const Optional&) -> Grpc::AsyncRequest* { + const absl::optional&) -> Grpc::AsyncRequest* { EXPECT_EQ("envoy.service.auth.v2.Authorization", service_method.service()->full_name()); EXPECT_EQ("Check", service_method.name()); return &async_request_; @@ -123,7 +123,7 @@ class CheckRequestUtilsTest : public testing::Test { }; Network::Address::InstanceConstSharedPtr addr_; - Optional protocol_; + absl::optional protocol_; CheckRequestUtils check_request_generator_; NiceMock callbacks_; NiceMock net_callbacks_; diff --git a/test/common/filter/auth/client_ssl_test.cc b/test/common/filter/auth/client_ssl_test.cc index cd0050661ad6..fe799213f8b3 100644 --- a/test/common/filter/auth/client_ssl_test.cc +++ b/test/common/filter/auth/client_ssl_test.cc @@ -96,9 +96,9 @@ class ClientSslAuthFilterTest : public testing::Test { void setupRequest() { EXPECT_CALL(cm_, httpAsyncClientForCluster("vpn")).WillOnce(ReturnRef(cm_.async_client_)); EXPECT_CALL(cm_.async_client_, send_(_, _, _)) - .WillOnce( - Invoke([this](Http::MessagePtr&, Http::AsyncClient::Callbacks& callbacks, - Optional) -> Http::AsyncClient::Request* { + .WillOnce(Invoke( + [this](Http::MessagePtr&, Http::AsyncClient::Callbacks& callbacks, + absl::optional) -> Http::AsyncClient::Request* { callbacks_ = &callbacks; return &request_; })); @@ -249,9 +249,9 @@ TEST_F(ClientSslAuthFilterTest, Ssl) { // Interval timer fires, cannot obtain async client. EXPECT_CALL(cm_, httpAsyncClientForCluster("vpn")).WillOnce(ReturnRef(cm_.async_client_)); EXPECT_CALL(cm_.async_client_, send_(_, _, _)) - .WillOnce( - Invoke([&](Http::MessagePtr&, Http::AsyncClient::Callbacks& callbacks, - const Optional&) -> Http::AsyncClient::Request* { + .WillOnce(Invoke( + [&](Http::MessagePtr&, Http::AsyncClient::Callbacks& callbacks, + const absl::optional&) -> Http::AsyncClient::Request* { callbacks.onSuccess(Http::MessagePtr{new Http::ResponseMessageImpl( Http::HeaderMapPtr{new Http::TestHeaderMapImpl{{":status", "503"}}})}); return nullptr; diff --git a/test/common/filter/tcp_proxy_test.cc b/test/common/filter/tcp_proxy_test.cc index 0e4889f2f1fd..051d47776845 100644 --- a/test/common/filter/tcp_proxy_test.cc +++ b/test/common/filter/tcp_proxy_test.cc @@ -444,7 +444,7 @@ class TcpProxyTest : public testing::Test { : Network::FilterStatus::StopIteration, filter_->onNewConnection()); - EXPECT_EQ(Optional(), filter_->computeHashKey()); + EXPECT_EQ(absl::optional(), filter_->computeHashKey()); EXPECT_EQ(&filter_callbacks_.connection_, filter_->downstreamConnection()); EXPECT_EQ(nullptr, filter_->metadataMatchCriteria()); } diff --git a/test/common/grpc/async_client_impl_test.cc b/test/common/grpc/async_client_impl_test.cc index 3749ae18991b..4e14181331eb 100644 --- a/test/common/grpc/async_client_impl_test.cc +++ b/test/common/grpc/async_client_impl_test.cc @@ -63,7 +63,7 @@ TEST_F(EnvoyAsyncClientImplTest, RequestHttpStartFail) { EXPECT_CALL(*child_span, injectContext(_)).Times(0); auto* grpc_request = grpc_client_->send(*method_descriptor_, request_msg, grpc_callbacks, - active_span, Optional()); + active_span, absl::optional()); EXPECT_EQ(grpc_request, nullptr); } @@ -74,9 +74,9 @@ TEST_F(EnvoyAsyncClientImplTest, StreamHttpSendHeadersFail) { Http::AsyncClient::StreamCallbacks* http_callbacks; Http::MockAsyncClientStream http_stream; EXPECT_CALL(http_client_, start(_, _, false)) - .WillOnce( - Invoke([&http_callbacks, &http_stream](Http::AsyncClient::StreamCallbacks& callbacks, - const Optional&, bool) { + .WillOnce(Invoke( + [&http_callbacks, &http_stream](Http::AsyncClient::StreamCallbacks& callbacks, + const absl::optional&, bool) { http_callbacks = &callbacks; return &http_stream; })); @@ -100,9 +100,9 @@ TEST_F(EnvoyAsyncClientImplTest, RequestHttpSendHeadersFail) { Http::AsyncClient::StreamCallbacks* http_callbacks; Http::MockAsyncClientStream http_stream; EXPECT_CALL(http_client_, start(_, _, true)) - .WillOnce( - Invoke([&http_callbacks, &http_stream](Http::AsyncClient::StreamCallbacks& callbacks, - const Optional&, bool) { + .WillOnce(Invoke( + [&http_callbacks, &http_stream](Http::AsyncClient::StreamCallbacks& callbacks, + const absl::optional&, bool) { http_callbacks = &callbacks; return &http_stream; })); @@ -128,7 +128,7 @@ TEST_F(EnvoyAsyncClientImplTest, RequestHttpSendHeadersFail) { EXPECT_CALL(*child_span, finishSpan()); auto* grpc_request = grpc_client_->send(*method_descriptor_, request_msg, grpc_callbacks, - active_span, Optional()); + active_span, absl::optional()); EXPECT_EQ(grpc_request, nullptr); } diff --git a/test/common/grpc/common_test.cc b/test/common/grpc/common_test.cc index 109c7dcf9af1..cd676270743d 100644 --- a/test/common/grpc/common_test.cc +++ b/test/common/grpc/common_test.cc @@ -16,7 +16,7 @@ TEST(GrpcCommonTest, GetGrpcStatus) { EXPECT_EQ(Status::Ok, Common::getGrpcStatus(ok_trailers).value()); Http::TestHeaderMapImpl no_status_trailers{{"foo", "bar"}}; - EXPECT_FALSE(Common::getGrpcStatus(no_status_trailers).valid()); + EXPECT_FALSE(Common::getGrpcStatus(no_status_trailers)); Http::TestHeaderMapImpl aborted_trailers{{"grpc-status", "10"}}; EXPECT_EQ(Status::Aborted, Common::getGrpcStatus(aborted_trailers).value()); diff --git a/test/common/grpc/google_async_client_impl_test.cc b/test/common/grpc/google_async_client_impl_test.cc index 8425441f8790..3f69613832ae 100644 --- a/test/common/grpc/google_async_client_impl_test.cc +++ b/test/common/grpc/google_async_client_impl_test.cc @@ -93,7 +93,7 @@ TEST_F(EnvoyGoogleAsyncClientImplTest, RequestHttpStartFail) { EXPECT_CALL(*child_span, injectContext(_)); auto* grpc_request = grpc_client_->send(*method_descriptor_, request_msg, grpc_callbacks, - active_span, Optional()); + active_span, absl::optional()); EXPECT_EQ(grpc_request, nullptr); } diff --git a/test/common/grpc/grpc_client_integration_test.cc b/test/common/grpc/grpc_client_integration_test.cc index 5f9d2d6e1dae..ad2ab42781dd 100644 --- a/test/common/grpc/grpc_client_integration_test.cc +++ b/test/common/grpc/grpc_client_integration_test.cc @@ -334,8 +334,9 @@ class GrpcClientIntegrationTest : public GrpcClientIntegrationParamTest { setTag(Tracing::Tags::get().COMPONENT, Tracing::Tags::get().PROXY)); EXPECT_CALL(*request->child_span_, injectContext(_)); - request->grpc_request_ = grpc_client_->send(*method_descriptor_, request_msg, *request, - active_span, Optional()); + request->grpc_request_ = + grpc_client_->send(*method_descriptor_, request_msg, *request, active_span, + absl::optional()); EXPECT_NE(request->grpc_request_, nullptr); if (!fake_connection_) { diff --git a/test/common/grpc/http1_bridge_filter_test.cc b/test/common/grpc/http1_bridge_filter_test.cc index a00d5a30609c..da3390351ac3 100644 --- a/test/common/grpc/http1_bridge_filter_test.cc +++ b/test/common/grpc/http1_bridge_filter_test.cc @@ -33,7 +33,7 @@ class GrpcHttp1BridgeFilterTest : public testing::Test { Http1BridgeFilter filter_; NiceMock decoder_callbacks_; NiceMock encoder_callbacks_; - Optional protocol_{Http::Protocol::Http11}; + absl::optional protocol_{Http::Protocol::Http11}; }; TEST_F(GrpcHttp1BridgeFilterTest, NoRoute) { diff --git a/test/common/http/async_client_impl_test.cc b/test/common/http/async_client_impl_test.cc index 74266d5be8dd..fc3b36990bae 100644 --- a/test/common/http/async_client_impl_test.cc +++ b/test/common/http/async_client_impl_test.cc @@ -98,7 +98,7 @@ TEST_F(AsyncClientImplTest, BasicStream) { EXPECT_CALL(stream_callbacks_, onData(BufferEqual(body.get()), true)); AsyncClient::Stream* stream = - client_.start(stream_callbacks_, Optional(), false); + client_.start(stream_callbacks_, absl::optional(), false); stream->sendHeaders(headers, false); stream->sendData(*body, true); @@ -136,7 +136,7 @@ TEST_F(AsyncClientImplTest, Basic) { EXPECT_CALL(stream_encoder_, encodeData(BufferEqual(&data), true)); expectSuccess(200); - client_.send(std::move(message_), callbacks_, Optional()); + client_.send(std::move(message_), callbacks_, absl::optional()); HeaderMapPtr response_headers(new TestHeaderMapImpl{{":status", "200"}}); response_decoder_->decodeHeaders(std::move(response_headers), false); @@ -170,7 +170,7 @@ TEST_F(AsyncClientImplTest, Retry) { EXPECT_CALL(stream_encoder_, encodeData(BufferEqual(&data), true)); message_->headers().insertEnvoyRetryOn().value(Headers::get().EnvoyRetryOnValues._5xx); - client_.send(std::move(message_), callbacks_, Optional()); + client_.send(std::move(message_), callbacks_, absl::optional()); // Expect retry and retry timer create. timer_ = new NiceMock(&dispatcher_); @@ -216,7 +216,7 @@ TEST_F(AsyncClientImplTest, RetryWithStream) { headers.insertEnvoyRetryOn().value(Headers::get().EnvoyRetryOnValues._5xx); AsyncClient::Stream* stream = - client_.start(stream_callbacks_, Optional(), true); + client_.start(stream_callbacks_, absl::optional(), true); stream->sendHeaders(headers, false); stream->sendData(*body, true); @@ -264,7 +264,7 @@ TEST_F(AsyncClientImplTest, MultipleStreams) { EXPECT_CALL(stream_callbacks_, onData(BufferEqual(body.get()), true)); AsyncClient::Stream* stream = - client_.start(stream_callbacks_, Optional(), false); + client_.start(stream_callbacks_, absl::optional(), false); stream->sendHeaders(headers, false); stream->sendData(*body, true); @@ -289,7 +289,7 @@ TEST_F(AsyncClientImplTest, MultipleStreams) { expectResponseHeaders(stream_callbacks2, 503, true); AsyncClient::Stream* stream2 = - client_.start(stream_callbacks2, Optional(), false); + client_.start(stream_callbacks2, absl::optional(), false); stream2->sendHeaders(headers2, false); stream2->sendData(*body2, true); @@ -319,7 +319,7 @@ TEST_F(AsyncClientImplTest, MultipleRequests) { EXPECT_CALL(stream_encoder_, encodeHeaders(HeaderMapEqualRef(&message_->headers()), false)); EXPECT_CALL(stream_encoder_, encodeData(BufferEqual(&data), true)); - client_.send(std::move(message_), callbacks_, Optional()); + client_.send(std::move(message_), callbacks_, absl::optional()); // Send request 2. MessagePtr message2{new RequestMessageImpl()}; @@ -335,7 +335,7 @@ TEST_F(AsyncClientImplTest, MultipleRequests) { return nullptr; })); EXPECT_CALL(stream_encoder2, encodeHeaders(HeaderMapEqualRef(&message2->headers()), true)); - client_.send(std::move(message2), callbacks2, Optional()); + client_.send(std::move(message2), callbacks2, absl::optional()); // Finish request 2. HeaderMapPtr response_headers2(new TestHeaderMapImpl{{":status", "503"}}); @@ -365,7 +365,7 @@ TEST_F(AsyncClientImplTest, StreamAndRequest) { EXPECT_CALL(stream_encoder_, encodeHeaders(HeaderMapEqualRef(&message_->headers()), false)); EXPECT_CALL(stream_encoder_, encodeData(BufferEqual(&data), true)); - client_.send(std::move(message_), callbacks_, Optional()); + client_.send(std::move(message_), callbacks_, absl::optional()); // Start stream Buffer::InstancePtr body{new Buffer::OwnedImpl("test body")}; @@ -389,7 +389,7 @@ TEST_F(AsyncClientImplTest, StreamAndRequest) { EXPECT_CALL(stream_callbacks_, onData(BufferEqual(body.get()), true)); AsyncClient::Stream* stream = - client_.start(stream_callbacks_, Optional(), false); + client_.start(stream_callbacks_, absl::optional(), false); stream->sendHeaders(headers, false); stream->sendData(*body, true); @@ -429,7 +429,7 @@ TEST_F(AsyncClientImplTest, StreamWithTrailers) { EXPECT_CALL(stream_callbacks_, onTrailers_(HeaderMapEqualRef(&expected_trailers))); AsyncClient::Stream* stream = - client_.start(stream_callbacks_, Optional(), false); + client_.start(stream_callbacks_, absl::optional(), false); stream->sendHeaders(headers, false); stream->sendData(*body, false); stream->sendTrailers(trailers); @@ -456,7 +456,7 @@ TEST_F(AsyncClientImplTest, Trailers) { EXPECT_CALL(stream_encoder_, encodeData(BufferEqual(&data), true)); expectSuccess(200); - client_.send(std::move(message_), callbacks_, Optional()); + client_.send(std::move(message_), callbacks_, absl::optional()); HeaderMapPtr response_headers(new TestHeaderMapImpl{{":status", "200"}}); response_decoder_->decodeHeaders(std::move(response_headers), false); response_decoder_->decodeData(data, false); @@ -474,7 +474,7 @@ TEST_F(AsyncClientImplTest, ImmediateReset) { EXPECT_CALL(stream_encoder_, encodeHeaders(HeaderMapEqualRef(&message_->headers()), true)); expectSuccess(503); - client_.send(std::move(message_), callbacks_, Optional()); + client_.send(std::move(message_), callbacks_, absl::optional()); stream_encoder_.getStream().resetStream(StreamResetReason::RemoteReset); EXPECT_EQ( @@ -508,7 +508,7 @@ TEST_F(AsyncClientImplTest, LocalResetAfterStreamStart) { EXPECT_CALL(stream_callbacks_, onReset()); AsyncClient::Stream* stream = - client_.start(stream_callbacks_, Optional(), false); + client_.start(stream_callbacks_, absl::optional(), false); stream->sendHeaders(headers, false); stream->sendData(*body, false); @@ -540,7 +540,7 @@ TEST_F(AsyncClientImplTest, ResetInOnHeaders) { EXPECT_CALL(stream_encoder_, encodeData(BufferEqual(body.get()), false)); AsyncClient::Stream* stream = - client_.start(stream_callbacks_, Optional(), false); + client_.start(stream_callbacks_, absl::optional(), false); TestHeaderMapImpl expected_headers{{":status", "200"}}; EXPECT_CALL(stream_callbacks_, onHeaders_(HeaderMapEqualRef(&expected_headers), false)) @@ -582,7 +582,7 @@ TEST_F(AsyncClientImplTest, RemoteResetAfterStreamStart) { EXPECT_CALL(stream_callbacks_, onReset()); AsyncClient::Stream* stream = - client_.start(stream_callbacks_, Optional(), false); + client_.start(stream_callbacks_, absl::optional(), false); stream->sendHeaders(headers, false); stream->sendData(*body, false); @@ -604,7 +604,7 @@ TEST_F(AsyncClientImplTest, ResetAfterResponseStart) { EXPECT_CALL(stream_encoder_, encodeHeaders(HeaderMapEqualRef(&message_->headers()), true)); EXPECT_CALL(callbacks_, onFailure(_)); - client_.send(std::move(message_), callbacks_, Optional()); + client_.send(std::move(message_), callbacks_, absl::optional()); HeaderMapPtr response_headers(new TestHeaderMapImpl{{":status", "200"}}); response_decoder_->decodeHeaders(std::move(response_headers), false); stream_encoder_.getStream().resetStream(StreamResetReason::RemoteReset); @@ -623,7 +623,7 @@ TEST_F(AsyncClientImplTest, ResetStream) { EXPECT_CALL(stream_callbacks_, onReset()); AsyncClient::Stream* stream = - client_.start(stream_callbacks_, Optional(), false); + client_.start(stream_callbacks_, absl::optional(), false); stream->sendHeaders(message_->headers(), true); stream->reset(); } @@ -640,7 +640,7 @@ TEST_F(AsyncClientImplTest, CancelRequest) { EXPECT_CALL(stream_encoder_.stream_, resetStream(_)); AsyncClient::Request* request = - client_.send(std::move(message_), callbacks_, Optional()); + client_.send(std::move(message_), callbacks_, absl::optional()); request->cancel(); } @@ -656,7 +656,7 @@ TEST_F(AsyncClientImplTest, DestroyWithActiveStream) { EXPECT_CALL(stream_encoder_.stream_, resetStream(_)); EXPECT_CALL(stream_callbacks_, onReset()); AsyncClient::Stream* stream = - client_.start(stream_callbacks_, Optional(), false); + client_.start(stream_callbacks_, absl::optional(), false); stream->sendHeaders(message_->headers(), false); } @@ -671,7 +671,7 @@ TEST_F(AsyncClientImplTest, DestroyWithActiveRequest) { EXPECT_CALL(stream_encoder_, encodeHeaders(HeaderMapEqualRef(&message_->headers()), true)); EXPECT_CALL(stream_encoder_.stream_, resetStream(_)); EXPECT_CALL(callbacks_, onFailure(_)); - client_.send(std::move(message_), callbacks_, Optional()); + client_.send(std::move(message_), callbacks_, absl::optional()); } TEST_F(AsyncClientImplTest, PoolFailure) { @@ -683,8 +683,8 @@ TEST_F(AsyncClientImplTest, PoolFailure) { })); expectSuccess(503); - EXPECT_EQ(nullptr, - client_.send(std::move(message_), callbacks_, Optional())); + EXPECT_EQ(nullptr, client_.send(std::move(message_), callbacks_, + absl::optional())); EXPECT_EQ( 1UL, @@ -701,8 +701,8 @@ TEST_F(AsyncClientImplTest, PoolFailureWithBody) { expectSuccess(503); message_->body().reset(new Buffer::OwnedImpl("hello")); - EXPECT_EQ(nullptr, - client_.send(std::move(message_), callbacks_, Optional())); + EXPECT_EQ(nullptr, client_.send(std::move(message_), callbacks_, + absl::optional())); EXPECT_EQ( 1UL, @@ -831,7 +831,7 @@ TEST_F(AsyncClientImplTest, MultipleDataStream) { EXPECT_CALL(stream_callbacks_, onData(BufferEqual(body.get()), false)); AsyncClient::Stream* stream = - client_.start(stream_callbacks_, Optional(), false); + client_.start(stream_callbacks_, absl::optional(), false); stream->sendHeaders(headers, false); stream->sendData(*body, false); @@ -856,7 +856,7 @@ TEST_F(AsyncClientImplTest, WatermarkCallbacks) { TestHeaderMapImpl headers; HttpTestUtility::addDefaultHeaders(headers); AsyncClient::Stream* stream = - client_.start(stream_callbacks_, Optional(), false); + client_.start(stream_callbacks_, absl::optional(), false); stream->sendHeaders(headers, false); Http::StreamDecoderFilterCallbacks* filter_callbacks = static_cast(stream); @@ -869,7 +869,7 @@ TEST_F(AsyncClientImplTest, RdsGettersTest) { TestHeaderMapImpl headers; HttpTestUtility::addDefaultHeaders(headers); AsyncClient::Stream* stream = - client_.start(stream_callbacks_, Optional(), false); + client_.start(stream_callbacks_, absl::optional(), false); stream->sendHeaders(headers, false); Http::StreamDecoderFilterCallbacks* filter_callbacks = static_cast(stream); diff --git a/test/common/http/conn_manager_impl_test.cc b/test/common/http/conn_manager_impl_test.cc index cb71e9a52b26..c30e392923e4 100644 --- a/test/common/http/conn_manager_impl_test.cc +++ b/test/common/http/conn_manager_impl_test.cc @@ -229,7 +229,7 @@ class HttpConnectionManagerImplTest : public Test, public ConnectionManagerConfi std::chrono::milliseconds drainTimeout() override { return std::chrono::milliseconds(100); } FilterChainFactory& filterFactory() override { return filter_factory_; } bool generateRequestId() override { return true; } - const Optional& idleTimeout() override { return idle_timeout_; } + const absl::optional& idleTimeout() override { return idle_timeout_; } Router::RouteConfigProvider& routeConfigProvider() override { return route_config_provider_; } const std::string& serverName() override { return server_name_; } ConnectionManagerStats& stats() override { return stats_; } @@ -241,7 +241,7 @@ class HttpConnectionManagerImplTest : public Test, public ConnectionManagerConfi return set_current_client_cert_details_; } const Network::Address::Instance& localAddress() override { return local_address_; } - const Optional& userAgent() override { return user_agent_; } + const absl::optional& userAgent() override { return user_agent_; } const TracingConnectionManagerConfig* tracingConfig() override { return tracing_config_.get(); } ConnectionManagerListenerStats& listenerStats() override { return listener_stats_; } bool proxy100Continue() const override { return proxy_100_continue_; } @@ -264,8 +264,8 @@ class HttpConnectionManagerImplTest : public Test, public ConnectionManagerConfi bool use_remote_address_{true}; Http::ForwardClientCertType forward_client_cert_{Http::ForwardClientCertType::Sanitize}; std::vector set_current_client_cert_details_; - Optional user_agent_; - Optional idle_timeout_; + absl::optional user_agent_; + absl::optional idle_timeout_; NiceMock random_; NiceMock local_info_; std::unique_ptr ssl_connection_; @@ -885,7 +885,7 @@ TEST_F(HttpConnectionManagerImplTest, TestAccessLog) { EXPECT_CALL(*handler, log(_, _, _)) .WillOnce(Invoke( [](const HeaderMap*, const HeaderMap*, const RequestInfo::RequestInfo& request_info) { - EXPECT_TRUE(request_info.responseCode().valid()); + EXPECT_TRUE(request_info.responseCode()); EXPECT_EQ(request_info.responseCode().value(), uint32_t(200)); EXPECT_NE(nullptr, request_info.downstreamLocalAddress()); EXPECT_NE(nullptr, request_info.downstreamRemoteAddress()); @@ -1459,7 +1459,7 @@ TEST_F(HttpConnectionManagerImplTest, IdleTimeoutNoCodec) { // Not used in the test. delete codec_; - idle_timeout_.value(std::chrono::milliseconds(10)); + idle_timeout_ = (std::chrono::milliseconds(10)); Event::MockTimer* idle_timer = new Event::MockTimer(&filter_callbacks_.connection_.dispatcher_); EXPECT_CALL(*idle_timer, enableTimer(_)); setup(false, ""); @@ -1472,7 +1472,7 @@ TEST_F(HttpConnectionManagerImplTest, IdleTimeoutNoCodec) { } TEST_F(HttpConnectionManagerImplTest, IdleTimeout) { - idle_timeout_.value(std::chrono::milliseconds(10)); + idle_timeout_ = (std::chrono::milliseconds(10)); Event::MockTimer* idle_timer = new Event::MockTimer(&filter_callbacks_.connection_.dispatcher_); EXPECT_CALL(*idle_timer, enableTimer(_)); setup(false, ""); diff --git a/test/common/http/conn_manager_utility_test.cc b/test/common/http/conn_manager_utility_test.cc index 8f19a50459d1..c90f536a8ca0 100644 --- a/test/common/http/conn_manager_utility_test.cc +++ b/test/common/http/conn_manager_utility_test.cc @@ -62,7 +62,7 @@ class ConnectionManagerUtilityTest : public testing::Test { NiceMock random_; NiceMock config_; NiceMock route_config_; - Optional user_agent_; + absl::optional user_agent_; NiceMock runtime_; Http::TracingConnectionManagerConfig tracing_config_; NiceMock local_info_; @@ -136,7 +136,7 @@ TEST_F(ConnectionManagerUtilityTest, UserAgentSetWhenIncomingEmpty) { connection_.remote_address_ = std::make_shared("10.0.0.1"); ON_CALL(config_, useRemoteAddress()).WillByDefault(Return(true)); ON_CALL(local_info_, nodeName()).WillByDefault(Return(canary_node_)); - user_agent_.value("bar"); + user_agent_ = "bar"; TestHeaderMapImpl headers{{"user-agent", ""}, {"x-envoy-downstream-service-cluster", "foo"}}; EXPECT_EQ((MutateRequestRet{"10.0.0.1:0", true}), @@ -257,7 +257,7 @@ TEST_F(ConnectionManagerUtilityTest, UserAgentSetIncomingUserAgent) { connection_.remote_address_ = std::make_shared("10.0.0.1"); ON_CALL(config_, useRemoteAddress()).WillByDefault(Return(true)); - user_agent_.value("bar"); + user_agent_ = "bar"; TestHeaderMapImpl headers{{"user-agent", "foo"}, {"x-envoy-downstream-service-cluster", "foo"}}; EXPECT_CALL(local_info_, nodeName()).WillOnce(Return(empty_node_)); @@ -272,7 +272,7 @@ TEST_F(ConnectionManagerUtilityTest, UserAgentSetIncomingUserAgent) { TEST_F(ConnectionManagerUtilityTest, UserAgentSetNoIncomingUserAgent) { connection_.remote_address_ = std::make_shared("10.0.0.1"); ON_CALL(config_, useRemoteAddress()).WillByDefault(Return(true)); - user_agent_.value("bar"); + user_agent_ = "bar"; TestHeaderMapImpl headers; EXPECT_EQ((MutateRequestRet{"10.0.0.1:0", true}), diff --git a/test/common/http/filter/lua/lua_filter_test.cc b/test/common/http/filter/lua/lua_filter_test.cc index 331ddfd62d6c..2c60b81e550a 100644 --- a/test/common/http/filter/lua/lua_filter_test.cc +++ b/test/common/http/filter/lua/lua_filter_test.cc @@ -721,16 +721,17 @@ TEST_F(LuaHttpFilterTest, HttpCall) { EXPECT_CALL(cluster_manager_, get("cluster")); EXPECT_CALL(cluster_manager_, httpAsyncClientForCluster("cluster")); EXPECT_CALL(cluster_manager_.async_client_, send_(_, _, _)) - .WillOnce(Invoke([&](MessagePtr& message, AsyncClient::Callbacks& cb, - const Optional&) -> AsyncClient::Request* { - EXPECT_EQ((TestHeaderMapImpl{{":path", "/"}, - {":method", "POST"}, - {":authority", "foo"}, - {"content-length", "11"}}), - message->headers()); - callbacks = &cb; - return &request; - })); + .WillOnce( + Invoke([&](MessagePtr& message, AsyncClient::Callbacks& cb, + const absl::optional&) -> AsyncClient::Request* { + EXPECT_EQ((TestHeaderMapImpl{{":path", "/"}, + {":method", "POST"}, + {":authority", "foo"}, + {"content-length", "11"}}), + message->headers()); + callbacks = &cb; + return &request; + })); EXPECT_EQ(FilterHeadersStatus::StopIteration, filter_->decodeHeaders(request_headers, false)); @@ -794,16 +795,17 @@ TEST_F(LuaHttpFilterTest, DoubleHttpCall) { EXPECT_CALL(cluster_manager_, get("cluster")); EXPECT_CALL(cluster_manager_, httpAsyncClientForCluster("cluster")); EXPECT_CALL(cluster_manager_.async_client_, send_(_, _, _)) - .WillOnce(Invoke([&](MessagePtr& message, AsyncClient::Callbacks& cb, - const Optional&) -> AsyncClient::Request* { - EXPECT_EQ((TestHeaderMapImpl{{":path", "/"}, - {":method", "POST"}, - {":authority", "foo"}, - {"content-length", "11"}}), - message->headers()); - callbacks = &cb; - return &request; - })); + .WillOnce( + Invoke([&](MessagePtr& message, AsyncClient::Callbacks& cb, + const absl::optional&) -> AsyncClient::Request* { + EXPECT_EQ((TestHeaderMapImpl{{":path", "/"}, + {":method", "POST"}, + {":authority", "foo"}, + {"content-length", "11"}}), + message->headers()); + callbacks = &cb; + return &request; + })); EXPECT_EQ(FilterHeadersStatus::StopIteration, filter_->decodeHeaders(request_headers, false)); @@ -815,13 +817,15 @@ TEST_F(LuaHttpFilterTest, DoubleHttpCall) { EXPECT_CALL(cluster_manager_, get("cluster2")); EXPECT_CALL(cluster_manager_, httpAsyncClientForCluster("cluster2")); EXPECT_CALL(cluster_manager_.async_client_, send_(_, _, _)) - .WillOnce(Invoke([&](MessagePtr& message, AsyncClient::Callbacks& cb, - const Optional&) -> AsyncClient::Request* { - EXPECT_EQ((TestHeaderMapImpl{{":path", "/bar"}, {":method", "GET"}, {":authority", "foo"}}), - message->headers()); - callbacks = &cb; - return &request; - })); + .WillOnce( + Invoke([&](MessagePtr& message, AsyncClient::Callbacks& cb, + const absl::optional&) -> AsyncClient::Request* { + EXPECT_EQ( + (TestHeaderMapImpl{{":path", "/bar"}, {":method", "GET"}, {":authority", "foo"}}), + message->headers()); + callbacks = &cb; + return &request; + })); callbacks->onSuccess(std::move(response_message)); response_message.reset( @@ -869,13 +873,15 @@ TEST_F(LuaHttpFilterTest, HttpCallNoBody) { EXPECT_CALL(cluster_manager_, get("cluster")); EXPECT_CALL(cluster_manager_, httpAsyncClientForCluster("cluster")); EXPECT_CALL(cluster_manager_.async_client_, send_(_, _, _)) - .WillOnce(Invoke([&](MessagePtr& message, AsyncClient::Callbacks& cb, - const Optional&) -> AsyncClient::Request* { - EXPECT_EQ((TestHeaderMapImpl{{":path", "/"}, {":method", "GET"}, {":authority", "foo"}}), - message->headers()); - callbacks = &cb; - return &request; - })); + .WillOnce( + Invoke([&](MessagePtr& message, AsyncClient::Callbacks& cb, + const absl::optional&) -> AsyncClient::Request* { + EXPECT_EQ( + (TestHeaderMapImpl{{":path", "/"}, {":method", "GET"}, {":authority", "foo"}}), + message->headers()); + callbacks = &cb; + return &request; + })); EXPECT_EQ(FilterHeadersStatus::StopIteration, filter_->decodeHeaders(request_headers, false)); @@ -921,13 +927,15 @@ TEST_F(LuaHttpFilterTest, HttpCallImmediateResponse) { EXPECT_CALL(cluster_manager_, get("cluster")); EXPECT_CALL(cluster_manager_, httpAsyncClientForCluster("cluster")); EXPECT_CALL(cluster_manager_.async_client_, send_(_, _, _)) - .WillOnce(Invoke([&](MessagePtr& message, AsyncClient::Callbacks& cb, - const Optional&) -> AsyncClient::Request* { - EXPECT_EQ((TestHeaderMapImpl{{":path", "/"}, {":method", "GET"}, {":authority", "foo"}}), - message->headers()); - callbacks = &cb; - return &request; - })); + .WillOnce( + Invoke([&](MessagePtr& message, AsyncClient::Callbacks& cb, + const absl::optional&) -> AsyncClient::Request* { + EXPECT_EQ( + (TestHeaderMapImpl{{":path", "/"}, {":method", "GET"}, {":authority", "foo"}}), + message->headers()); + callbacks = &cb; + return &request; + })); EXPECT_EQ(FilterHeadersStatus::StopIteration, filter_->decodeHeaders(request_headers, false)); @@ -966,11 +974,12 @@ TEST_F(LuaHttpFilterTest, HttpCallErrorAfterResumeSuccess) { EXPECT_CALL(cluster_manager_, get("cluster")); EXPECT_CALL(cluster_manager_, httpAsyncClientForCluster("cluster")); EXPECT_CALL(cluster_manager_.async_client_, send_(_, _, _)) - .WillOnce(Invoke([&](MessagePtr&, AsyncClient::Callbacks& cb, - const Optional&) -> AsyncClient::Request* { - callbacks = &cb; - return &request; - })); + .WillOnce( + Invoke([&](MessagePtr&, AsyncClient::Callbacks& cb, + const absl::optional&) -> AsyncClient::Request* { + callbacks = &cb; + return &request; + })); EXPECT_EQ(FilterHeadersStatus::StopIteration, filter_->decodeHeaders(request_headers, true)); @@ -1014,11 +1023,12 @@ TEST_F(LuaHttpFilterTest, HttpCallFailure) { EXPECT_CALL(cluster_manager_, get("cluster")); EXPECT_CALL(cluster_manager_, httpAsyncClientForCluster("cluster")); EXPECT_CALL(cluster_manager_.async_client_, send_(_, _, _)) - .WillOnce(Invoke([&](MessagePtr&, AsyncClient::Callbacks& cb, - const Optional&) -> AsyncClient::Request* { - callbacks = &cb; - return &request; - })); + .WillOnce( + Invoke([&](MessagePtr&, AsyncClient::Callbacks& cb, + const absl::optional&) -> AsyncClient::Request* { + callbacks = &cb; + return &request; + })); EXPECT_EQ(FilterHeadersStatus::StopIteration, filter_->decodeHeaders(request_headers, true)); EXPECT_CALL(*filter_, scriptLog(spdlog::level::trace, StrEq(":status 503"))); @@ -1054,11 +1064,12 @@ TEST_F(LuaHttpFilterTest, HttpCallReset) { EXPECT_CALL(cluster_manager_, get("cluster")); EXPECT_CALL(cluster_manager_, httpAsyncClientForCluster("cluster")); EXPECT_CALL(cluster_manager_.async_client_, send_(_, _, _)) - .WillOnce(Invoke([&](MessagePtr&, AsyncClient::Callbacks& cb, - const Optional&) -> AsyncClient::Request* { - callbacks = &cb; - return &request; - })); + .WillOnce( + Invoke([&](MessagePtr&, AsyncClient::Callbacks& cb, + const absl::optional&) -> AsyncClient::Request* { + callbacks = &cb; + return &request; + })); EXPECT_EQ(FilterHeadersStatus::StopIteration, filter_->decodeHeaders(request_headers, true)); @@ -1095,11 +1106,12 @@ TEST_F(LuaHttpFilterTest, HttpCallImmediateFailure) { EXPECT_CALL(cluster_manager_, get("cluster")); EXPECT_CALL(cluster_manager_, httpAsyncClientForCluster("cluster")); EXPECT_CALL(cluster_manager_.async_client_, send_(_, _, _)) - .WillOnce(Invoke([&](MessagePtr&, AsyncClient::Callbacks& cb, - const Optional&) -> AsyncClient::Request* { - cb.onFailure(AsyncClient::FailureReason::Reset); - return nullptr; - })); + .WillOnce( + Invoke([&](MessagePtr&, AsyncClient::Callbacks& cb, + const absl::optional&) -> AsyncClient::Request* { + cb.onFailure(AsyncClient::FailureReason::Reset); + return nullptr; + })); EXPECT_CALL(*filter_, scriptLog(spdlog::level::trace, StrEq(":status 503"))); EXPECT_CALL(*filter_, scriptLog(spdlog::level::trace, StrEq("upstream failure"))); diff --git a/test/common/http/filter/squash_filter_test.cc b/test/common/http/filter/squash_filter_test.cc index 7bf6c0d95652..9555a81bec1d 100644 --- a/test/common/http/filter/squash_filter_test.cc +++ b/test/common/http/filter/squash_filter_test.cc @@ -217,7 +217,7 @@ class SquashFilterTest : public testing::Test { void expectAsyncClientSend() { EXPECT_CALL(cm_.async_client_, send_(_, _, _)) .WillOnce(Invoke([&](Envoy::Http::MessagePtr&, Envoy::Http::AsyncClient::Callbacks& cb, - const Envoy::Optional&) + const absl::optional&) -> Envoy::Http::AsyncClient::Request* { callbacks_.push_back(&cb); return &request_; @@ -268,7 +268,7 @@ TEST_F(SquashFilterTest, DecodeHeaderContinuesOnClientFail) { EXPECT_CALL(cm_.async_client_, send_(_, _, _)) .WillOnce(Invoke([&](Envoy::Http::MessagePtr&, Envoy::Http::AsyncClient::Callbacks& callbacks, - const Envoy::Optional&) + const absl::optional&) -> Envoy::Http::AsyncClient::Request* { callbacks.onFailure(Envoy::Http::AsyncClient::FailureReason::Reset); return nullptr; @@ -433,7 +433,7 @@ TEST_F(SquashFilterTest, TimerExpiresInline) { EXPECT_CALL(cm_.async_client_, send_(_, _, _)) .WillOnce(Invoke([&](Envoy::Http::MessagePtr&, Envoy::Http::AsyncClient::Callbacks&, - const Envoy::Optional&) + const absl::optional&) -> Envoy::Http::AsyncClient::Request* { return &request_; })); EXPECT_CALL(request_, cancel()); diff --git a/test/common/ratelimit/ratelimit_impl_test.cc b/test/common/ratelimit/ratelimit_impl_test.cc index 8ce5f00e6cdf..a9ae6764c07e 100644 --- a/test/common/ratelimit/ratelimit_impl_test.cc +++ b/test/common/ratelimit/ratelimit_impl_test.cc @@ -33,7 +33,7 @@ class RateLimitGrpcClientTest : public testing::Test { public: RateLimitGrpcClientTest() : async_client_(new Grpc::MockAsyncClient()), - client_(Grpc::AsyncClientPtr{async_client_}, Optional()) {} + client_(Grpc::AsyncClientPtr{async_client_}, absl::optional()) {} Grpc::MockAsyncClient* async_client_; Grpc::MockAsyncRequest async_request_; @@ -50,14 +50,15 @@ TEST_F(RateLimitGrpcClientTest, Basic) { Http::HeaderMapImpl headers; GrpcClientImpl::createRequest(request, "foo", {{{{"foo", "bar"}}}}); EXPECT_CALL(*async_client_, send(_, ProtoEq(request), Ref(client_), _, _)) - .WillOnce(Invoke([this](const Protobuf::MethodDescriptor& service_method, - const Protobuf::Message&, Grpc::AsyncRequestCallbacks&, - Tracing::Span&, - const Optional&) -> Grpc::AsyncRequest* { - EXPECT_EQ("pb.lyft.ratelimit.RateLimitService", service_method.service()->full_name()); - EXPECT_EQ("ShouldRateLimit", service_method.name()); - return &async_request_; - })); + .WillOnce( + Invoke([this](const Protobuf::MethodDescriptor& service_method, + const Protobuf::Message&, Grpc::AsyncRequestCallbacks&, Tracing::Span&, + const absl::optional&) -> Grpc::AsyncRequest* { + EXPECT_EQ("pb.lyft.ratelimit.RateLimitService", + service_method.service()->full_name()); + EXPECT_EQ("ShouldRateLimit", service_method.name()); + return &async_request_; + })); client_.limit(request_callbacks_, "foo", {{{{"foo", "bar"}}}}, Tracing::NullSpan::instance()); @@ -130,7 +131,7 @@ TEST(RateLimitGrpcFactoryTest, Create) { return std::make_unique>(); })); GrpcFactoryImpl factory(config, async_client_manager, scope); - factory.create(Optional()); + factory.create(absl::optional()); } // TODO(htuch): cluster_name is deprecated, remove after 1.6.0. @@ -147,12 +148,12 @@ TEST(RateLimitGrpcFactoryTest, CreateLegacy) { return std::make_unique>(); })); GrpcFactoryImpl factory(config, async_client_manager, scope); - factory.create(Optional()); + factory.create(absl::optional()); } TEST(RateLimitNullFactoryTest, Basic) { NullFactoryImpl factory; - ClientPtr client = factory.create(Optional()); + ClientPtr client = factory.create(absl::optional()); MockRequestCallbacks request_callbacks; EXPECT_CALL(request_callbacks, complete(LimitStatus::OK)); client->limit(request_callbacks, "foo", {{{{"foo", "bar"}}}}, Tracing::NullSpan::instance()); diff --git a/test/common/request_info/request_info_impl_test.cc b/test/common/request_info/request_info_impl_test.cc index 8c1427a6732d..b246db2af114 100644 --- a/test/common/request_info/request_info_impl_test.cc +++ b/test/common/request_info/request_info_impl_test.cc @@ -18,8 +18,8 @@ namespace RequestInfo { namespace { std::chrono::nanoseconds checkDuration(std::chrono::nanoseconds last, - Optional timing) { - EXPECT_TRUE(timing.valid()); + absl::optional timing) { + EXPECT_TRUE(timing); EXPECT_LE(last, timing.value()); return timing.value(); } @@ -34,36 +34,36 @@ TEST(RequestInfoImplTest, TimingTest) { EXPECT_LE(pre_start, start) << "Start time was lower than expected"; EXPECT_GE(post_start, start) << "Start time was higher than expected"; - EXPECT_FALSE(info.lastDownstreamRxByteReceived().valid()); + EXPECT_FALSE(info.lastDownstreamRxByteReceived()); info.onLastDownstreamRxByteReceived(); std::chrono::nanoseconds dur = checkDuration(std::chrono::nanoseconds{0}, info.lastDownstreamRxByteReceived()); - EXPECT_FALSE(info.firstUpstreamTxByteSent().valid()); + EXPECT_FALSE(info.firstUpstreamTxByteSent()); info.onFirstUpstreamTxByteSent(); dur = checkDuration(dur, info.firstUpstreamTxByteSent()); - EXPECT_FALSE(info.lastUpstreamTxByteSent().valid()); + EXPECT_FALSE(info.lastUpstreamTxByteSent()); info.onLastUpstreamTxByteSent(); dur = checkDuration(dur, info.lastUpstreamTxByteSent()); - EXPECT_FALSE(info.firstUpstreamRxByteReceived().valid()); + EXPECT_FALSE(info.firstUpstreamRxByteReceived()); info.onFirstUpstreamRxByteReceived(); dur = checkDuration(dur, info.firstUpstreamRxByteReceived()); - EXPECT_FALSE(info.lastUpstreamRxByteReceived().valid()); + EXPECT_FALSE(info.lastUpstreamRxByteReceived()); info.onLastUpstreamRxByteReceived(); dur = checkDuration(dur, info.lastUpstreamRxByteReceived()); - EXPECT_FALSE(info.firstDownstreamTxByteSent().valid()); + EXPECT_FALSE(info.firstDownstreamTxByteSent()); info.onFirstDownstreamTxByteSent(); dur = checkDuration(dur, info.firstDownstreamTxByteSent()); - EXPECT_FALSE(info.lastDownstreamTxByteSent().valid()); + EXPECT_FALSE(info.lastDownstreamTxByteSent()); info.onLastDownstreamTxByteSent(); dur = checkDuration(dur, info.lastDownstreamTxByteSent()); - EXPECT_FALSE(info.requestComplete().valid()); + EXPECT_FALSE(info.requestComplete()); info.onRequestComplete(); dur = checkDuration(dur, info.requestComplete()); } @@ -113,9 +113,9 @@ TEST(RequestInfoImplTest, MiscSettersAndGetters) { request_info.protocol(Http::Protocol::Http10); EXPECT_EQ(Http::Protocol::Http10, request_info.protocol().value()); - EXPECT_FALSE(request_info.responseCode().valid()); + EXPECT_FALSE(request_info.responseCode()); request_info.response_code_ = 200; - ASSERT_TRUE(request_info.responseCode().valid()); + ASSERT_TRUE(request_info.responseCode()); EXPECT_EQ(200, request_info.responseCode().value()); EXPECT_EQ(nullptr, request_info.upstreamHost()); diff --git a/test/common/router/BUILD b/test/common/router/BUILD index 9edf264a6286..d40edc35ae64 100644 --- a/test/common/router/BUILD +++ b/test/common/router/BUILD @@ -100,8 +100,8 @@ envoy_cc_test( envoy_cc_test( name = "router_upstream_log_test", srcs = ["router_upstream_log_test.cc"], + external_deps = ["abseil_optional"], deps = [ - "//include/envoy/common:optional", "//source/common/buffer:buffer_lib", "//source/common/config:filter_json_lib", "//source/common/network:utility_lib", diff --git a/test/common/router/config_impl_test.cc b/test/common/router/config_impl_test.cc index e87de78dd32f..a3179791f9b4 100644 --- a/test/common/router/config_impl_test.cc +++ b/test/common/router/config_impl_test.cc @@ -1289,15 +1289,13 @@ TEST_F(RouterMatcherHashPolicyTest, HashHeaders) { { Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET"); Router::RouteConstSharedPtr route = config().route(headers, 0); - EXPECT_FALSE( - route->routeEntry()->hashPolicy()->generateHash("", headers, add_cookie_nop_).valid()); + EXPECT_FALSE(route->routeEntry()->hashPolicy()->generateHash("", headers, add_cookie_nop_)); } { Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET"); headers.addCopy("foo_header", "bar"); Router::RouteConstSharedPtr route = config().route(headers, 0); - EXPECT_TRUE( - route->routeEntry()->hashPolicy()->generateHash("", headers, add_cookie_nop_).valid()); + EXPECT_TRUE(route->routeEntry()->hashPolicy()->generateHash("", headers, add_cookie_nop_)); } { Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/bar", "GET"); @@ -1318,24 +1316,21 @@ TEST_F(RouterMatcherCookieHashPolicyTest, NoTtl) { // With no cookie, no hash is generated. Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET"); Router::RouteConstSharedPtr route = config().route(headers, 0); - EXPECT_FALSE( - route->routeEntry()->hashPolicy()->generateHash("", headers, add_cookie_nop_).valid()); + EXPECT_FALSE(route->routeEntry()->hashPolicy()->generateHash("", headers, add_cookie_nop_)); } { // With no matching cookie, no hash is generated. Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET"); headers.addCopy("Cookie", "choco=late; su=gar"); Router::RouteConstSharedPtr route = config().route(headers, 0); - EXPECT_FALSE( - route->routeEntry()->hashPolicy()->generateHash("", headers, add_cookie_nop_).valid()); + EXPECT_FALSE(route->routeEntry()->hashPolicy()->generateHash("", headers, add_cookie_nop_)); } { // Matching cookie produces a valid hash. Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET"); headers.addCopy("Cookie", "choco=late; hash=brown"); Router::RouteConstSharedPtr route = config().route(headers, 0); - EXPECT_TRUE( - route->routeEntry()->hashPolicy()->generateHash("", headers, add_cookie_nop_).valid()); + EXPECT_TRUE(route->routeEntry()->hashPolicy()->generateHash("", headers, add_cookie_nop_)); } { // The hash policy is per-route. @@ -1376,20 +1371,20 @@ TEST_F(RouterMatcherCookieHashPolicyTest, TtlSet) { Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET"); Router::RouteConstSharedPtr route = config().route(headers, 0); EXPECT_CALL(mock_cookie_cb, Call("hash", 42)); - EXPECT_TRUE(route->routeEntry()->hashPolicy()->generateHash("", headers, add_cookie).valid()); + EXPECT_TRUE(route->routeEntry()->hashPolicy()->generateHash("", headers, add_cookie)); } { Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET"); headers.addCopy("Cookie", "choco=late; su=gar"); Router::RouteConstSharedPtr route = config().route(headers, 0); EXPECT_CALL(mock_cookie_cb, Call("hash", 42)); - EXPECT_TRUE(route->routeEntry()->hashPolicy()->generateHash("", headers, add_cookie).valid()); + EXPECT_TRUE(route->routeEntry()->hashPolicy()->generateHash("", headers, add_cookie)); } { Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET"); headers.addCopy("Cookie", "choco=late; hash=brown"); Router::RouteConstSharedPtr route = config().route(headers, 0); - EXPECT_TRUE(route->routeEntry()->hashPolicy()->generateHash("", headers, add_cookie).valid()); + EXPECT_TRUE(route->routeEntry()->hashPolicy()->generateHash("", headers, add_cookie)); } { uint64_t hash_1, hash_2; @@ -1419,16 +1414,13 @@ TEST_F(RouterMatcherHashPolicyTest, HashIp) { { Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET"); Router::RouteConstSharedPtr route = config().route(headers, 0); - EXPECT_FALSE( - route->routeEntry()->hashPolicy()->generateHash("", headers, add_cookie_nop_).valid()); + EXPECT_FALSE(route->routeEntry()->hashPolicy()->generateHash("", headers, add_cookie_nop_)); } { Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET"); Router::RouteConstSharedPtr route = config().route(headers, 0); - EXPECT_TRUE(route->routeEntry() - ->hashPolicy() - ->generateHash("1.2.3.4", headers, add_cookie_nop_) - .valid()); + EXPECT_TRUE( + route->routeEntry()->hashPolicy()->generateHash("1.2.3.4", headers, add_cookie_nop_)); } { Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET"); @@ -1469,8 +1461,7 @@ TEST_F(RouterMatcherHashPolicyTest, HashMultiple) { { Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET"); Router::RouteConstSharedPtr route = config().route(headers, 0); - EXPECT_FALSE( - route->routeEntry()->hashPolicy()->generateHash("", headers, add_cookie_nop_).valid()); + EXPECT_FALSE(route->routeEntry()->hashPolicy()->generateHash("", headers, add_cookie_nop_)); } { Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET"); diff --git a/test/common/router/header_formatter_test.cc b/test/common/router/header_formatter_test.cc index c4b36857c5be..7b85846801b6 100644 --- a/test/common/router/header_formatter_test.cc +++ b/test/common/router/header_formatter_test.cc @@ -75,7 +75,7 @@ TEST_F(RequestInfoHeaderFormatterTest, TestFormatWithDownstreamLocalAddressWitho TEST_F(RequestInfoHeaderFormatterTest, TestFormatWithProtocolVariable) { NiceMock request_info; - Optional protocol = Envoy::Http::Protocol::Http11; + absl::optional protocol = Envoy::Http::Protocol::Http11; ON_CALL(request_info, protocol()).WillByDefault(ReturnPointee(&protocol)); testFormatting(request_info, "PROTOCOL", "HTTP/1.1"); @@ -247,8 +247,8 @@ TEST_F(RequestInfoHeaderFormatterTest, WrongFormatOnUpstreamMetadataVariable) { TEST(HeaderParserTest, TestParseInternal) { struct TestCase { std::string input_; - Optional expected_output_; - Optional expected_exception_; + absl::optional expected_output_; + absl::optional expected_exception_; }; static const TestCase test_cases[] = { @@ -388,7 +388,7 @@ TEST(HeaderParserTest, TestParseInternal) { }; NiceMock request_info; - Optional protocol = Envoy::Http::Protocol::Http11; + absl::optional protocol = Envoy::Http::Protocol::Http11; ON_CALL(request_info, protocol()).WillByDefault(ReturnPointee(&protocol)); std::shared_ptr> host( @@ -410,8 +410,8 @@ TEST(HeaderParserTest, TestParseInternal) { header->mutable_header()->set_key("x-header"); header->mutable_header()->set_value(test_case.input_); - if (test_case.expected_exception_.valid()) { - EXPECT_FALSE(test_case.expected_output_.valid()); + if (test_case.expected_exception_) { + EXPECT_FALSE(test_case.expected_output_); EXPECT_THROW_WITH_MESSAGE(HeaderParser::configure(to_add), EnvoyException, test_case.expected_exception_.value()); continue; @@ -425,7 +425,7 @@ TEST(HeaderParserTest, TestParseInternal) { std::string descriptor = fmt::format("for test case input: {}", test_case.input_); EXPECT_TRUE(headerMap.has("x-header")) << descriptor; - EXPECT_TRUE(test_case.expected_output_.valid()) << descriptor; + EXPECT_TRUE(test_case.expected_output_) << descriptor; EXPECT_EQ(test_case.expected_output_.value(), headerMap.get_("x-header")) << descriptor; } } @@ -538,7 +538,7 @@ match: { prefix: "/new_endpoint" } HeaderParser::configure(parseRouteFromV2Yaml(yaml).route().request_headers_to_add()); Http::TestHeaderMapImpl headerMap{{":method", "POST"}}; NiceMock request_info; - Optional protocol = Envoy::Http::Protocol::Http11; + absl::optional protocol = Envoy::Http::Protocol::Http11; ON_CALL(request_info, protocol()).WillByDefault(ReturnPointee(&protocol)); std::shared_ptr> host( diff --git a/test/common/router/rds_impl_test.cc b/test/common/router/rds_impl_test.cc index bb3bc482a16a..717b55f2a5a6 100644 --- a/test/common/router/rds_impl_test.cc +++ b/test/common/router/rds_impl_test.cc @@ -93,9 +93,9 @@ class RdsImplTest : public testing::Test { void expectRequest() { EXPECT_CALL(cm_, httpAsyncClientForCluster("foo_cluster")); EXPECT_CALL(cm_.async_client_, send_(_, _, _)) - .WillOnce( - Invoke([&](Http::MessagePtr& request, Http::AsyncClient::Callbacks& callbacks, - const Optional&) -> Http::AsyncClient::Request* { + .WillOnce(Invoke( + [&](Http::MessagePtr& request, Http::AsyncClient::Callbacks& callbacks, + const absl::optional&) -> Http::AsyncClient::Request* { EXPECT_EQ((Http::TestHeaderMapImpl{ {":method", "GET"}, {":path", "/v1/routes/foo_route_config/cluster_name/node_name"}, diff --git a/test/common/router/retry_state_impl_test.cc b/test/common/router/retry_state_impl_test.cc index 7ecda95b3803..8d1fa8f4dc77 100644 --- a/test/common/router/retry_state_impl_test.cc +++ b/test/common/router/retry_state_impl_test.cc @@ -47,12 +47,12 @@ class RouterRetryStateImplTest : public testing::Test { ReadyWatcher callback_ready_; RetryState::DoRetryCallback callback_; - const Optional no_reset_; - const Optional remote_reset_{Http::StreamResetReason::RemoteReset}; - const Optional remote_refused_stream_reset_{ + const absl::optional no_reset_; + const absl::optional remote_reset_{Http::StreamResetReason::RemoteReset}; + const absl::optional remote_refused_stream_reset_{ Http::StreamResetReason::RemoteRefusedStreamReset}; - const Optional overflow_reset_{Http::StreamResetReason::Overflow}; - const Optional connect_failure_{ + const absl::optional overflow_reset_{Http::StreamResetReason::Overflow}; + const absl::optional connect_failure_{ Http::StreamResetReason::ConnectionFailure}; }; diff --git a/test/common/router/router_test.cc b/test/common/router/router_test.cc index 5b8757b8ebef..9bf9d8bfdb77 100644 --- a/test/common/router/router_test.cc +++ b/test/common/router/router_test.cc @@ -216,7 +216,7 @@ TEST_F(RouterTest, Http2Upstream) { } TEST_F(RouterTest, UseDownstreamProtocol1) { - Optional downstream_protocol{Http::Protocol::Http11}; + absl::optional downstream_protocol{Http::Protocol::Http11}; EXPECT_CALL(*cm_.thread_local_cluster_.cluster_.info_, features()) .WillOnce(Return(Upstream::ClusterInfo::Features::USE_DOWNSTREAM_PROTOCOL)); EXPECT_CALL(callbacks_.request_info_, protocol()).WillOnce(ReturnPointee(&downstream_protocol)); @@ -236,7 +236,7 @@ TEST_F(RouterTest, UseDownstreamProtocol1) { } TEST_F(RouterTest, UseDownstreamProtocol2) { - Optional downstream_protocol{Http::Protocol::Http2}; + absl::optional downstream_protocol{Http::Protocol::Http2}; EXPECT_CALL(*cm_.thread_local_cluster_.cluster_.info_, features()) .WillOnce(Return(Upstream::ClusterInfo::Features::USE_DOWNSTREAM_PROTOCOL)); EXPECT_CALL(callbacks_.request_info_, protocol()).WillOnce(ReturnPointee(&downstream_protocol)); @@ -259,7 +259,7 @@ TEST_F(RouterTest, HashPolicy) { ON_CALL(callbacks_.route_->route_entry_, hashPolicy()) .WillByDefault(Return(&callbacks_.route_->route_entry_.hash_policy_)); EXPECT_CALL(callbacks_.route_->route_entry_.hash_policy_, generateHash(_, _, _)) - .WillOnce(Return(Optional(10))); + .WillOnce(Return(absl::optional(10))); EXPECT_CALL(cm_, httpConnPoolForCluster(_, _, _, _)) .WillOnce( Invoke([&](const std::string&, Upstream::ResourcePriority, Http::Protocol, @@ -284,12 +284,12 @@ TEST_F(RouterTest, HashPolicyNoHash) { ON_CALL(callbacks_.route_->route_entry_, hashPolicy()) .WillByDefault(Return(&callbacks_.route_->route_entry_.hash_policy_)); EXPECT_CALL(callbacks_.route_->route_entry_.hash_policy_, generateHash(_, _, _)) - .WillOnce(Return(Optional())); + .WillOnce(Return(absl::optional())); EXPECT_CALL(cm_, httpConnPoolForCluster(_, _, _, &router_)) .WillOnce( Invoke([&](const std::string&, Upstream::ResourcePriority, Http::Protocol, Upstream::LoadBalancerContext* context) -> Http::ConnectionPool::Instance* { - EXPECT_EQ(false, context->computeHashKey().valid()); + EXPECT_FALSE(context->computeHashKey()); return &cm_.conn_pool_; })); EXPECT_CALL(cm_.conn_pool_, newStream(_, _)).WillOnce(Return(&cancellable_)); @@ -332,7 +332,7 @@ TEST_F(RouterTest, AddCookie) { .WillOnce(Invoke([&](const std::string&, const Http::HeaderMap&, const HashPolicy::AddCookieCallback add_cookie) { cookie_value = add_cookie("foo", std::chrono::seconds(1337)); - return Optional(10); + return absl::optional(10); })); EXPECT_CALL(callbacks_, encodeHeaders_(_, _)) @@ -379,7 +379,7 @@ TEST_F(RouterTest, AddCookieNoDuplicate) { const HashPolicy::AddCookieCallback add_cookie) { // this should be ignored add_cookie("foo", std::chrono::seconds(1337)); - return Optional(10); + return absl::optional(10); })); EXPECT_CALL(callbacks_, encodeHeaders_(_, _)) @@ -427,7 +427,7 @@ TEST_F(RouterTest, AddMultipleCookies) { const HashPolicy::AddCookieCallback add_cookie) { choco_c = add_cookie("choco", std::chrono::seconds(15)); foo_c = add_cookie("foo", std::chrono::seconds(1337)); - return Optional(10); + return absl::optional(10); })); EXPECT_CALL(callbacks_, encodeHeaders_(_, _)) diff --git a/test/common/router/router_upstream_log_test.cc b/test/common/router/router_upstream_log_test.cc index dae08bd00715..776c53834f49 100644 --- a/test/common/router/router_upstream_log_test.cc +++ b/test/common/router/router_upstream_log_test.cc @@ -1,5 +1,3 @@ -#include "envoy/common/optional.h" - #include "common/config/filter_json.h" #include "common/router/router.h" #include "common/upstream/upstream_impl.h" @@ -16,6 +14,7 @@ #include "test/mocks/upstream/mocks.h" #include "test/test_common/utility.h" +#include "absl/types/optional.h" #include "gmock/gmock.h" #include "gtest/gtest.h" @@ -29,7 +28,7 @@ namespace Envoy { namespace Router { namespace { -Optional testUpstreamLog() { +absl::optional testUpstreamLog() { // Custom format without timestamps or durations. const std::string json_string = R"EOF( { @@ -43,7 +42,7 @@ Optional testUpstreamLog() { envoy::config::filter::accesslog::v2::AccessLog upstream_log; Envoy::Config::FilterJson::translateAccessLog(*json_object_ptr, upstream_log); - return Optional(upstream_log); + return absl::optional(upstream_log); } } // namespace @@ -73,10 +72,10 @@ class RouterUpstreamLogTest : public testing::Test { public: RouterUpstreamLogTest() {} - void init(Optional upstream_log) { + void init(absl::optional upstream_log) { envoy::config::filter::http::router::v2::Router router_proto; - if (upstream_log.valid()) { + if (upstream_log) { ON_CALL(*context_.access_log_manager_.file_, write(_)) .WillByDefault(Invoke([&](const std::string& data) { output_.push_back(data); })); diff --git a/test/common/router/shadow_writer_impl_test.cc b/test/common/router/shadow_writer_impl_test.cc index 1d59aaf42517..1f1b9c480cce 100644 --- a/test/common/router/shadow_writer_impl_test.cc +++ b/test/common/router/shadow_writer_impl_test.cc @@ -27,10 +27,10 @@ void expectShadowWriter(absl::string_view host, absl::string_view shadowed_host) Http::MockAsyncClientRequest request(&cm.async_client_); Http::AsyncClient::Callbacks* callback; EXPECT_CALL(cm.async_client_, - send_(_, _, Optional(std::chrono::milliseconds(5)))) - .WillOnce( - Invoke([&](Http::MessagePtr& inner_message, Http::AsyncClient::Callbacks& callbacks, - const Optional&) -> Http::AsyncClient::Request* { + send_(_, _, absl::optional(std::chrono::milliseconds(5)))) + .WillOnce(Invoke( + [&](Http::MessagePtr& inner_message, Http::AsyncClient::Callbacks& callbacks, + const absl::optional&) -> Http::AsyncClient::Request* { EXPECT_EQ(message, inner_message); EXPECT_EQ(shadowed_host, message->headers().Host()->value().c_str()); callback = &callbacks; @@ -46,10 +46,10 @@ void expectShadowWriter(absl::string_view host, absl::string_view shadowed_host) message->headers().insertHost().value(std::string(host)); EXPECT_CALL(cm, httpAsyncClientForCluster("bar")).WillOnce(ReturnRef(cm.async_client_)); EXPECT_CALL(cm.async_client_, - send_(_, _, Optional(std::chrono::milliseconds(10)))) - .WillOnce( - Invoke([&](Http::MessagePtr& inner_message, Http::AsyncClient::Callbacks& callbacks, - const Optional&) -> Http::AsyncClient::Request* { + send_(_, _, absl::optional(std::chrono::milliseconds(10)))) + .WillOnce(Invoke( + [&](Http::MessagePtr& inner_message, Http::AsyncClient::Callbacks& callbacks, + const absl::optional&) -> Http::AsyncClient::Request* { EXPECT_EQ(message, inner_message); EXPECT_EQ(shadowed_host, message->headers().Host()->value().c_str()); callback = &callbacks; diff --git a/test/common/runtime/runtime_impl_test.cc b/test/common/runtime/runtime_impl_test.cc index 8c875d777fd6..c2bce70d267e 100644 --- a/test/common/runtime/runtime_impl_test.cc +++ b/test/common/runtime/runtime_impl_test.cc @@ -143,17 +143,17 @@ TEST_F(RuntimeImplTest, GetAll) { auto entry = values.find("file1"); EXPECT_FALSE(entry == values.end()); EXPECT_EQ("hello override", entry->second.string_value_); - EXPECT_FALSE(entry->second.uint_value_.valid()); + EXPECT_FALSE(entry->second.uint_value_); entry = values.find("file2"); EXPECT_FALSE(entry == values.end()); EXPECT_EQ("world", entry->second.string_value_); - EXPECT_FALSE(entry->second.uint_value_.valid()); + EXPECT_FALSE(entry->second.uint_value_); entry = values.find("file3"); EXPECT_FALSE(entry == values.end()); EXPECT_EQ("2", entry->second.string_value_); - EXPECT_TRUE(entry->second.uint_value_.valid()); + EXPECT_TRUE(entry->second.uint_value_); EXPECT_EQ(2UL, entry->second.uint_value_.value()); entry = values.find("invalid"); diff --git a/test/common/tracing/http_tracer_impl_test.cc b/test/common/tracing/http_tracer_impl_test.cc index ea7e6afcf560..9887e86f35ee 100644 --- a/test/common/tracing/http_tracer_impl_test.cc +++ b/test/common/tracing/http_tracer_impl_test.cc @@ -247,11 +247,11 @@ TEST(HttpConnManFinalizerImpl, OriginalAndLongPath) { {"x-forwarded-proto", "http"}}; NiceMock request_info; - Optional protocol = Http::Protocol::Http2; + absl::optional protocol = Http::Protocol::Http2; EXPECT_CALL(request_info, bytesReceived()).WillOnce(Return(10)); EXPECT_CALL(request_info, bytesSent()).WillOnce(Return(11)); EXPECT_CALL(request_info, protocol()).WillOnce(ReturnPointee(&protocol)); - Optional response_code; + absl::optional response_code; EXPECT_CALL(request_info, responseCode()).WillRepeatedly(ReturnPointee(&response_code)); EXPECT_CALL(*span, setTag(_, _)).Times(testing::AnyNumber()); @@ -269,7 +269,7 @@ TEST(HttpConnManFinalizerImpl, NullRequestHeaders) { EXPECT_CALL(request_info, bytesReceived()).WillOnce(Return(10)); EXPECT_CALL(request_info, bytesSent()).WillOnce(Return(11)); - Optional response_code; + absl::optional response_code; EXPECT_CALL(request_info, responseCode()).WillRepeatedly(ReturnPointee(&response_code)); EXPECT_CALL(request_info, upstreamHost()).WillOnce(Return(nullptr)); @@ -291,7 +291,7 @@ TEST(HttpConnManFinalizerImpl, UpstreamClusterTagSet) { EXPECT_CALL(request_info, bytesReceived()).WillOnce(Return(10)); EXPECT_CALL(request_info, bytesSent()).WillOnce(Return(11)); - Optional response_code; + absl::optional response_code; EXPECT_CALL(request_info, responseCode()).WillRepeatedly(ReturnPointee(&response_code)); EXPECT_CALL(request_info, upstreamHost()).Times(2); @@ -315,7 +315,7 @@ TEST(HttpConnManFinalizerImpl, SpanOptionalHeaders) { {"x-forwarded-proto", "https"}}; NiceMock request_info; - Optional protocol = Http::Protocol::Http10; + absl::optional protocol = Http::Protocol::Http10; EXPECT_CALL(request_info, bytesReceived()).WillOnce(Return(10)); EXPECT_CALL(request_info, protocol()).WillOnce(ReturnPointee(&protocol)); const std::string service_node = "i-453"; @@ -329,7 +329,7 @@ TEST(HttpConnManFinalizerImpl, SpanOptionalHeaders) { EXPECT_CALL(*span, setTag(Tracing::Tags::get().DOWNSTREAM_CLUSTER, "-")); EXPECT_CALL(*span, setTag(Tracing::Tags::get().REQUEST_SIZE, "10")); - Optional response_code; + absl::optional response_code; EXPECT_CALL(request_info, responseCode()).WillRepeatedly(ReturnPointee(&response_code)); EXPECT_CALL(request_info, bytesSent()).WillOnce(Return(100)); EXPECT_CALL(request_info, upstreamHost()).WillOnce(Return(nullptr)); @@ -357,7 +357,7 @@ TEST(HttpConnManFinalizerImpl, SpanPopulatedFailureResponse) { request_headers.insertEnvoyDownstreamServiceCluster().value(std::string("downstream_cluster")); request_headers.insertClientTraceId().value(std::string("client_trace_id")); - Optional protocol = Http::Protocol::Http10; + absl::optional protocol = Http::Protocol::Http10; EXPECT_CALL(request_info, protocol()).WillOnce(ReturnPointee(&protocol)); EXPECT_CALL(request_info, bytesReceived()).WillOnce(Return(10)); const std::string service_node = "i-453"; @@ -384,7 +384,7 @@ TEST(HttpConnManFinalizerImpl, SpanPopulatedFailureResponse) { EXPECT_CALL(*span, setTag("cc", "c")); EXPECT_CALL(config, requestHeadersForTags()); - Optional response_code(503); + absl::optional response_code(503); EXPECT_CALL(request_info, responseCode()).WillRepeatedly(ReturnPointee(&response_code)); EXPECT_CALL(request_info, bytesSent()).WillOnce(Return(100)); ON_CALL(request_info, getResponseFlag(RequestInfo::ResponseFlag::UpstreamRequestTimeout)) diff --git a/test/common/tracing/lightstep_tracer_impl_test.cc b/test/common/tracing/lightstep_tracer_impl_test.cc index 67c36149d19a..21fc576f78f0 100644 --- a/test/common/tracing/lightstep_tracer_impl_test.cc +++ b/test/common/tracing/lightstep_tracer_impl_test.cc @@ -162,12 +162,12 @@ TEST_F(LightStepDriverTest, FlushSeveralSpans) { Http::MockAsyncClientRequest request(&cm_.async_client_); Http::AsyncClient::Callbacks* callback; - const Optional timeout(std::chrono::seconds(5)); + const absl::optional timeout(std::chrono::seconds(5)); EXPECT_CALL(cm_.async_client_, send_(_, _, timeout)) - .WillOnce( - Invoke([&](Http::MessagePtr& message, Http::AsyncClient::Callbacks& callbacks, - const Optional&) -> Http::AsyncClient::Request* { + .WillOnce(Invoke( + [&](Http::MessagePtr& message, Http::AsyncClient::Callbacks& callbacks, + const absl::optional&) -> Http::AsyncClient::Request* { callback = &callbacks; EXPECT_STREQ("/lightstep.collector.CollectorService/Report", @@ -220,12 +220,12 @@ TEST_F(LightStepDriverTest, FlushOneFailure) { Http::MockAsyncClientRequest request(&cm_.async_client_); Http::AsyncClient::Callbacks* callback; - const Optional timeout(std::chrono::seconds(5)); + const absl::optional timeout(std::chrono::seconds(5)); EXPECT_CALL(cm_.async_client_, send_(_, _, timeout)) - .WillOnce( - Invoke([&](Http::MessagePtr& message, Http::AsyncClient::Callbacks& callbacks, - const Optional&) -> Http::AsyncClient::Request* { + .WillOnce(Invoke( + [&](Http::MessagePtr& message, Http::AsyncClient::Callbacks& callbacks, + const absl::optional&) -> Http::AsyncClient::Request* { callback = &callbacks; EXPECT_STREQ("/lightstep.collector.CollectorService/Report", @@ -261,12 +261,12 @@ TEST_F(LightStepDriverTest, FlushOneInvalidResponse) { Http::MockAsyncClientRequest request(&cm_.async_client_); Http::AsyncClient::Callbacks* callback; - const Optional timeout(std::chrono::seconds(5)); + const absl::optional timeout(std::chrono::seconds(5)); EXPECT_CALL(cm_.async_client_, send_(_, _, timeout)) - .WillOnce( - Invoke([&](Http::MessagePtr& message, Http::AsyncClient::Callbacks& callbacks, - const Optional&) -> Http::AsyncClient::Request* { + .WillOnce(Invoke( + [&](Http::MessagePtr& message, Http::AsyncClient::Callbacks& callbacks, + const absl::optional&) -> Http::AsyncClient::Request* { callback = &callbacks; EXPECT_STREQ("/lightstep.collector.CollectorService/Report", @@ -306,7 +306,7 @@ TEST_F(LightStepDriverTest, FlushOneInvalidResponse) { TEST_F(LightStepDriverTest, FlushSpansTimer) { setupValidDriver(); - const Optional timeout(std::chrono::seconds(5)); + const absl::optional timeout(std::chrono::seconds(5)); EXPECT_CALL(cm_.async_client_, send_(_, _, timeout)); EXPECT_CALL(runtime_.snapshot_, getInteger("tracing.lightstep.min_flush_spans", 5)) @@ -333,12 +333,12 @@ TEST_F(LightStepDriverTest, FlushOneSpanGrpcFailure) { Http::MockAsyncClientRequest request(&cm_.async_client_); Http::AsyncClient::Callbacks* callback; - const Optional timeout(std::chrono::seconds(5)); + const absl::optional timeout(std::chrono::seconds(5)); EXPECT_CALL(cm_.async_client_, send_(_, _, timeout)) - .WillOnce( - Invoke([&](Http::MessagePtr& message, Http::AsyncClient::Callbacks& callbacks, - const Optional&) -> Http::AsyncClient::Request* { + .WillOnce(Invoke( + [&](Http::MessagePtr& message, Http::AsyncClient::Callbacks& callbacks, + const absl::optional&) -> Http::AsyncClient::Request* { callback = &callbacks; EXPECT_STREQ("/lightstep.collector.CollectorService/Report", @@ -376,12 +376,12 @@ TEST_F(LightStepDriverTest, CancelRequestOnDestruction) { Http::MockAsyncClientRequest request(&cm_.async_client_); Http::AsyncClient::Callbacks* callback; - const Optional timeout(std::chrono::seconds(5)); + const absl::optional timeout(std::chrono::seconds(5)); EXPECT_CALL(cm_.async_client_, send_(_, _, timeout)) - .WillOnce( - Invoke([&](Http::MessagePtr& /*message*/, Http::AsyncClient::Callbacks& callbacks, - const Optional&) -> Http::AsyncClient::Request* { + .WillOnce(Invoke( + [&](Http::MessagePtr& /*message*/, Http::AsyncClient::Callbacks& callbacks, + const absl::optional&) -> Http::AsyncClient::Request* { callback = &callbacks; return &request; diff --git a/test/common/tracing/zipkin/BUILD b/test/common/tracing/zipkin/BUILD index 0cb331f4b9e7..ba27c3e2cc4b 100644 --- a/test/common/tracing/zipkin/BUILD +++ b/test/common/tracing/zipkin/BUILD @@ -18,8 +18,8 @@ envoy_cc_test( "zipkin_core_types_test.cc", "zipkin_tracer_impl_test.cc", ], + external_deps = ["abseil_optional"], deps = [ - "//include/envoy/common:optional", "//include/envoy/common:time_interface", "//include/envoy/runtime:runtime_interface", "//source/common/common:hex_lib", diff --git a/test/common/tracing/zipkin/zipkin_tracer_impl_test.cc b/test/common/tracing/zipkin/zipkin_tracer_impl_test.cc index 216a81abe61a..2008dae93b68 100644 --- a/test/common/tracing/zipkin/zipkin_tracer_impl_test.cc +++ b/test/common/tracing/zipkin/zipkin_tracer_impl_test.cc @@ -133,12 +133,12 @@ TEST_F(ZipkinDriverTest, FlushSeveralSpans) { Http::MockAsyncClientRequest request(&cm_.async_client_); Http::AsyncClient::Callbacks* callback; - const Optional timeout(std::chrono::seconds(5)); + const absl::optional timeout(std::chrono::seconds(5)); EXPECT_CALL(cm_.async_client_, send_(_, _, timeout)) - .WillOnce( - Invoke([&](Http::MessagePtr& message, Http::AsyncClient::Callbacks& callbacks, - const Optional&) -> Http::AsyncClient::Request* { + .WillOnce(Invoke( + [&](Http::MessagePtr& message, Http::AsyncClient::Callbacks& callbacks, + const absl::optional&) -> Http::AsyncClient::Request* { callback = &callbacks; EXPECT_STREQ("/api/v1/spans", message->headers().Path()->value().c_str()); @@ -182,12 +182,12 @@ TEST_F(ZipkinDriverTest, FlushOneSpanReportFailure) { Http::MockAsyncClientRequest request(&cm_.async_client_); Http::AsyncClient::Callbacks* callback; - const Optional timeout(std::chrono::seconds(5)); + const absl::optional timeout(std::chrono::seconds(5)); EXPECT_CALL(cm_.async_client_, send_(_, _, timeout)) - .WillOnce( - Invoke([&](Http::MessagePtr& message, Http::AsyncClient::Callbacks& callbacks, - const Optional&) -> Http::AsyncClient::Request* { + .WillOnce(Invoke( + [&](Http::MessagePtr& message, Http::AsyncClient::Callbacks& callbacks, + const absl::optional&) -> Http::AsyncClient::Request* { callback = &callbacks; EXPECT_STREQ("/api/v1/spans", message->headers().Path()->value().c_str()); @@ -220,7 +220,7 @@ TEST_F(ZipkinDriverTest, FlushOneSpanReportFailure) { TEST_F(ZipkinDriverTest, FlushSpansTimer) { setupValidDriver(); - const Optional timeout(std::chrono::seconds(5)); + const absl::optional timeout(std::chrono::seconds(5)); EXPECT_CALL(cm_.async_client_, send_(_, _, timeout)); EXPECT_CALL(runtime_.snapshot_, getInteger("tracing.zipkin.min_flush_spans", 5)) diff --git a/test/common/upstream/BUILD b/test/common/upstream/BUILD index 1ef4585f76bb..0a969a0ff6da 100644 --- a/test/common/upstream/BUILD +++ b/test/common/upstream/BUILD @@ -194,9 +194,9 @@ envoy_cc_test( envoy_cc_test( name = "outlier_detection_impl_test", srcs = ["outlier_detection_impl_test.cc"], + external_deps = ["abseil_optional"], deps = [ ":utility_lib", - "//include/envoy/common:optional", "//include/envoy/common:time_interface", "//source/common/network:utility_lib", "//source/common/upstream:outlier_detection_lib", diff --git a/test/common/upstream/cds_api_impl_test.cc b/test/common/upstream/cds_api_impl_test.cc index 19f3c84b0322..119258a1128c 100644 --- a/test/common/upstream/cds_api_impl_test.cc +++ b/test/common/upstream/cds_api_impl_test.cc @@ -73,9 +73,9 @@ class CdsApiImplTest : public testing::Test { void expectRequest() { EXPECT_CALL(cm_, httpAsyncClientForCluster("foo_cluster")); EXPECT_CALL(cm_.async_client_, send_(_, _, _)) - .WillOnce( - Invoke([&](Http::MessagePtr& request, Http::AsyncClient::Callbacks& callbacks, - const Optional&) -> Http::AsyncClient::Request* { + .WillOnce(Invoke( + [&](Http::MessagePtr& request, Http::AsyncClient::Callbacks& callbacks, + const absl::optional&) -> Http::AsyncClient::Request* { EXPECT_EQ((Http::TestHeaderMapImpl{ {":method", v2_rest_ ? "POST" : "GET"}, {":path", v2_rest_ ? "/v2/discovery:clusters" @@ -106,7 +106,7 @@ class CdsApiImplTest : public testing::Test { Event::MockTimer* interval_timer_; Http::AsyncClient::Callbacks* callbacks_{}; ReadyWatcher initialized_; - Optional eds_config_; + absl::optional eds_config_; }; // Negative test for protoc-gen-validate constraints. diff --git a/test/common/upstream/cluster_manager_impl_test.cc b/test/common/upstream/cluster_manager_impl_test.cc index facc15b6f4d2..37c7100599c4 100644 --- a/test/common/upstream/cluster_manager_impl_test.cc +++ b/test/common/upstream/cluster_manager_impl_test.cc @@ -67,7 +67,7 @@ class TestClusterManagerFactory : public ClusterManagerFactory { } CdsApiPtr createCds(const envoy::api::v2::core::ConfigSource&, - const Optional&, + const absl::optional&, ClusterManager&) override { return CdsApiPtr{createCds_()}; } @@ -208,7 +208,8 @@ TEST_F(ClusterManagerImplTest, OutlierEventLog) { TEST_F(ClusterManagerImplTest, NoSdsConfig) { const std::string json = fmt::sprintf("{%s}", clustersJson({defaultSdsClusterJson("cluster_1")})); - EXPECT_THROW(create(parseBootstrapFromJson(json)), EnvoyException); + EXPECT_THROW_WITH_MESSAGE(create(parseBootstrapFromJson(json)), EnvoyException, + "cannot create sds cluster with no sds config"); } TEST_F(ClusterManagerImplTest, UnknownClusterType) { diff --git a/test/common/upstream/health_checker_impl_test.cc b/test/common/upstream/health_checker_impl_test.cc index ffae54c06f2c..73fa9417a3cf 100644 --- a/test/common/upstream/health_checker_impl_test.cc +++ b/test/common/upstream/health_checker_impl_test.cc @@ -291,10 +291,10 @@ class HttpHealthCheckerImplTest : public testing::Test { void respond(size_t index, const std::string& code, bool conn_close, bool body = false, bool trailers = false, - const Optional& service_cluster = Optional()) { + const absl::optional& service_cluster = absl::optional()) { std::unique_ptr response_headers( new Http::TestHeaderMapImpl{{":status", code}}); - if (service_cluster.valid()) { + if (service_cluster) { response_headers->addCopy(Http::Headers::get().EnvoyUpstreamHealthCheckedCluster, service_cluster.value()); } @@ -471,7 +471,7 @@ TEST_F(HttpHealthCheckerImplTest, SuccessServiceCheck) { .WillOnce(Return(45000)); EXPECT_CALL(*test_sessions_[0]->interval_timer_, enableTimer(std::chrono::milliseconds(45000))); EXPECT_CALL(*test_sessions_[0]->timeout_timer_, disableTimer()); - Optional health_checked_cluster("locations-production-iad"); + absl::optional health_checked_cluster("locations-production-iad"); respond(0, "200", false, true, false, health_checked_cluster); EXPECT_TRUE(cluster_->prioritySet().getMockHostSet(0)->hosts_[0]->healthy()); } @@ -508,7 +508,7 @@ TEST_F(HttpHealthCheckerImplTest, SuccessServiceCheckWithCustomHostValue) { .WillOnce(Return(45000)); EXPECT_CALL(*test_sessions_[0]->interval_timer_, enableTimer(std::chrono::milliseconds(45000))); EXPECT_CALL(*test_sessions_[0]->timeout_timer_, disableTimer()); - Optional health_checked_cluster("locations-production-iad"); + absl::optional health_checked_cluster("locations-production-iad"); respond(0, "200", false, true, false, health_checked_cluster); EXPECT_TRUE(cluster_->prioritySet().getMockHostSet(0)->hosts_[0]->healthy()); } @@ -533,7 +533,7 @@ TEST_F(HttpHealthCheckerImplTest, ServiceDoesNotMatchFail) { .WillOnce(Return(45000)); EXPECT_CALL(*test_sessions_[0]->interval_timer_, enableTimer(std::chrono::milliseconds(45000))); EXPECT_CALL(*test_sessions_[0]->timeout_timer_, disableTimer()); - Optional health_checked_cluster("api-production-iad"); + absl::optional health_checked_cluster("api-production-iad"); respond(0, "200", false, true, false, health_checked_cluster); EXPECT_TRUE(cluster_->prioritySet().getMockHostSet(0)->hosts_[0]->healthFlagGet( Host::HealthFlag::FAILED_ACTIVE_HC)); @@ -586,7 +586,7 @@ TEST_F(HttpHealthCheckerImplTest, ServiceCheckRuntimeOff) { .WillOnce(Return(45000)); EXPECT_CALL(*test_sessions_[0]->interval_timer_, enableTimer(std::chrono::milliseconds(45000))); EXPECT_CALL(*test_sessions_[0]->timeout_timer_, disableTimer()); - Optional health_checked_cluster("api-production-iad"); + absl::optional health_checked_cluster("api-production-iad"); respond(0, "200", false, true, false, health_checked_cluster); EXPECT_TRUE(cluster_->prioritySet().getMockHostSet(0)->hosts_[0]->healthy()); } @@ -603,7 +603,7 @@ TEST_F(HttpHealthCheckerImplTest, SuccessStartFailedFailFirstServiceCheck) { expectStreamCreate(0); EXPECT_CALL(*test_sessions_[0]->timeout_timer_, enableTimer(_)); health_checker_->start(); - Optional health_checked_cluster("locations-production-iad"); + absl::optional health_checked_cluster("locations-production-iad"); // Test that failing first disables fast success. EXPECT_CALL(*this, onHostStatus(_, false)); diff --git a/test/common/upstream/load_balancer_benchmark.cc b/test/common/upstream/load_balancer_benchmark.cc index 69f45dc0c120..ccb6dfde700d 100644 --- a/test/common/upstream/load_balancer_benchmark.cc +++ b/test/common/upstream/load_balancer_benchmark.cc @@ -33,7 +33,7 @@ class BaseTester { class RingHashTester : public BaseTester { public: RingHashTester(uint64_t num_hosts, uint64_t min_ring_size) : BaseTester(num_hosts) { - config_.value(envoy::api::v2::Cluster::RingHashLbConfig()); + config_ = (envoy::api::v2::Cluster::RingHashLbConfig()); config_.value().mutable_minimum_ring_size()->set_value(min_ring_size); ring_hash_lb_.reset(new RingHashLoadBalancer{priority_set_, stats_, runtime_, random_, config_, common_config_}); @@ -43,7 +43,7 @@ class RingHashTester : public BaseTester { ClusterStats stats_{ClusterInfoImpl::generateStats(stats_store_)}; NiceMock runtime_; Runtime::RandomGeneratorImpl random_; - Optional config_; + absl::optional config_; std::unique_ptr ring_hash_lb_; envoy::api::v2::Cluster::CommonLbConfig common_config_; }; @@ -92,11 +92,11 @@ BENCHMARK(BM_MaglevLoadBalancerBuildTable) class TestLoadBalancerContext : public LoadBalancerContext { public: // Upstream::LoadBalancerContext - Optional computeHashKey() override { return hash_key_; } + absl::optional computeHashKey() override { return hash_key_; } const Router::MetadataMatchCriteria* metadataMatchCriteria() const override { return nullptr; } const Network::Connection* downstreamConnection() const override { return nullptr; } - Optional hash_key_; + absl::optional hash_key_; }; void computeHitStats(benchmark::State& state, @@ -139,7 +139,7 @@ void BM_RingHashLoadBalancerChooseHost(benchmark::State& state) { // TODO(mattklein123): When Maglev is a real load balancer, further share code with the // other test. for (uint64_t i = 0; i < keys_to_simulate; i++) { - context.hash_key_.value(hashInt(i)); + context.hash_key_ = (hashInt(i)); hit_counter[lb->chooseHost(&context)->address()->asString()] += 1; } @@ -201,7 +201,7 @@ void BM_RingHashLoadBalancerHostLoss(benchmark::State& state) { std::vector hosts; TestLoadBalancerContext context; for (uint64_t i = 0; i < keys_to_simulate; i++) { - context.hash_key_.value(hashInt(i)); + context.hash_key_ = (hashInt(i)); hosts.push_back(lb->chooseHost(&context)); } @@ -210,7 +210,7 @@ void BM_RingHashLoadBalancerHostLoss(benchmark::State& state) { lb = tester2.ring_hash_lb_->factory()->create(); std::vector hosts2; for (uint64_t i = 0; i < keys_to_simulate; i++) { - context.hash_key_.value(hashInt(i)); + context.hash_key_ = (hashInt(i)); hosts2.push_back(lb->chooseHost(&context)); } diff --git a/test/common/upstream/maglev_lb_test.cc b/test/common/upstream/maglev_lb_test.cc index f4c852cb973d..875a18928d09 100644 --- a/test/common/upstream/maglev_lb_test.cc +++ b/test/common/upstream/maglev_lb_test.cc @@ -11,11 +11,11 @@ class TestLoadBalancerContext : public LoadBalancerContext { TestLoadBalancerContext(uint64_t hash_key) : hash_key_(hash_key) {} // Upstream::LoadBalancerContext - Optional computeHashKey() override { return hash_key_; } + absl::optional computeHashKey() override { return hash_key_; } const Router::MetadataMatchCriteria* metadataMatchCriteria() const override { return nullptr; } const Network::Connection* downstreamConnection() const override { return nullptr; } - Optional hash_key_; + absl::optional hash_key_; }; // Note: ThreadAwareLoadBalancer base is heavily tested by RingHashLoadBalancerTest. Only basic diff --git a/test/common/upstream/original_dst_cluster_test.cc b/test/common/upstream/original_dst_cluster_test.cc index d94e5cc7f268..6ed7cf3db278 100644 --- a/test/common/upstream/original_dst_cluster_test.cc +++ b/test/common/upstream/original_dst_cluster_test.cc @@ -36,11 +36,11 @@ class TestLoadBalancerContext : public LoadBalancerContext { TestLoadBalancerContext(const Network::Connection* connection) : connection_(connection) {} // Upstream::LoadBalancerContext - Optional computeHashKey() override { return 0; } + absl::optional computeHashKey() override { return 0; } const Network::Connection* downstreamConnection() const override { return connection_; } const Router::MetadataMatchCriteria* metadataMatchCriteria() const override { return nullptr; } - Optional hash_key_; + absl::optional hash_key_; const Network::Connection* connection_; }; diff --git a/test/common/upstream/outlier_detection_impl_test.cc b/test/common/upstream/outlier_detection_impl_test.cc index 9b507b19e5d6..4dee20f917d3 100644 --- a/test/common/upstream/outlier_detection_impl_test.cc +++ b/test/common/upstream/outlier_detection_impl_test.cc @@ -4,7 +4,6 @@ #include #include -#include "envoy/common/optional.h" #include "envoy/common/time.h" #include "common/network/utility.h" @@ -17,6 +16,7 @@ #include "test/mocks/runtime/mocks.h" #include "test/mocks/upstream/mocks.h" +#include "absl/types/optional.h" #include "gmock/gmock.h" #include "gtest/gtest.h" @@ -217,7 +217,7 @@ TEST_F(OutlierDetectorImplTest, BasicFlow5xx) { .WillOnce(Return(MonotonicTime(std::chrono::milliseconds(9999)))); EXPECT_CALL(*interval_timer_, enableTimer(std::chrono::milliseconds(10000))); interval_timer_->callback_(); - EXPECT_FALSE(hosts_[0]->outlierDetector().lastUnejectionTime().valid()); + EXPECT_FALSE(hosts_[0]->outlierDetector().lastUnejectionTime()); // Interval that does bring the host back in. EXPECT_CALL(time_source_, currentTime()) @@ -228,7 +228,7 @@ TEST_F(OutlierDetectorImplTest, BasicFlow5xx) { EXPECT_CALL(*interval_timer_, enableTimer(std::chrono::milliseconds(10000))); interval_timer_->callback_(); EXPECT_FALSE(hosts_[0]->healthFlagGet(Host::HealthFlag::FAILED_OUTLIER_CHECK)); - EXPECT_TRUE(hosts_[0]->outlierDetector().lastUnejectionTime().valid()); + EXPECT_TRUE(hosts_[0]->outlierDetector().lastUnejectionTime()); // Eject host again to cause an ejection after an unejection has taken place hosts_[0]->outlierDetector().putResponseTime(std::chrono::milliseconds(5)); @@ -302,7 +302,7 @@ TEST_F(OutlierDetectorImplTest, BasicFlowGatewayFailure) { .WillOnce(Return(MonotonicTime(std::chrono::milliseconds(9999)))); EXPECT_CALL(*interval_timer_, enableTimer(std::chrono::milliseconds(10000))); interval_timer_->callback_(); - EXPECT_FALSE(hosts_[0]->outlierDetector().lastUnejectionTime().valid()); + EXPECT_FALSE(hosts_[0]->outlierDetector().lastUnejectionTime()); // Interval that does bring the host back in. EXPECT_CALL(time_source_, currentTime()) @@ -313,7 +313,7 @@ TEST_F(OutlierDetectorImplTest, BasicFlowGatewayFailure) { EXPECT_CALL(*interval_timer_, enableTimer(std::chrono::milliseconds(10000))); interval_timer_->callback_(); EXPECT_FALSE(hosts_[0]->healthFlagGet(Host::HealthFlag::FAILED_OUTLIER_CHECK)); - EXPECT_TRUE(hosts_[0]->outlierDetector().lastUnejectionTime().valid()); + EXPECT_TRUE(hosts_[0]->outlierDetector().lastUnejectionTime()); // Eject host again to cause an ejection after an unejection has taken place hosts_[0]->outlierDetector().putResponseTime(std::chrono::milliseconds(5)); @@ -396,7 +396,7 @@ TEST_F(OutlierDetectorImplTest, BasicFlowGatewayFailureAnd5xx) { .WillOnce(Return(MonotonicTime(std::chrono::milliseconds(9999)))); EXPECT_CALL(*interval_timer_, enableTimer(std::chrono::milliseconds(10000))); interval_timer_->callback_(); - EXPECT_FALSE(hosts_[0]->outlierDetector().lastUnejectionTime().valid()); + EXPECT_FALSE(hosts_[0]->outlierDetector().lastUnejectionTime()); // Interval that does bring the host back in. EXPECT_CALL(time_source_, currentTime()) @@ -407,7 +407,7 @@ TEST_F(OutlierDetectorImplTest, BasicFlowGatewayFailureAnd5xx) { EXPECT_CALL(*interval_timer_, enableTimer(std::chrono::milliseconds(10000))); interval_timer_->callback_(); EXPECT_FALSE(hosts_[0]->healthFlagGet(Host::HealthFlag::FAILED_OUTLIER_CHECK)); - EXPECT_TRUE(hosts_[0]->outlierDetector().lastUnejectionTime().valid()); + EXPECT_TRUE(hosts_[0]->outlierDetector().lastUnejectionTime()); // Eject host again but with a mix of 500s and 503s to trigger 5xx ejection first hosts_[0]->outlierDetector().putResponseTime(std::chrono::milliseconds(5)); @@ -743,8 +743,8 @@ TEST(DetectorHostMonitorNullImplTest, All) { DetectorHostMonitorNullImpl null_sink; EXPECT_EQ(0UL, null_sink.numEjections()); - EXPECT_FALSE(null_sink.lastEjectionTime().valid()); - EXPECT_FALSE(null_sink.lastUnejectionTime().valid()); + EXPECT_FALSE(null_sink.lastEjectionTime()); + EXPECT_FALSE(null_sink.lastUnejectionTime()); } TEST(OutlierDetectionEventLoggerImplTest, All) { @@ -755,8 +755,8 @@ TEST(OutlierDetectionEventLoggerImplTest, All) { ON_CALL(*host, cluster()).WillByDefault(ReturnRef(cluster)); NiceMock time_source; NiceMock monotonic_time_source; - Optional time; - Optional monotonic_time; + absl::optional time; + absl::optional monotonic_time; NiceMock detector; EXPECT_CALL(log_manager, createAccessLog("foo")).WillOnce(Return(file)); @@ -784,8 +784,8 @@ TEST(OutlierDetectionEventLoggerImplTest, All) { Json::Factory::loadFromString(log2); // now test with time since last action. - time.value(time_source.currentTime() - std::chrono::seconds(30)); - monotonic_time.value(monotonic_time_source.currentTime() - std::chrono::seconds(30)); + time = (time_source.currentTime() - std::chrono::seconds(30)); + monotonic_time = (monotonic_time_source.currentTime() - std::chrono::seconds(30)); std::string log3; EXPECT_CALL(host->outlier_detector_, lastUnejectionTime()).WillOnce(ReturnRef(monotonic_time)); diff --git a/test/common/upstream/ring_hash_lb_test.cc b/test/common/upstream/ring_hash_lb_test.cc index db61d613c77c..6d49724b694c 100644 --- a/test/common/upstream/ring_hash_lb_test.cc +++ b/test/common/upstream/ring_hash_lb_test.cc @@ -27,11 +27,11 @@ class TestLoadBalancerContext : public LoadBalancerContext { TestLoadBalancerContext(uint64_t hash_key) : hash_key_(hash_key) {} // Upstream::LoadBalancerContext - Optional computeHashKey() override { return hash_key_; } + absl::optional computeHashKey() override { return hash_key_; } const Router::MetadataMatchCriteria* metadataMatchCriteria() const override { return nullptr; } const Network::Connection* downstreamConnection() const override { return nullptr; } - Optional hash_key_; + absl::optional hash_key_; }; class RingHashLoadBalancerTest : public ::testing::TestWithParam { @@ -54,7 +54,7 @@ class RingHashLoadBalancerTest : public ::testing::TestWithParam { std::shared_ptr info_{new NiceMock()}; Stats::IsolatedStoreImpl stats_store_; ClusterStats stats_; - Optional config_; + absl::optional config_; envoy::api::v2::Cluster::CommonLbConfig common_config_; NiceMock runtime_; NiceMock random_; @@ -81,7 +81,7 @@ TEST_P(RingHashLoadBalancerTest, Basic) { hostSet().healthy_hosts_ = hostSet().hosts_; hostSet().runCallbacks({}, {}); - config_.value(envoy::api::v2::Cluster::RingHashLbConfig()); + config_ = (envoy::api::v2::Cluster::RingHashLbConfig()); config_.value().mutable_minimum_ring_size()->set_value(12); config_.value().mutable_deprecated_v1()->mutable_use_std_hash()->set_value(false); @@ -148,7 +148,7 @@ TEST_P(RingHashFailoverTest, BasicFailover) { failover_host_set_.healthy_hosts_ = {makeTestHost(info_, "tcp://127.0.0.1:82")}; failover_host_set_.hosts_ = failover_host_set_.healthy_hosts_; - config_.value(envoy::api::v2::Cluster::RingHashLbConfig()); + config_ = (envoy::api::v2::Cluster::RingHashLbConfig()); config_.value().mutable_minimum_ring_size()->set_value(12); config_.value().mutable_deprecated_v1()->mutable_use_std_hash()->set_value(false); init(); @@ -193,7 +193,7 @@ TEST_P(RingHashLoadBalancerTest, BasicWithStdHash) { hostSet().runCallbacks({}, {}); // use_std_hash defaults to true so don't set it here. - config_.value(envoy::api::v2::Cluster::RingHashLbConfig()); + config_ = (envoy::api::v2::Cluster::RingHashLbConfig()); config_.value().mutable_minimum_ring_size()->set_value(12); init(); @@ -241,7 +241,7 @@ TEST_P(RingHashLoadBalancerTest, UnevenHosts) { hostSet().healthy_hosts_ = hostSet().hosts_; hostSet().runCallbacks({}, {}); - config_.value(envoy::api::v2::Cluster::RingHashLbConfig()); + config_ = (envoy::api::v2::Cluster::RingHashLbConfig()); config_.value().mutable_minimum_ring_size()->set_value(3); config_.value().mutable_deprecated_v1()->mutable_use_std_hash()->set_value(false); init(); diff --git a/test/common/upstream/sds_test.cc b/test/common/upstream/sds_test.cc index a4a292658c88..d89b7de332a7 100644 --- a/test/common/upstream/sds_test.cc +++ b/test/common/upstream/sds_test.cc @@ -90,20 +90,23 @@ class SdsTest : public testing::Test { void setupPoolFailure() { EXPECT_CALL(cm_, httpAsyncClientForCluster("sds")).WillOnce(ReturnRef(cm_.async_client_)); - EXPECT_CALL(cm_.async_client_, - send_(_, _, Optional(std::chrono::milliseconds(1000)))) - .WillOnce(Invoke([](Http::MessagePtr&, Http::AsyncClient::Callbacks& callbacks, - Optional) -> Http::AsyncClient::Request* { - callbacks.onSuccess(Http::MessagePtr{new Http::ResponseMessageImpl( - Http::HeaderMapPtr{new Http::TestHeaderMapImpl{{":status", "503"}}})}); - return nullptr; - })); + EXPECT_CALL( + cm_.async_client_, + send_(_, _, absl::optional(std::chrono::milliseconds(1000)))) + .WillOnce( + Invoke([](Http::MessagePtr&, Http::AsyncClient::Callbacks& callbacks, + absl::optional) -> Http::AsyncClient::Request* { + callbacks.onSuccess(Http::MessagePtr{new Http::ResponseMessageImpl( + Http::HeaderMapPtr{new Http::TestHeaderMapImpl{{":status", "503"}}})}); + return nullptr; + })); } void setupRequest() { EXPECT_CALL(cm_, httpAsyncClientForCluster("sds")).WillOnce(ReturnRef(cm_.async_client_)); - EXPECT_CALL(cm_.async_client_, - send_(_, _, Optional(std::chrono::milliseconds(1000)))) + EXPECT_CALL( + cm_.async_client_, + send_(_, _, absl::optional(std::chrono::milliseconds(1000)))) .WillOnce(DoAll(WithArg<1>(SaveArgAddress(&callbacks_)), Return(&request_))); } diff --git a/test/common/upstream/subset_lb_test.cc b/test/common/upstream/subset_lb_test.cc index 595c411a8ad9..ea092992f3d1 100644 --- a/test/common/upstream/subset_lb_test.cc +++ b/test/common/upstream/subset_lb_test.cc @@ -6,7 +6,6 @@ #include #include "envoy/api/v2/cds.pb.h" -#include "envoy/common/optional.h" #include "common/config/metadata.h" #include "common/upstream/subset_lb.h" @@ -16,6 +15,7 @@ #include "test/mocks/runtime/mocks.h" #include "test/mocks/upstream/mocks.h" +#include "absl/types/optional.h" #include "gmock/gmock.h" #include "gtest/gtest.h" @@ -69,7 +69,7 @@ class TestLoadBalancerContext : public LoadBalancerContext { new TestMetadataMatchCriteria(std::map(metadata_matches))) {} // Upstream::LoadBalancerContext - Optional computeHashKey() override { return {}; } + absl::optional computeHashKey() override { return {}; } const Network::Connection* downstreamConnection() const override { return nullptr; } const Router::MetadataMatchCriteria* metadataMatchCriteria() const override { return matches_.get(); @@ -191,7 +191,7 @@ class SubsetLoadBalancerTest : public testing::TestWithParam { return default_subset; } - void modifyHosts(HostVector add, HostVector remove, Optional add_in_locality = {}, + void modifyHosts(HostVector add, HostVector remove, absl::optional add_in_locality = {}, uint32_t priority = 0) { MockHostSet& host_set = *priority_set_.getMockHostSet(priority); for (const auto& host : remove) { @@ -220,7 +220,7 @@ class SubsetLoadBalancerTest : public testing::TestWithParam { host_set.hosts_.emplace_back(host); host_set.healthy_hosts_ = host_set.hosts_; - if (add_in_locality.valid()) { + if (add_in_locality) { std::vector locality_hosts_copy = host_set.hosts_per_locality_->get(); locality_hosts_copy[add_in_locality.value()].emplace_back(host); host_set.hosts_per_locality_ = makeHostsPerLocality(std::move(locality_hosts_copy)); @@ -822,7 +822,7 @@ TEST_P(SubsetLoadBalancerTest, ZoneAwareFallbackAfterUpdate) { EXPECT_EQ(host_set_.healthy_hosts_per_locality_->get()[1][1], lb_->chooseHost(nullptr)); modifyHosts({makeHost("tcp://127.0.0.1:8000", {{"version", "1.0"}})}, {host_set_.hosts_[0]}, - Optional(0)); + absl::optional(0)); modifyLocalHosts({makeHost("tcp://127.0.0.1:9000", {{"version", "1.0"}})}, {local_hosts_->at(0)}, 0); @@ -943,7 +943,7 @@ TEST_P(SubsetLoadBalancerTest, ZoneAwareFallbackDefaultSubsetAfterUpdate) { EXPECT_EQ(host_set_.healthy_hosts_per_locality_->get()[1][3], lb_->chooseHost(nullptr)); modifyHosts({makeHost("tcp://127.0.0.1:8001", {{"version", "default"}})}, {host_set_.hosts_[1]}, - Optional(0)); + absl::optional(0)); modifyLocalHosts({local_hosts_->at(1)}, {makeHost("tcp://127.0.0.1:9001", {{"version", "default"}})}, 0); @@ -1062,7 +1062,7 @@ TEST_P(SubsetLoadBalancerTest, ZoneAwareBalancesSubsetsAfterUpdate) { EXPECT_EQ(host_set_.healthy_hosts_per_locality_->get()[1][3], lb_->chooseHost(&context)); modifyHosts({makeHost("tcp://127.0.0.1:8001", {{"version", "1.1"}})}, {host_set_.hosts_[1]}, - Optional(0)); + absl::optional(0)); modifyLocalHosts({local_hosts_->at(1)}, {makeHost("tcp://127.0.0.1:9001", {{"version", "1.1"}})}, 0); diff --git a/test/common/upstream/utility.h b/test/common/upstream/utility.h index 98af6611a503..ea6aa5b3d404 100644 --- a/test/common/upstream/utility.h +++ b/test/common/upstream/utility.h @@ -47,7 +47,7 @@ inline envoy::api::v2::Cluster parseClusterFromJson(const std::string& json_stri envoy::api::v2::Cluster cluster; auto json_object_ptr = Json::Factory::loadFromString(json_string); Config::CdsJson::translateCluster(*json_object_ptr, - Optional(), cluster); + absl::optional(), cluster); return cluster; } diff --git a/test/mocks/grpc/mocks.h b/test/mocks/grpc/mocks.h index 2290a91392ca..c43eda618033 100644 --- a/test/mocks/grpc/mocks.h +++ b/test/mocks/grpc/mocks.h @@ -64,7 +64,7 @@ class MockAsyncClient : public AsyncClient { MOCK_METHOD5_T(send, AsyncRequest*(const Protobuf::MethodDescriptor& service_method, const Protobuf::Message& request, AsyncRequestCallbacks& callbacks, Tracing::Span& parent_span, - const Optional& timeout)); + const absl::optional& timeout)); MOCK_METHOD2_T(start, AsyncStream*(const Protobuf::MethodDescriptor& service_method, AsyncStreamCallbacks& callbacks)); }; diff --git a/test/mocks/http/mocks.h b/test/mocks/http/mocks.h index c5082c1c08ce..d45621b75cb6 100644 --- a/test/mocks/http/mocks.h +++ b/test/mocks/http/mocks.h @@ -47,7 +47,7 @@ class MockConnectionManagerConfig : public ConnectionManagerConfig { MOCK_METHOD0(drainTimeout, std::chrono::milliseconds()); MOCK_METHOD0(filterFactory, FilterChainFactory&()); MOCK_METHOD0(generateRequestId, bool()); - MOCK_METHOD0(idleTimeout, const Optional&()); + MOCK_METHOD0(idleTimeout, const absl::optional&()); MOCK_METHOD0(routeConfigProvider, Router::RouteConfigProvider&()); MOCK_METHOD0(serverName, const std::string&()); MOCK_METHOD0(stats, ConnectionManagerStats&()); @@ -58,7 +58,7 @@ class MockConnectionManagerConfig : public ConnectionManagerConfig { MOCK_CONST_METHOD0(setCurrentClientCertDetails, const std::vector&()); MOCK_METHOD0(localAddress, const Network::Address::Instance&()); - MOCK_METHOD0(userAgent, const Optional&()); + MOCK_METHOD0(userAgent, const absl::optional&()); MOCK_METHOD0(tracingConfig, const Http::TracingConnectionManagerConfig*()); MOCK_METHOD0(listenerStats, ConnectionManagerListenerStats&()); MOCK_CONST_METHOD0(proxy100Continue, bool()); @@ -354,15 +354,15 @@ class MockAsyncClient : public AsyncClient { // Http::AsyncClient Request* send(MessagePtr&& request, Callbacks& callbacks, - const Optional& timeout) override { + const absl::optional& timeout) override { return send_(request, callbacks, timeout); } MOCK_METHOD3(send_, Request*(MessagePtr& request, Callbacks& callbacks, - const Optional& timeout)); + const absl::optional& timeout)); MOCK_METHOD3(start, Stream*(StreamCallbacks& callbacks, - const Optional& timeout, + const absl::optional& timeout, bool buffer_body_for_retry)); MOCK_METHOD0(dispatcher, Event::Dispatcher&()); diff --git a/test/mocks/request_info/mocks.h b/test/mocks/request_info/mocks.h index 19dfbfe6c537..fd596926767c 100644 --- a/test/mocks/request_info/mocks.h +++ b/test/mocks/request_info/mocks.h @@ -19,27 +19,27 @@ class MockRequestInfo : public RequestInfo { MOCK_METHOD1(onUpstreamHostSelected, void(Upstream::HostDescriptionConstSharedPtr host)); MOCK_CONST_METHOD0(startTime, SystemTime()); MOCK_CONST_METHOD0(startTimeMonotonic, MonotonicTime()); - MOCK_CONST_METHOD0(lastDownstreamRxByteReceived, Optional()); + MOCK_CONST_METHOD0(lastDownstreamRxByteReceived, absl::optional()); MOCK_METHOD0(onLastDownstreamRxByteReceived, void()); - MOCK_CONST_METHOD0(firstUpstreamTxByteSent, Optional()); + MOCK_CONST_METHOD0(firstUpstreamTxByteSent, absl::optional()); MOCK_METHOD0(onFirstUpstreamTxByteSent, void()); - MOCK_CONST_METHOD0(lastUpstreamTxByteSent, Optional()); + MOCK_CONST_METHOD0(lastUpstreamTxByteSent, absl::optional()); MOCK_METHOD0(onLastUpstreamTxByteSent, void()); - MOCK_CONST_METHOD0(firstUpstreamRxByteReceived, Optional()); + MOCK_CONST_METHOD0(firstUpstreamRxByteReceived, absl::optional()); MOCK_METHOD0(onFirstUpstreamRxByteReceived, void()); - MOCK_CONST_METHOD0(lastUpstreamRxByteReceived, Optional()); + MOCK_CONST_METHOD0(lastUpstreamRxByteReceived, absl::optional()); MOCK_METHOD0(onLastUpstreamRxByteReceived, void()); - MOCK_CONST_METHOD0(firstDownstreamTxByteSent, Optional()); + MOCK_CONST_METHOD0(firstDownstreamTxByteSent, absl::optional()); MOCK_METHOD0(onFirstDownstreamTxByteSent, void()); - MOCK_CONST_METHOD0(lastDownstreamTxByteSent, Optional()); + MOCK_CONST_METHOD0(lastDownstreamTxByteSent, absl::optional()); MOCK_METHOD0(onLastDownstreamTxByteSent, void()); MOCK_METHOD0(onRequestComplete, void()); - MOCK_CONST_METHOD0(requestComplete, Optional()); + MOCK_CONST_METHOD0(requestComplete, absl::optional()); MOCK_METHOD0(resetUpstreamTimings, void()); MOCK_CONST_METHOD0(bytesReceived, uint64_t()); - MOCK_CONST_METHOD0(protocol, Optional()); + MOCK_CONST_METHOD0(protocol, absl::optional()); MOCK_METHOD1(protocol, void(Http::Protocol protocol)); - MOCK_CONST_METHOD0(responseCode, Optional()); + MOCK_CONST_METHOD0(responseCode, absl::optional()); MOCK_CONST_METHOD0(bytesSent, uint64_t()); MOCK_CONST_METHOD1(getResponseFlag, bool(ResponseFlag)); MOCK_CONST_METHOD0(upstreamHost, Upstream::HostDescriptionConstSharedPtr()); @@ -54,19 +54,19 @@ class MockRequestInfo : public RequestInfo { new testing::NiceMock()}; SystemTime start_time_; MonotonicTime start_time_monotonic_; - Optional last_downstream_rx_byte_received_; - Optional first_upstream_tx_byte_sent_; - Optional last_upstream_tx_byte_sent_; - Optional first_upstream_rx_byte_received_; - Optional last_upstream_rx_byte_received_; - Optional first_downstream_tx_byte_sent_; - Optional last_downstream_tx_byte_sent_; - Optional end_time_; + absl::optional last_downstream_rx_byte_received_; + absl::optional first_upstream_tx_byte_sent_; + absl::optional last_upstream_tx_byte_sent_; + absl::optional first_upstream_rx_byte_received_; + absl::optional last_upstream_rx_byte_received_; + absl::optional first_downstream_tx_byte_sent_; + absl::optional last_downstream_tx_byte_sent_; + absl::optional end_time_; Network::Address::InstanceConstSharedPtr upstream_local_address_; Network::Address::InstanceConstSharedPtr downstream_local_address_; Network::Address::InstanceConstSharedPtr downstream_remote_address_; - Optional protocol_; - Optional response_code_; + absl::optional protocol_; + absl::optional response_code_; uint64_t bytes_received_{}; uint64_t bytes_sent_{}; }; diff --git a/test/mocks/router/mocks.h b/test/mocks/router/mocks.h index 8ebf699a5ae9..bd581894f320 100644 --- a/test/mocks/router/mocks.h +++ b/test/mocks/router/mocks.h @@ -49,7 +49,7 @@ class TestCorsPolicy : public CorsPolicy { const std::string& allowHeaders() const override { return allow_headers_; }; const std::string& exposeHeaders() const override { return expose_headers_; }; const std::string& maxAge() const override { return max_age_; }; - const Optional& allowCredentials() const override { return allow_credentials_; }; + const absl::optional& allowCredentials() const override { return allow_credentials_; }; bool enabled() const override { return enabled_; }; std::list allow_origin_{}; @@ -57,7 +57,7 @@ class TestCorsPolicy : public CorsPolicy { std::string allow_headers_{}; std::string expose_headers_{}; std::string max_age_{}; - Optional allow_credentials_{}; + absl::optional allow_credentials_{}; bool enabled_{false}; }; @@ -82,7 +82,7 @@ class MockRetryState : public RetryState { MOCK_METHOD0(enabled, bool()); MOCK_METHOD3(shouldRetry, RetryStatus(const Http::HeaderMap* response_headers, - const Optional& reset_reason, + const absl::optional& reset_reason, DoRetryCallback callback)); DoRetryCallback callback_; @@ -175,9 +175,9 @@ class MockHashPolicy : public HashPolicy { ~MockHashPolicy(); // Router::HashPolicy - MOCK_CONST_METHOD3(generateHash, Optional(const std::string& downstream_address, - const Http::HeaderMap& headers, - const AddCookieCallback add_cookie)); + MOCK_CONST_METHOD3(generateHash, absl::optional(const std::string& downstream_address, + const Http::HeaderMap& headers, + const AddCookieCallback add_cookie)); }; class MockMetadataMatchCriteria : public MetadataMatchCriteria { diff --git a/test/mocks/runtime/BUILD b/test/mocks/runtime/BUILD index da08ebe7760c..e373cb891685 100644 --- a/test/mocks/runtime/BUILD +++ b/test/mocks/runtime/BUILD @@ -12,8 +12,8 @@ envoy_cc_mock( name = "runtime_mocks", srcs = ["mocks.cc"], hdrs = ["mocks.h"], + external_deps = ["abseil_optional"], deps = [ - "//include/envoy/common:optional", "//include/envoy/runtime:runtime_interface", "//test/mocks:common_lib", ], diff --git a/test/mocks/server/mocks.h b/test/mocks/server/mocks.h index 7146b00314c7..f28e7203da91 100644 --- a/test/mocks/server/mocks.h +++ b/test/mocks/server/mocks.h @@ -237,7 +237,7 @@ class MockInstance : public Instance { ~MockInstance(); // Server::Instance - RateLimit::ClientPtr rateLimitClient(const Optional&) override { + RateLimit::ClientPtr rateLimitClient(const absl::optional&) override { return RateLimit::ClientPtr{rateLimitClient_()}; } @@ -321,7 +321,7 @@ class MockFactoryContext : public FactoryContext { MockFactoryContext(); ~MockFactoryContext(); - RateLimit::ClientPtr rateLimitClient(const Optional&) override { + RateLimit::ClientPtr rateLimitClient(const absl::optional&) override { return RateLimit::ClientPtr{rateLimitClient_()}; } diff --git a/test/mocks/upstream/cluster_info.h b/test/mocks/upstream/cluster_info.h index ddeef3441b56..1ad1f506748e 100644 --- a/test/mocks/upstream/cluster_info.h +++ b/test/mocks/upstream/cluster_info.h @@ -49,7 +49,7 @@ class MockClusterInfo : public ClusterInfo { MOCK_CONST_METHOD0(lbType, LoadBalancerType()); MOCK_CONST_METHOD0(type, envoy::api::v2::Cluster::DiscoveryType()); MOCK_CONST_METHOD0(lbRingHashConfig, - const Optional&()); + const absl::optional&()); MOCK_CONST_METHOD0(maintenanceMode, bool()); MOCK_CONST_METHOD0(maxRequestsPerConnection, uint64_t()); MOCK_CONST_METHOD0(name, const std::string&()); @@ -76,7 +76,7 @@ class MockClusterInfo : public ClusterInfo { LoadBalancerType lb_type_{LoadBalancerType::RoundRobin}; envoy::api::v2::Cluster::DiscoveryType type_{envoy::api::v2::Cluster::STRICT_DNS}; NiceMock lb_subset_; - Optional lb_ring_hash_config_; + absl::optional lb_ring_hash_config_; envoy::api::v2::Cluster::CommonLbConfig lb_config_; }; diff --git a/test/mocks/upstream/host.h b/test/mocks/upstream/host.h index d2b35aea6162..54cf01b79575 100644 --- a/test/mocks/upstream/host.h +++ b/test/mocks/upstream/host.h @@ -26,8 +26,8 @@ class MockDetectorHostMonitor : public DetectorHostMonitor { MOCK_METHOD1(putHttpResponseCode, void(uint64_t code)); MOCK_METHOD1(putResult, void(Result result)); MOCK_METHOD1(putResponseTime, void(std::chrono::milliseconds time)); - MOCK_METHOD0(lastEjectionTime, const Optional&()); - MOCK_METHOD0(lastUnejectionTime, const Optional&()); + MOCK_METHOD0(lastEjectionTime, const absl::optional&()); + MOCK_METHOD0(lastUnejectionTime, const absl::optional&()); MOCK_CONST_METHOD0(successRate, double()); MOCK_METHOD1(successRate, void(double new_success_rate)); }; diff --git a/test/server/config_validation/async_client_test.cc b/test/server/config_validation/async_client_test.cc index f94c221f9e6a..200e8afb6c20 100644 --- a/test/server/config_validation/async_client_test.cc +++ b/test/server/config_validation/async_client_test.cc @@ -16,9 +16,10 @@ TEST(ValidationAsyncClientTest, MockedMethods) { MockAsyncClientStreamCallbacks stream_callbacks; ValidationAsyncClient client; + EXPECT_EQ(nullptr, client.send(std::move(message), callbacks, + absl::optional())); EXPECT_EQ(nullptr, - client.send(std::move(message), callbacks, Optional())); - EXPECT_EQ(nullptr, client.start(stream_callbacks, Optional(), false)); + client.start(stream_callbacks, absl::optional(), false)); } } // namespace Http diff --git a/test/server/config_validation/cluster_manager_test.cc b/test/server/config_validation/cluster_manager_test.cc index 583564223ea2..a9bfa1ac1c3a 100644 --- a/test/server/config_validation/cluster_manager_test.cc +++ b/test/server/config_validation/cluster_manager_test.cc @@ -44,7 +44,8 @@ TEST(ValidationClusterManagerTest, MockedMethods) { Http::AsyncClient& client = cluster_manager->httpAsyncClientForCluster("cluster"); Http::MockAsyncClientStreamCallbacks stream_callbacks; - EXPECT_EQ(nullptr, client.start(stream_callbacks, Optional(), false)); + EXPECT_EQ(nullptr, + client.start(stream_callbacks, absl::optional(), false)); } } // namespace Upstream diff --git a/test/server/lds_api_test.cc b/test/server/lds_api_test.cc index 45e805684974..95678d1ceef9 100644 --- a/test/server/lds_api_test.cc +++ b/test/server/lds_api_test.cc @@ -68,9 +68,9 @@ class LdsApiTest : public testing::Test { void expectRequest() { EXPECT_CALL(cluster_manager_, httpAsyncClientForCluster("foo_cluster")); EXPECT_CALL(cluster_manager_.async_client_, send_(_, _, _)) - .WillOnce( - Invoke([&](Http::MessagePtr& request, Http::AsyncClient::Callbacks& callbacks, - const Optional&) -> Http::AsyncClient::Request* { + .WillOnce(Invoke( + [&](Http::MessagePtr& request, Http::AsyncClient::Callbacks& callbacks, + const absl::optional&) -> Http::AsyncClient::Request* { EXPECT_EQ((Http::TestHeaderMapImpl{ {":method", v2_rest_ ? "POST" : "GET"}, {":path", v2_rest_ ? "/v2/discovery:listeners"