Skip to content

Commit

Permalink
add a helper class for runtime-derived uint32 (#16398)
Browse files Browse the repository at this point in the history
Adding runtime helper protobuf messages for RuntimeUInt32.
TODO(WeavingGao): use for 

Risk Level: Low
Testing: Unit Test
Docs Changes: N/A
Release Notes: N/A
part of #16392


Signed-off-by: gaoweiwen <[email protected]>
  • Loading branch information
WeavingGao authored May 20, 2021
1 parent 2b9fb47 commit 2174fd0
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
28 changes: 28 additions & 0 deletions source/common/runtime/runtime_protos.h
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,34 @@
namespace Envoy {
namespace Runtime {

// TODO(WeavingGao): use for #16392
// Helper class for runtime-derived uint32.
class UInt32 : Logger::Loggable<Logger::Id::runtime> {
public:
UInt32(const envoy::config::core::v3::RuntimeUInt32& uint32_proto, Runtime::Loader& runtime)
: runtime_key_(uint32_proto.runtime_key()), default_value_(uint32_proto.default_value()),
runtime_(runtime) {}

const std::string& runtimeKey() const { return runtime_key_; }

uint32_t value() const {
uint64_t raw_value = runtime_.snapshot().getInteger(runtime_key_, default_value_);
if (raw_value > std::numeric_limits<uint32_t>::max()) {
ENVOY_LOG_EVERY_POW_2(
warn,
"parsed runtime value:{} of {} is larger than uint32 max, returning default instead",
raw_value, runtime_key_);
return default_value_;
}
return static_cast<uint32_t>(raw_value);
}

private:
const std::string runtime_key_;
const uint32_t default_value_;
Runtime::Loader& runtime_;
};

// Helper class for runtime-derived boolean feature flags.
class FeatureFlag {
public:
Expand Down
21 changes: 21 additions & 0 deletions test/common/runtime/runtime_protos_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,27 @@ class RuntimeProtosTest : public testing::Test {
NiceMock<MockLoader> runtime_;
};

TEST_F(RuntimeProtosTest, UInt32Test) {
envoy::config::core::v3::RuntimeUInt32 uint32_proto;
std::string yaml(R"EOF(
runtime_key: "foo.bar"
default_value: 99
)EOF");
TestUtility::loadFromYamlAndValidate(yaml, uint32_proto);
UInt32 test_uint32(uint32_proto, runtime_);

EXPECT_EQ("foo.bar", test_uint32.runtimeKey());

EXPECT_CALL(runtime_.snapshot_, getInteger("foo.bar", 99));
EXPECT_EQ(99, test_uint32.value());

EXPECT_CALL(runtime_.snapshot_, getInteger("foo.bar", 99)).WillOnce(Return(1024));
EXPECT_EQ(1024, test_uint32.value());

EXPECT_CALL(runtime_.snapshot_, getInteger("foo.bar", 99)).WillOnce(Return(1ull << 33));
EXPECT_EQ(99, test_uint32.value());
}

TEST_F(RuntimeProtosTest, PercentBasicTest) {
envoy::config::core::v3::RuntimePercent percent_proto;
std::string yaml(R"EOF(
Expand Down

0 comments on commit 2174fd0

Please sign in to comment.