[JSON] Replace ctors with factory methods (#32834)

pull/32984/head
Mark D. Roth 2 years ago committed by GitHub
parent 8b02295e58
commit 844e740183
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 5
      src/core/BUILD
  2. 6
      src/core/ext/filters/client_channel/client_channel.cc
  3. 35
      src/core/ext/filters/client_channel/client_channel_channelz.cc
  4. 6
      src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.cc
  5. 10
      src/core/ext/filters/client_channel/lb_policy/rls/rls.cc
  6. 89
      src/core/ext/filters/client_channel/lb_policy/xds/cds.cc
  7. 72
      src/core/ext/filters/client_channel/lb_policy/xds/xds_cluster_resolver.cc
  8. 20
      src/core/ext/filters/client_channel/lb_policy/xds/xds_wrr_locality.cc
  9. 2
      src/core/ext/filters/client_channel/resolver/dns/event_engine/service_config_helper.cc
  10. 53
      src/core/ext/filters/client_channel/resolver/google_c2p/google_c2p_resolver.cc
  11. 4
      src/core/ext/xds/certificate_provider_store.cc
  12. 7
      src/core/ext/xds/xds_api.cc
  13. 7
      src/core/ext/xds/xds_audit_logger_registry.cc
  14. 21
      src/core/ext/xds/xds_bootstrap_grpc.cc
  15. 38
      src/core/ext/xds/xds_cluster.cc
  16. 18
      src/core/ext/xds/xds_cluster_specifier_plugin.cc
  17. 2
      src/core/ext/xds/xds_common_types.cc
  18. 25
      src/core/ext/xds/xds_http_fault_filter.cc
  19. 147
      src/core/ext/xds/xds_http_rbac_filter.cc
  20. 21
      src/core/ext/xds/xds_http_stateful_session_filter.cc
  21. 36
      src/core/ext/xds/xds_lb_policy_registry.cc
  22. 4
      src/core/ext/xds/xds_transport_grpc.cc
  23. 27
      src/core/lib/channel/channel_trace.cc
  24. 189
      src/core/lib/channel/channelz.cc
  25. 34
      src/core/lib/channel/channelz_registry.cc
  26. 210
      src/core/lib/json/json.h
  27. 8
      src/core/lib/json/json_object_loader.cc
  28. 17
      src/core/lib/json/json_reader.cc
  29. 17
      src/core/lib/json/json_util.cc
  30. 11
      src/core/lib/json/json_writer.cc
  31. 30
      src/core/lib/security/credentials/external/aws_external_account_credentials.cc
  32. 5
      src/core/lib/security/credentials/external/external_account_credentials.cc
  33. 25
      src/core/lib/security/credentials/jwt/json_token.cc
  34. 5
      src/core/lib/security/credentials/jwt/jwt_credentials.cc
  35. 3
      src/core/lib/service_config/service_config_impl.cc
  36. 3
      test/core/channel/channelz_test.cc
  37. 39
      test/core/client_channel/lb_policy/outlier_detection_test.cc
  38. 16
      test/core/client_channel/lb_policy/weighted_round_robin_test.cc
  39. 26
      test/core/client_channel/lb_policy/xds_override_host_test.cc
  40. 30
      test/core/json/json_object_loader_test.cc
  41. 125
      test/core/json/json_test.cc
  42. 12
      test/core/security/credentials_test.cc
  43. 8
      test/core/xds/certificate_provider_store_test.cc
  44. 6
      test/core/xds/xds_bootstrap_test.cc
  45. 8
      test/core/xds/xds_client_test.cc
  46. 8
      test/core/xds/xds_cluster_resource_type_test.cc
  47. 55
      test/core/xds/xds_http_filters_test.cc
  48. 2
      test/core/xds/xds_lb_policy_registry_test.cc
  49. 25
      test/cpp/util/channelz_sampler.cc

@ -3307,7 +3307,10 @@ grpc_cc_library(
hdrs = [
"lib/json/json.h",
],
external_deps = ["absl/types:variant"],
external_deps = [
"absl/strings",
"absl/types:variant",
],
deps = ["//:gpr"],
)

@ -1179,9 +1179,9 @@ RefCountedPtr<LoadBalancingPolicy::Config> ChooseLbPolicy(
// above.
if (!policy_name.has_value()) policy_name = "pick_first";
// Now that we have the policy name, construct an empty config for it.
Json config_json = Json::Array{Json::Object{
{std::string(*policy_name), Json::Object{}},
}};
Json config_json = Json::FromArray({Json::FromObject({
{std::string(*policy_name), Json::FromObject({})},
})});
auto lb_policy_config =
CoreConfiguration::Get().lb_policy_registry().ParseLoadBalancingConfig(
config_json);

@ -20,6 +20,8 @@
#include "src/core/ext/filters/client_channel/client_channel_channelz.h"
#include "absl/strings/str_cat.h"
#include "src/core/lib/transport/connectivity_state.h"
// IWYU pragma: no_include <type_traits>
@ -49,13 +51,11 @@ Json SubchannelNode::RenderJson() {
grpc_connectivity_state state =
connectivity_state_.load(std::memory_order_relaxed);
Json::Object data = {
{"state",
Json::Object{
{"state", ConnectivityStateName(state)},
}},
{"target", target_},
{"state", Json::FromObject({
{"state", Json::FromString(ConnectivityStateName(state))},
})},
{"target", Json::FromString(target_)},
};
// Fill in the channel trace if applicable
Json trace_json = trace_.RenderJson();
if (trace_json.type() != Json::Type::kNull) {
@ -65,11 +65,10 @@ Json SubchannelNode::RenderJson() {
call_counter_.PopulateCallCounts(&data);
// Construct top-level object.
Json::Object object{
{"ref",
Json::Object{
{"subchannelId", std::to_string(uuid())},
}},
{"data", std::move(data)},
{"ref", Json::FromObject({
{"subchannelId", Json::FromString(absl::StrCat(uuid()))},
})},
{"data", Json::FromObject(std::move(data))},
};
// Populate the child socket.
RefCountedPtr<SocketNode> child_socket;
@ -78,14 +77,14 @@ Json SubchannelNode::RenderJson() {
child_socket = child_socket_;
}
if (child_socket != nullptr && child_socket->uuid() != 0) {
object["socketRef"] = Json::Array{
Json::Object{
{"socketId", std::to_string(child_socket->uuid())},
{"name", child_socket->name()},
},
};
object["socketRef"] = Json::FromArray({
Json::FromObject({
{"socketId", Json::FromString(absl::StrCat(child_socket->uuid()))},
{"name", Json::FromString(child_socket->name())},
}),
});
}
return object;
return Json::FromObject(object);
}
} // namespace channelz

@ -190,9 +190,9 @@ class GrpcLbConfig : public LoadBalancingPolicy::Config {
const Json* child_policy_config_json;
auto it = json.object().find("childPolicy");
if (it == json.object().end()) {
child_policy_config_json_tmp = Json::Array{Json::Object{
{"round_robin", Json::Object()},
}};
child_policy_config_json_tmp = Json::FromArray({Json::FromObject({
{"round_robin", Json::FromObject({})},
})});
child_policy_config_json = &child_policy_config_json_tmp;
} else {
child_policy_config_json = &it->second;

@ -780,15 +780,15 @@ absl::optional<Json> InsertOrUpdateChildPolicyField(const std::string& field,
errors->AddError("child policy config is not an object");
} else {
Json::Object child_config = child_config_json.object();
child_config[field] = Json(value);
array.emplace_back(
Json::Object{{child_name, std::move(child_config)}});
child_config[field] = Json::FromString(value);
array.emplace_back(Json::FromObject(
{{child_name, Json::FromObject(std::move(child_config))}}));
}
}
}
}
if (errors->size() != original_num_errors) return absl::nullopt;
return array;
return Json::FromArray(std::move(array));
}
void RlsLb::ChildPolicyWrapper::StartUpdate() {
@ -2472,7 +2472,7 @@ void RlsLbConfig::JsonPostLoad(const Json& json, const JsonArgs&,
// a child policy for a given target.
for (const Json& config : child_policy_config_.array()) {
if (config.object().begin()->first == (*parsed_config)->name()) {
child_policy_config_ = Json::Array{config};
child_policy_config_ = Json::FromArray({config});
break;
}
}

@ -406,59 +406,68 @@ absl::StatusOr<bool> CdsLb::GenerateDiscoveryMechanismForCluster(
return !missing_cluster;
}
Json::Object mechanism = {
{"clusterName", name},
{"max_concurrent_requests", state.update->max_concurrent_requests},
{"clusterName", Json::FromString(name)},
{"max_concurrent_requests",
Json::FromNumber(state.update->max_concurrent_requests)},
};
if (state.update->outlier_detection.has_value()) {
auto& outlier_detection_update = state.update->outlier_detection.value();
Json::Object outlier_detection;
outlier_detection["interval"] =
outlier_detection_update.interval.ToJsonString();
outlier_detection["baseEjectionTime"] =
outlier_detection_update.base_ejection_time.ToJsonString();
outlier_detection["maxEjectionTime"] =
outlier_detection_update.max_ejection_time.ToJsonString();
Json::FromString(outlier_detection_update.interval.ToJsonString());
outlier_detection["baseEjectionTime"] = Json::FromString(
outlier_detection_update.base_ejection_time.ToJsonString());
outlier_detection["maxEjectionTime"] = Json::FromString(
outlier_detection_update.max_ejection_time.ToJsonString());
outlier_detection["maxEjectionPercent"] =
outlier_detection_update.max_ejection_percent;
Json::FromNumber(outlier_detection_update.max_ejection_percent);
if (outlier_detection_update.success_rate_ejection.has_value()) {
outlier_detection["successRateEjection"] = Json::Object{
outlier_detection["successRateEjection"] = Json::FromObject({
{"stdevFactor",
outlier_detection_update.success_rate_ejection->stdev_factor},
Json::FromNumber(
outlier_detection_update.success_rate_ejection->stdev_factor)},
{"enforcementPercentage",
outlier_detection_update.success_rate_ejection
->enforcement_percentage},
Json::FromNumber(outlier_detection_update.success_rate_ejection
->enforcement_percentage)},
{"minimumHosts",
outlier_detection_update.success_rate_ejection->minimum_hosts},
Json::FromNumber(
outlier_detection_update.success_rate_ejection->minimum_hosts)},
{"requestVolume",
outlier_detection_update.success_rate_ejection->request_volume},
};
Json::FromNumber(
outlier_detection_update.success_rate_ejection->request_volume)},
});
}
if (outlier_detection_update.failure_percentage_ejection.has_value()) {
outlier_detection["failurePercentageEjection"] = Json::Object{
outlier_detection["failurePercentageEjection"] = Json::FromObject({
{"threshold",
outlier_detection_update.failure_percentage_ejection->threshold},
Json::FromNumber(outlier_detection_update
.failure_percentage_ejection->threshold)},
{"enforcementPercentage",
outlier_detection_update.failure_percentage_ejection
->enforcement_percentage},
Json::FromNumber(
outlier_detection_update.failure_percentage_ejection
->enforcement_percentage)},
{"minimumHosts",
outlier_detection_update.failure_percentage_ejection->minimum_hosts},
{"requestVolume", outlier_detection_update
.failure_percentage_ejection->request_volume},
};
Json::FromNumber(outlier_detection_update
.failure_percentage_ejection->minimum_hosts)},
{"requestVolume",
Json::FromNumber(outlier_detection_update
.failure_percentage_ejection->request_volume)},
});
}
mechanism["outlierDetection"] = std::move(outlier_detection);
mechanism["outlierDetection"] =
Json::FromObject(std::move(outlier_detection));
}
Match(
state.update->type,
[&](const XdsClusterResource::Eds& eds) {
mechanism["type"] = "EDS";
mechanism["type"] = Json::FromString("EDS");
if (!eds.eds_service_name.empty()) {
mechanism["edsServiceName"] = eds.eds_service_name;
mechanism["edsServiceName"] = Json::FromString(eds.eds_service_name);
}
},
[&](const XdsClusterResource::LogicalDns& logical_dns) {
mechanism["type"] = "LOGICAL_DNS";
mechanism["dnsHostname"] = logical_dns.hostname;
mechanism["type"] = Json::FromString("LOGICAL_DNS");
mechanism["dnsHostname"] = Json::FromString(logical_dns.hostname);
},
[&](const XdsClusterResource::Aggregate&) { GPR_ASSERT(0); });
if (state.update->lrs_load_reporting_server.has_value()) {
@ -468,11 +477,11 @@ absl::StatusOr<bool> CdsLb::GenerateDiscoveryMechanismForCluster(
if (!state.update->override_host_statuses.empty()) {
Json::Array status_list;
for (const auto& status : state.update->override_host_statuses) {
status_list.emplace_back(status.ToString());
status_list.emplace_back(Json::FromString(status.ToString()));
}
mechanism["overrideHostStatus"] = std::move(status_list);
mechanism["overrideHostStatus"] = Json::FromArray(std::move(status_list));
}
discovery_mechanisms->emplace_back(std::move(mechanism));
discovery_mechanisms->emplace_back(Json::FromObject(std::move(mechanism)));
return true;
}
@ -514,15 +523,17 @@ void CdsLb::OnClusterChanged(const std::string& name,
auto it = watchers_.find(config_->cluster());
GPR_ASSERT(it != watchers_.end());
// Construct config for child policy.
Json json = Json::Array{
Json::Object{
Json json = Json::FromArray({
Json::FromObject({
{"xds_cluster_resolver_experimental",
Json::Object{
{"xdsLbPolicy", it->second.update->lb_policy_config},
{"discoveryMechanisms", std::move(discovery_mechanisms)},
}},
},
};
Json::FromObject({
{"xdsLbPolicy",
Json::FromArray(it->second.update->lb_policy_config)},
{"discoveryMechanisms",
Json::FromArray(std::move(discovery_mechanisms))},
})},
}),
});
if (GRPC_TRACE_FLAG_ENABLED(grpc_cds_lb_trace)) {
gpr_log(GPR_INFO, "[cdslb %p] generated config for child policy: %s",
this, JsonDump(json, /*indent=*/1).c_str());

@ -308,10 +308,10 @@ class XdsClusterResolverLb : public LoadBalancingPolicy {
void Start() override;
void Orphan() override;
Json::Array override_child_policy() override {
return Json::Array{
Json::Object{
{"pick_first", Json::Object()},
},
return {
Json::FromObject({
{"pick_first", Json::FromObject({})},
}),
};
}
bool disable_reresolution() override { return false; };
@ -878,8 +878,8 @@ XdsClusterResolverLb::CreateChildPolicyConfigLocked() {
Json child_policy;
if (!discovery_entry.discovery_mechanism->override_child_policy()
.empty()) {
child_policy =
discovery_entry.discovery_mechanism->override_child_policy();
child_policy = Json::FromArray(
discovery_entry.discovery_mechanism->override_child_policy());
} else {
child_policy = config_->xds_lb_policy();
}
@ -889,32 +889,34 @@ XdsClusterResolverLb::CreateChildPolicyConfigLocked() {
};
if (!discovery_config.override_host_statuses.empty()) {
xds_override_host_lb_config["overrideHostStatus"] =
discovery_config.override_host_statuses;
Json::FromArray(discovery_config.override_host_statuses);
}
Json::Array xds_override_host_config = {Json::Object{
Json::Array xds_override_host_config = {Json::FromObject({
{"xds_override_host_experimental",
std::move(xds_override_host_lb_config)},
}};
Json::FromObject(std::move(xds_override_host_lb_config))},
})};
// Wrap it in the xds_cluster_impl policy.
Json::Array drop_categories;
if (discovery_entry.latest_update->drop_config != nullptr) {
for (const auto& category :
discovery_entry.latest_update->drop_config->drop_category_list()) {
drop_categories.push_back(Json::Object{
{"category", category.name},
{"requests_per_million", category.parts_per_million},
});
drop_categories.push_back(Json::FromObject({
{"category", Json::FromString(category.name)},
{"requests_per_million",
Json::FromNumber(category.parts_per_million)},
}));
}
}
Json::Object xds_cluster_impl_config = {
{"clusterName", discovery_config.cluster_name},
{"childPolicy", std::move(xds_override_host_config)},
{"dropCategories", std::move(drop_categories)},
{"maxConcurrentRequests", discovery_config.max_concurrent_requests},
{"clusterName", Json::FromString(discovery_config.cluster_name)},
{"childPolicy", Json::FromArray(std::move(xds_override_host_config))},
{"dropCategories", Json::FromArray(std::move(drop_categories))},
{"maxConcurrentRequests",
Json::FromNumber(discovery_config.max_concurrent_requests)},
};
if (!discovery_config.eds_service_name.empty()) {
xds_cluster_impl_config["edsServiceName"] =
discovery_config.eds_service_name;
Json::FromString(discovery_config.eds_service_name);
}
if (discovery_config.lrs_load_reporting_server.has_value()) {
xds_cluster_impl_config["lrsLoadReportingServer"] =
@ -926,32 +928,34 @@ XdsClusterResolverLb::CreateChildPolicyConfigLocked() {
outlier_detection_config =
discovery_entry.config().outlier_detection_lb_config.value();
}
outlier_detection_config["childPolicy"] = Json::Array{Json::Object{
{"xds_cluster_impl_experimental", std::move(xds_cluster_impl_config)},
}};
Json locality_picking_policy = Json::Array{Json::Object{
outlier_detection_config["childPolicy"] =
Json::FromArray({Json::FromObject({
{"xds_cluster_impl_experimental",
Json::FromObject(std::move(xds_cluster_impl_config))},
})});
Json locality_picking_policy = Json::FromArray({Json::FromObject({
{"outlier_detection_experimental",
std::move(outlier_detection_config)},
}};
Json::FromObject(std::move(outlier_detection_config))},
})});
// Add priority entry, with the appropriate child name.
std::string child_name = discovery_entry.GetChildPolicyName(priority);
priority_priorities.emplace_back(child_name);
priority_priorities.emplace_back(Json::FromString(child_name));
Json::Object child_config = {
{"config", std::move(locality_picking_policy)},
};
if (discovery_entry.discovery_mechanism->disable_reresolution()) {
child_config["ignore_reresolution_requests"] = true;
child_config["ignore_reresolution_requests"] = Json::FromBool(true);
}
priority_children[child_name] = std::move(child_config);
priority_children[child_name] = Json::FromObject(std::move(child_config));
}
}
Json json = Json::Array{Json::Object{
Json json = Json::FromArray({Json::FromObject({
{"priority_experimental",
Json::Object{
{"children", std::move(priority_children)},
{"priorities", std::move(priority_priorities)},
}},
}};
Json::FromObject({
{"children", Json::FromObject(std::move(priority_children))},
{"priorities", Json::FromArray(std::move(priority_priorities))},
})},
})});
if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_xds_cluster_resolver_trace)) {
gpr_log(
GPR_INFO,

@ -211,19 +211,19 @@ absl::Status XdsWrrLocalityLb::UpdateLocked(UpdateArgs args) {
const std::string& locality_name = p.first;
uint32_t weight = p.second;
// Add weighted target entry.
weighted_targets[locality_name] = Json::Object{
{"weight", weight},
weighted_targets[locality_name] = Json::FromObject({
{"weight", Json::FromNumber(weight)},
{"childPolicy", config->child_config()},
};
});
}
Json child_config_json = Json::Array{
Json::Object{
Json child_config_json = Json::FromArray({
Json::FromObject({
{"weighted_target_experimental",
Json::Object{
{"targets", std::move(weighted_targets)},
}},
},
};
Json::FromObject({
{"targets", Json::FromObject(std::move(weighted_targets))},
})},
}),
});
if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_wrr_locality_lb_trace)) {
gpr_log(GPR_INFO,
"[xds_wrr_locality_lb %p] generated child policy config: %s", this,

@ -88,7 +88,7 @@ absl::StatusOr<std::string> ChooseServiceConfig(
continue;
}
}
return JsonDump(choice.service_config);
return JsonDump(Json::FromObject(choice.service_config));
}
// No matching service config was found
return "";

@ -219,17 +219,17 @@ void GoogleCloud2ProdResolver::StartXdsResolver() {
std::mt19937 mt(rd());
std::uniform_int_distribution<uint64_t> dist(1, UINT64_MAX);
Json::Object node = {
{"id", absl::StrCat("C2P-", dist(mt))},
{"id", Json::FromString(absl::StrCat("C2P-", dist(mt)))},
};
if (!zone_->empty()) {
node["locality"] = Json::Object{
{"zone", *zone_},
};
node["locality"] = Json::FromObject({
{"zone", Json::FromString(*zone_)},
});
};
if (*supports_ipv6_) {
node["metadata"] = Json::Object{
{"TRAFFICDIRECTOR_DIRECTPATH_C2P_IPV6_CAPABLE", true},
};
node["metadata"] = Json::FromObject({
{"TRAFFICDIRECTOR_DIRECTPATH_C2P_IPV6_CAPABLE", Json::FromBool(true)},
});
}
// Allow the TD server uri to be overridden for testing purposes.
auto override_server =
@ -238,29 +238,28 @@ void GoogleCloud2ProdResolver::StartXdsResolver() {
override_server.has_value() && !override_server->empty()
? override_server->c_str()
: "directpath-pa.googleapis.com";
Json xds_server = Json::Array{
Json::Object{
{"server_uri", server_uri},
Json xds_server = Json::FromArray({
Json::FromObject({
{"server_uri", Json::FromString(server_uri)},
{"channel_creds",
Json::Array{
Json::Object{
{"type", "google_default"},
},
}},
{"server_features", Json::Array{"xds_v3"}},
},
};
Json bootstrap = Json::Object{
Json::FromArray({
Json::FromObject({
{"type", Json::FromString("google_default")},
}),
})},
{"server_features", Json::FromArray({Json::FromString("xds_v3")})},
}),
});
Json bootstrap = Json::FromObject({
{"xds_servers", xds_server},
{"authorities",
Json::Object{
{kC2PAuthority,
Json::Object{
{"xds_servers", std::move(xds_server)},
}},
}},
{"node", std::move(node)},
};
Json::FromObject({
{kC2PAuthority, Json::FromObject({
{"xds_servers", std::move(xds_server)},
})},
})},
{"node", Json::FromObject(std::move(node))},
});
// Inject bootstrap JSON as fallback config.
internal::SetXdsFallbackBootstrapConfig(JsonDump(bootstrap).c_str());
// Now start xDS resolver.

@ -76,8 +76,8 @@ void CertificateProviderStore::PluginDefinition::JsonPostLoad(
if (factory == nullptr) return;
// Use plugin to validate and parse config.
grpc_error_handle parse_error;
config =
factory->CreateCertificateProviderConfig(config_json, &parse_error);
config = factory->CreateCertificateProviderConfig(
Json::FromObject(std::move(config_json)), &parse_error);
if (!parse_error.ok()) {
errors->AddError(StatusToString(parse_error));
}

@ -114,11 +114,8 @@ void PopulateMetadataValue(const XdsApiContext& context,
google_protobuf_Value_set_string_value(
value_pb, StdStringToUpbString(value.string()));
break;
case Json::Type::kTrue:
google_protobuf_Value_set_bool_value(value_pb, true);
break;
case Json::Type::kFalse:
google_protobuf_Value_set_bool_value(value_pb, false);
case Json::Type::kBoolean:
google_protobuf_Value_set_bool_value(value_pb, value.boolean());
break;
case Json::Type::kObject: {
google_protobuf_Struct* struct_value =

@ -40,7 +40,7 @@ class StdoutLoggerConfigFactory : public XdsAuditLoggerRegistry::ConfigFactory {
const XdsResourceType::DecodeContext& /*context*/,
absl::string_view /*configuration*/,
ValidationErrors* /*errors*/) override {
return Json::Object{{"stdout_logger", Json::Object()}};
return Json::Object{{"stdout_logger", Json::FromObject({})}};
}
absl::string_view type() override { return Type(); }
@ -85,8 +85,9 @@ Json XdsAuditLoggerRegistry::ConvertXdsAuditLoggerConfig(
audit_logger_config_factories_.find(extension->type);
if (config_factory_it != audit_logger_config_factories_.end()) {
// TODO(lwge): Parse the config with the gRPC audit logger registry.
return config_factory_it->second->ConvertXdsAuditLoggerConfig(
context, *serialized_value, errors);
return Json::FromObject(
config_factory_it->second->ConvertXdsAuditLoggerConfig(
context, *serialized_value, errors));
}
}
// TODO(lwge): Check for third-party audit logger type. For now, we disallow

@ -139,7 +139,7 @@ void GrpcXdsBootstrap::GrpcXdsServer::JsonPostLoad(const Json& json,
CoreConfiguration::Get().channel_creds_registry().IsSupported(
creds.type)) {
if (!CoreConfiguration::Get().channel_creds_registry().IsValidConfig(
creds.type, creds.config)) {
creds.type, Json::FromObject(creds.config))) {
errors->AddError(absl::StrCat(
"invalid config for channel creds type \"", creds.type, "\""));
continue;
@ -173,22 +173,25 @@ void GrpcXdsBootstrap::GrpcXdsServer::JsonPostLoad(const Json& json,
}
Json GrpcXdsBootstrap::GrpcXdsServer::ToJson() const {
Json::Object channel_creds_json{{"type", channel_creds_.type}};
Json::Object channel_creds_json{
{"type", Json::FromString(channel_creds_.type)},
};
if (!channel_creds_.config.empty()) {
channel_creds_json["config"] = channel_creds_.config;
channel_creds_json["config"] = Json::FromObject(channel_creds_.config);
}
Json::Object json{
{"server_uri", server_uri_},
{"channel_creds", Json::Array{std::move(channel_creds_json)}},
{"server_uri", Json::FromString(server_uri_)},
{"channel_creds",
Json::FromArray({Json::FromObject(std::move(channel_creds_json))})},
};
if (!server_features_.empty()) {
Json::Array server_features_json;
for (auto& feature : server_features_) {
server_features_json.emplace_back(feature);
server_features_json.emplace_back(Json::FromString(feature));
}
json["server_features"] = std::move(server_features_json);
json["server_features"] = Json::FromArray(std::move(server_features_json));
}
return json;
return Json::FromObject(std::move(json));
}
//
@ -292,7 +295,7 @@ std::string GrpcXdsBootstrap::ToString() const {
"},\n",
node_->id(), node_->cluster(), node_->locality_region(),
node_->locality_zone(), node_->locality_sub_zone(),
JsonDump(Json{node_->metadata()})));
JsonDump(Json::FromObject(node_->metadata()))));
}
parts.push_back(
absl::StrFormat("servers=[\n%s\n],\n", JsonDump(servers_[0].ToJson())));

@ -102,8 +102,8 @@ std::string XdsClusterResource::ToString() const {
"prioritized_cluster_names=[",
absl::StrJoin(aggregate.prioritized_cluster_names, ", "), "]"));
});
contents.push_back(
absl::StrCat("lb_policy_config=", JsonDump(Json{lb_policy_config})));
contents.push_back(absl::StrCat("lb_policy_config=",
JsonDump(Json::FromArray(lb_policy_config))));
if (lrs_load_reporting_server.has_value()) {
contents.push_back(absl::StrCat("lrs_load_reporting_server_name=",
lrs_load_reporting_server->server_uri()));
@ -329,7 +329,8 @@ void ParseLbPolicyConfig(const XdsResourceType::DecodeContext& context,
if (original_error_count == errors->size()) {
auto config = CoreConfiguration::Get()
.lb_policy_registry()
.ParseLoadBalancingConfig(cds_update->lb_policy_config);
.ParseLoadBalancingConfig(
Json::FromArray(cds_update->lb_policy_config));
if (!config.ok()) errors->AddError(config.status().message());
}
return;
@ -339,17 +340,16 @@ void ParseLbPolicyConfig(const XdsResourceType::DecodeContext& context,
if (envoy_config_cluster_v3_Cluster_lb_policy(cluster) ==
envoy_config_cluster_v3_Cluster_ROUND_ROBIN) {
cds_update->lb_policy_config = {
Json::Object{
Json::FromObject({
{"xds_wrr_locality_experimental",
Json::Object{
{"childPolicy",
Json::Array{
Json::Object{
{"round_robin", Json::Object()},
},
}},
}},
},
Json::FromObject({
{"childPolicy", Json::FromArray({
Json::FromObject({
{"round_robin", Json::FromObject({})},
}),
})},
})},
}),
};
} else if (envoy_config_cluster_v3_Cluster_lb_policy(cluster) ==
envoy_config_cluster_v3_Cluster_RING_HASH) {
@ -391,13 +391,13 @@ void ParseLbPolicyConfig(const XdsResourceType::DecodeContext& context,
}
}
cds_update->lb_policy_config = {
Json::Object{
Json::FromObject({
{"ring_hash_experimental",
Json::Object{
{"minRingSize", min_ring_size},
{"maxRingSize", max_ring_size},
}},
},
Json::FromObject({
{"minRingSize", Json::FromNumber(min_ring_size)},
{"maxRingSize", Json::FromNumber(max_ring_size)},
})},
}),
};
} else {
ValidationErrors::ScopedField field(errors, ".lb_policy");

@ -91,14 +91,16 @@ Json XdsRouteLookupClusterSpecifierPlugin::GenerateLoadBalancingPolicyConfig(
reinterpret_cast<char*>(buf), json_size + 1, status.ptr());
auto json = JsonParse(reinterpret_cast<char*>(buf));
GPR_ASSERT(json.ok());
return Json::Array{Json::Object{
{"rls_experimental",
Json::Object{
{"routeLookupConfig", std::move(*json)},
{"childPolicy",
Json::Array{Json::Object{{"cds_experimental", Json::Object()}}}},
{"childPolicyConfigTargetFieldName", "cluster"},
}}}};
return Json::FromArray({Json::FromObject(
{{"rls_experimental",
Json::FromObject({
{"routeLookupConfig", std::move(*json)},
{"childPolicy",
Json::FromArray({
Json::FromObject({{"cds_experimental", Json::FromObject({})}}),
})},
{"childPolicyConfigTargetFieldName", Json::FromString("cluster")},
})}})});
}
//

@ -486,7 +486,7 @@ absl::optional<XdsExtension> ExtractXdsExtension(
errors, absl::StrCat(".value[", extension.type, "]"));
auto* protobuf_struct = xds_type_v3_TypedStruct_value(typed_struct);
if (protobuf_struct == nullptr) {
extension.value = Json::Object(); // Default to empty object.
extension.value = Json::FromObject({}); // Default to empty object.
} else {
auto json = ParseProtobufStructToJson(context, protobuf_struct);
if (!json.ok()) {

@ -139,14 +139,14 @@ XdsHttpFaultFilter::GenerateFilterConfig(
}
// Set the abort_code, even if it's OK
fault_injection_policy_json["abortCode"] =
grpc_status_code_to_string(abort_grpc_status_code);
Json::FromString(grpc_status_code_to_string(abort_grpc_status_code));
// Set the headers if we enabled header abort injection control
if (envoy_extensions_filters_http_fault_v3_FaultAbort_has_header_abort(
fault_abort)) {
fault_injection_policy_json["abortCodeHeader"] =
"x-envoy-fault-abort-grpc-request";
Json::FromString("x-envoy-fault-abort-grpc-request");
fault_injection_policy_json["abortPercentageHeader"] =
"x-envoy-fault-abort-percentage";
Json::FromString("x-envoy-fault-abort-percentage");
}
// Set the fraction percent
auto* percent =
@ -154,9 +154,9 @@ XdsHttpFaultFilter::GenerateFilterConfig(
fault_abort);
if (percent != nullptr) {
fault_injection_policy_json["abortPercentageNumerator"] =
envoy_type_v3_FractionalPercent_numerator(percent);
Json::FromNumber(envoy_type_v3_FractionalPercent_numerator(percent));
fault_injection_policy_json["abortPercentageDenominator"] =
GetDenominator(percent);
Json::FromNumber(GetDenominator(percent));
}
}
// Section 2: Parse the delay injection config
@ -171,15 +171,16 @@ XdsHttpFaultFilter::GenerateFilterConfig(
if (delay_duration != nullptr) {
ValidationErrors::ScopedField field(errors, ".fixed_delay");
Duration duration = ParseDuration(delay_duration, errors);
fault_injection_policy_json["delay"] = duration.ToJsonString();
fault_injection_policy_json["delay"] =
Json::FromString(duration.ToJsonString());
}
// Set the headers if we enabled header delay injection control
if (envoy_extensions_filters_common_fault_v3_FaultDelay_has_header_delay(
fault_delay)) {
fault_injection_policy_json["delayHeader"] =
"x-envoy-fault-delay-request";
Json::FromString("x-envoy-fault-delay-request");
fault_injection_policy_json["delayPercentageHeader"] =
"x-envoy-fault-delay-request-percentage";
Json::FromString("x-envoy-fault-delay-request-percentage");
}
// Set the fraction percent
auto* percent =
@ -187,9 +188,9 @@ XdsHttpFaultFilter::GenerateFilterConfig(
fault_delay);
if (percent != nullptr) {
fault_injection_policy_json["delayPercentageNumerator"] =
envoy_type_v3_FractionalPercent_numerator(percent);
Json::FromNumber(envoy_type_v3_FractionalPercent_numerator(percent));
fault_injection_policy_json["delayPercentageDenominator"] =
GetDenominator(percent);
Json::FromNumber(GetDenominator(percent));
}
}
// Section 3: Parse the maximum active faults
@ -198,10 +199,10 @@ XdsHttpFaultFilter::GenerateFilterConfig(
http_fault);
if (max_fault_wrapper != nullptr) {
fault_injection_policy_json["maxFaults"] =
google_protobuf_UInt32Value_value(max_fault_wrapper);
Json::FromNumber(google_protobuf_UInt32Value_value(max_fault_wrapper));
}
return FilterConfig{ConfigProtoName(),
std::move(fault_injection_policy_json)};
Json::FromObject(std::move(fault_injection_policy_json))};
}
absl::optional<XdsHttpFilterImpl::FilterConfig>

@ -19,9 +19,9 @@
#include "src/core/ext/xds/xds_http_rbac_filter.h"
#include <stddef.h>
#include <stdint.h>
#include <algorithm>
#include <cstdint>
#include <string>
#include <utility>
@ -58,14 +58,16 @@ namespace {
Json ParseRegexMatcherToJson(
const envoy_type_matcher_v3_RegexMatcher* regex_matcher) {
return Json::Object(
{{"regex", UpbStringToStdString(envoy_type_matcher_v3_RegexMatcher_regex(
regex_matcher))}});
return Json::FromObject(
{{"regex",
Json::FromString(UpbStringToStdString(
envoy_type_matcher_v3_RegexMatcher_regex(regex_matcher)))}});
}
Json ParseInt64RangeToJson(const envoy_type_v3_Int64Range* range) {
return Json::Object{{"start", envoy_type_v3_Int64Range_start(range)},
{"end", envoy_type_v3_Int64Range_end(range)}};
return Json::FromObject(
{{"start", Json::FromNumber(envoy_type_v3_Int64Range_start(range))},
{"end", Json::FromNumber(envoy_type_v3_Int64Range_end(range))}});
}
Json ParseHeaderMatcherToJson(const envoy_config_route_v3_HeaderMatcher* header,
@ -80,13 +82,13 @@ Json ParseHeaderMatcherToJson(const envoy_config_route_v3_HeaderMatcher* header,
} else if (absl::StartsWith(name, "grpc-")) {
errors->AddError("'grpc-' prefixes not allowed in header");
}
header_json.emplace("name", std::move(name));
header_json.emplace("name", Json::FromString(std::move(name)));
}
if (envoy_config_route_v3_HeaderMatcher_has_exact_match(header)) {
header_json.emplace(
"exactMatch",
UpbStringToStdString(
envoy_config_route_v3_HeaderMatcher_exact_match(header)));
Json::FromString(UpbStringToStdString(
envoy_config_route_v3_HeaderMatcher_exact_match(header))));
} else if (envoy_config_route_v3_HeaderMatcher_has_safe_regex_match(header)) {
header_json.emplace(
"safeRegexMatch",
@ -100,28 +102,30 @@ Json ParseHeaderMatcherToJson(const envoy_config_route_v3_HeaderMatcher* header,
} else if (envoy_config_route_v3_HeaderMatcher_has_present_match(header)) {
header_json.emplace(
"presentMatch",
envoy_config_route_v3_HeaderMatcher_present_match(header));
Json::FromBool(
envoy_config_route_v3_HeaderMatcher_present_match(header)));
} else if (envoy_config_route_v3_HeaderMatcher_has_prefix_match(header)) {
header_json.emplace(
"prefixMatch",
UpbStringToStdString(
envoy_config_route_v3_HeaderMatcher_prefix_match(header)));
Json::FromString(UpbStringToStdString(
envoy_config_route_v3_HeaderMatcher_prefix_match(header))));
} else if (envoy_config_route_v3_HeaderMatcher_has_suffix_match(header)) {
header_json.emplace(
"suffixMatch",
UpbStringToStdString(
envoy_config_route_v3_HeaderMatcher_suffix_match(header)));
Json::FromString(UpbStringToStdString(
envoy_config_route_v3_HeaderMatcher_suffix_match(header))));
} else if (envoy_config_route_v3_HeaderMatcher_has_contains_match(header)) {
header_json.emplace(
"containsMatch",
UpbStringToStdString(
envoy_config_route_v3_HeaderMatcher_contains_match(header)));
Json::FromString(UpbStringToStdString(
envoy_config_route_v3_HeaderMatcher_contains_match(header))));
} else {
errors->AddError("invalid route header matcher specified");
}
header_json.emplace("invertMatch",
envoy_config_route_v3_HeaderMatcher_invert_match(header));
return header_json;
header_json.emplace(
"invertMatch",
Json::FromBool(envoy_config_route_v3_HeaderMatcher_invert_match(header)));
return Json::FromObject(std::move(header_json));
}
Json ParseStringMatcherToJson(
@ -130,30 +134,31 @@ Json ParseStringMatcherToJson(
Json::Object json;
if (envoy_type_matcher_v3_StringMatcher_has_exact(matcher)) {
json.emplace("exact",
UpbStringToStdString(
envoy_type_matcher_v3_StringMatcher_exact(matcher)));
Json::FromString(UpbStringToStdString(
envoy_type_matcher_v3_StringMatcher_exact(matcher))));
} else if (envoy_type_matcher_v3_StringMatcher_has_prefix(matcher)) {
json.emplace("prefix",
UpbStringToStdString(
envoy_type_matcher_v3_StringMatcher_prefix(matcher)));
Json::FromString(UpbStringToStdString(
envoy_type_matcher_v3_StringMatcher_prefix(matcher))));
} else if (envoy_type_matcher_v3_StringMatcher_has_suffix(matcher)) {
json.emplace("suffix",
UpbStringToStdString(
envoy_type_matcher_v3_StringMatcher_suffix(matcher)));
Json::FromString(UpbStringToStdString(
envoy_type_matcher_v3_StringMatcher_suffix(matcher))));
} else if (envoy_type_matcher_v3_StringMatcher_has_safe_regex(matcher)) {
json.emplace("safeRegex",
ParseRegexMatcherToJson(
envoy_type_matcher_v3_StringMatcher_safe_regex(matcher)));
} else if (envoy_type_matcher_v3_StringMatcher_has_contains(matcher)) {
json.emplace("contains",
UpbStringToStdString(
envoy_type_matcher_v3_StringMatcher_contains(matcher)));
Json::FromString(UpbStringToStdString(
envoy_type_matcher_v3_StringMatcher_contains(matcher))));
} else {
errors->AddError("invalid match pattern");
}
json.emplace("ignoreCase",
envoy_type_matcher_v3_StringMatcher_ignore_case(matcher));
return json;
json.emplace(
"ignoreCase",
Json::FromBool(envoy_type_matcher_v3_StringMatcher_ignore_case(matcher)));
return Json::FromObject(std::move(json));
}
Json ParsePathMatcherToJson(const envoy_type_matcher_v3_PathMatcher* matcher,
@ -165,30 +170,32 @@ Json ParsePathMatcherToJson(const envoy_type_matcher_v3_PathMatcher* matcher,
return Json();
}
Json path_json = ParseStringMatcherToJson(path, errors);
return Json::Object{{"path", std::move(path_json)}};
return Json::FromObject({{"path", std::move(path_json)}});
}
Json ParseCidrRangeToJson(const envoy_config_core_v3_CidrRange* range) {
Json::Object json;
json.emplace("addressPrefix",
UpbStringToStdString(
envoy_config_core_v3_CidrRange_address_prefix(range)));
Json::FromString(UpbStringToStdString(
envoy_config_core_v3_CidrRange_address_prefix(range))));
const auto* prefix_len = envoy_config_core_v3_CidrRange_prefix_len(range);
if (prefix_len != nullptr) {
json.emplace("prefixLen", google_protobuf_UInt32Value_value(prefix_len));
json.emplace(
"prefixLen",
Json::FromNumber(google_protobuf_UInt32Value_value(prefix_len)));
}
return json;
return Json::FromObject(std::move(json));
}
Json ParseMetadataMatcherToJson(
const envoy_type_matcher_v3_MetadataMatcher* metadata_matcher) {
Json::Object json;
// The fields "filter", "path" and "value" are irrelevant to gRPC as per
// https://github.com/grpc/proposal/blob/master/A41-xds-rbac.md and are not
// being parsed.
json.emplace("invert",
envoy_type_matcher_v3_MetadataMatcher_invert(metadata_matcher));
return json;
return Json::FromObject({
{"invert", Json::FromBool(envoy_type_matcher_v3_MetadataMatcher_invert(
metadata_matcher))},
});
}
Json ParsePermissionToJson(const envoy_config_rbac_v3_Permission* permission,
@ -208,7 +215,8 @@ Json ParsePermissionToJson(const envoy_config_rbac_v3_Permission* permission,
Json permission_json = ParsePermissionToJson(rules[i], errors);
rules_json.emplace_back(std::move(permission_json));
}
return Json::Object({{"rules", std::move(rules_json)}});
return Json::FromObject(
{{"rules", Json::FromArray(std::move(rules_json))}});
};
if (envoy_config_rbac_v3_Permission_has_and_rules(permission)) {
ValidationErrors::ScopedField field(errors, ".and_permission");
@ -222,8 +230,8 @@ Json ParsePermissionToJson(const envoy_config_rbac_v3_Permission* permission,
Json permission_set_json = parse_permission_set_to_json(or_rules);
permission_json.emplace("orRules", std::move(permission_set_json));
} else if (envoy_config_rbac_v3_Permission_has_any(permission)) {
permission_json.emplace("any",
envoy_config_rbac_v3_Permission_any(permission));
permission_json.emplace(
"any", Json::FromBool(envoy_config_rbac_v3_Permission_any(permission)));
} else if (envoy_config_rbac_v3_Permission_has_header(permission)) {
ValidationErrors::ScopedField field(errors, ".header");
Json header_json = ParseHeaderMatcherToJson(
@ -242,7 +250,8 @@ Json ParsePermissionToJson(const envoy_config_rbac_v3_Permission* permission,
} else if (envoy_config_rbac_v3_Permission_has_destination_port(permission)) {
permission_json.emplace(
"destinationPort",
envoy_config_rbac_v3_Permission_destination_port(permission));
Json::FromNumber(
envoy_config_rbac_v3_Permission_destination_port(permission)));
} else if (envoy_config_rbac_v3_Permission_has_metadata(permission)) {
permission_json.emplace(
"metadata", ParseMetadataMatcherToJson(
@ -263,7 +272,7 @@ Json ParsePermissionToJson(const envoy_config_rbac_v3_Permission* permission,
} else {
errors->AddError("invalid rule");
}
return permission_json;
return Json::FromObject(std::move(permission_json));
}
Json ParsePrincipalToJson(const envoy_config_rbac_v3_Principal* principal,
@ -283,7 +292,7 @@ Json ParsePrincipalToJson(const envoy_config_rbac_v3_Principal* principal,
Json principal_json = ParsePrincipalToJson(ids[i], errors);
ids_json.emplace_back(std::move(principal_json));
}
return Json::Object({{"ids", std::move(ids_json)}});
return Json::FromObject({{"ids", Json::FromArray(std::move(ids_json))}});
};
if (envoy_config_rbac_v3_Principal_has_and_ids(principal)) {
ValidationErrors::ScopedField field(errors, ".and_ids");
@ -296,8 +305,8 @@ Json ParsePrincipalToJson(const envoy_config_rbac_v3_Principal* principal,
Json principal_set_json = parse_principal_set_to_json(or_rules);
principal_json.emplace("orIds", std::move(principal_set_json));
} else if (envoy_config_rbac_v3_Principal_has_any(principal)) {
principal_json.emplace("any",
envoy_config_rbac_v3_Principal_any(principal));
principal_json.emplace(
"any", Json::FromBool(envoy_config_rbac_v3_Principal_any(principal)));
} else if (envoy_config_rbac_v3_Principal_has_authenticated(principal)) {
Json::Object authenticated_json;
const auto* principal_name =
@ -310,7 +319,8 @@ Json ParsePrincipalToJson(const envoy_config_rbac_v3_Principal* principal,
ParseStringMatcherToJson(principal_name, errors);
authenticated_json["principalName"] = std::move(principal_name_json);
}
principal_json["authenticated"] = std::move(authenticated_json);
principal_json["authenticated"] =
Json::FromObject(std::move(authenticated_json));
} else if (envoy_config_rbac_v3_Principal_has_source_ip(principal)) {
principal_json.emplace(
"sourceIp", ParseCidrRangeToJson(
@ -346,7 +356,7 @@ Json ParsePrincipalToJson(const envoy_config_rbac_v3_Principal* principal,
} else {
errors->AddError("invalid rule");
}
return principal_json;
return Json::FromObject(std::move(principal_json));
}
Json ParsePolicyToJson(const envoy_config_rbac_v3_Policy* policy,
@ -362,7 +372,8 @@ Json ParsePolicyToJson(const envoy_config_rbac_v3_Policy* policy,
Json permission_json = ParsePermissionToJson(permissions[i], errors);
permissions_json.emplace_back(std::move(permission_json));
}
policy_json.emplace("permissions", std::move(permissions_json));
policy_json.emplace("permissions",
Json::FromArray(std::move(permissions_json)));
Json::Array principals_json;
const envoy_config_rbac_v3_Principal* const* principals =
envoy_config_rbac_v3_Policy_principals(policy, &size);
@ -372,7 +383,8 @@ Json ParsePolicyToJson(const envoy_config_rbac_v3_Policy* policy,
Json principal_json = ParsePrincipalToJson(principals[i], errors);
principals_json.emplace_back(std::move(principal_json));
}
policy_json.emplace("principals", std::move(principals_json));
policy_json.emplace("principals",
Json::FromArray(std::move(principals_json)));
if (envoy_config_rbac_v3_Policy_has_condition(policy)) {
ValidationErrors::ScopedField field(errors, ".condition");
errors->AddError("condition not supported");
@ -381,7 +393,7 @@ Json ParsePolicyToJson(const envoy_config_rbac_v3_Policy* policy,
ValidationErrors::ScopedField field(errors, ".checked_condition");
errors->AddError("checked condition not supported");
}
return policy_json;
return Json::FromObject(std::move(policy_json));
}
Json ParseAuditLoggerConfigsToJson(
@ -403,7 +415,7 @@ Json ParseAuditLoggerConfigsToJson(
logger_configs_json.emplace_back(registry.ConvertXdsAuditLoggerConfig(
context, logger_configs[i], errors));
}
return logger_configs_json;
return Json::FromArray(logger_configs_json);
}
Json ParseHttpRbacToJson(const XdsResourceType::DecodeContext& context,
@ -416,10 +428,11 @@ Json ParseHttpRbacToJson(const XdsResourceType::DecodeContext& context,
int action = envoy_config_rbac_v3_RBAC_action(rules);
// Treat Log action as RBAC being absent
if (action == envoy_config_rbac_v3_RBAC_LOG) {
return rbac_json;
return Json::FromObject({});
}
Json::Object inner_rbac_json;
inner_rbac_json.emplace("action", envoy_config_rbac_v3_RBAC_action(rules));
inner_rbac_json.emplace(
"action", Json::FromNumber(envoy_config_rbac_v3_RBAC_action(rules)));
if (envoy_config_rbac_v3_RBAC_policies_size(rules) != 0) {
Json::Object policies_object;
size_t iter = kUpb_Map_Begin;
@ -436,7 +449,8 @@ Json ParseHttpRbacToJson(const XdsResourceType::DecodeContext& context,
envoy_config_rbac_v3_RBAC_PoliciesEntry_value(entry), errors);
policies_object.emplace(std::string(key), std::move(policy));
}
inner_rbac_json.emplace("policies", std::move(policies_object));
inner_rbac_json.emplace("policies",
Json::FromObject(std::move(policies_object)));
}
// Flatten the nested messages defined in rbac.proto
if (envoy_config_rbac_v3_RBAC_has_audit_logging_options(rules)) {
@ -451,7 +465,8 @@ Json ParseHttpRbacToJson(const XdsResourceType::DecodeContext& context,
case envoy_config_rbac_v3_RBAC_AuditLoggingOptions_ON_DENY:
case envoy_config_rbac_v3_RBAC_AuditLoggingOptions_ON_ALLOW:
case envoy_config_rbac_v3_RBAC_AuditLoggingOptions_ON_DENY_AND_ALLOW:
inner_rbac_json.emplace("audit_condition", audit_condition);
inner_rbac_json.emplace("audit_condition",
Json::FromNumber(audit_condition));
break;
default:
ValidationErrors::ScopedField field(errors, ".audit_condition");
@ -464,9 +479,9 @@ Json ParseHttpRbacToJson(const XdsResourceType::DecodeContext& context,
context, audit_logging_options, errors));
}
}
rbac_json.emplace("rules", std::move(inner_rbac_json));
rbac_json.emplace("rules", Json::FromObject(std::move(inner_rbac_json)));
}
return rbac_json;
return Json::FromObject(std::move(rbac_json));
}
} // namespace
@ -526,7 +541,7 @@ XdsHttpRbacFilter::GenerateFilterConfigOverride(
const auto* rbac =
envoy_extensions_filters_http_rbac_v3_RBACPerRoute_rbac(rbac_per_route);
if (rbac == nullptr) {
rbac_json = Json::Object();
rbac_json = Json::FromObject({});
} else {
ValidationErrors::ScopedField field(errors, ".rbac");
rbac_json = ParseHttpRbacToJson(context, rbac, errors);
@ -548,13 +563,15 @@ XdsHttpRbacFilter::GenerateServiceConfig(
const FilterConfig& hcm_filter_config,
const FilterConfig* filter_config_override,
absl::string_view filter_name) const {
Json policy_json = filter_config_override != nullptr
? filter_config_override->config
: hcm_filter_config.config;
const Json& policy_json = filter_config_override != nullptr
? filter_config_override->config
: hcm_filter_config.config;
auto json_object = policy_json.object();
json_object.emplace("filter_name", std::string(filter_name));
json_object.emplace("filter_name",
Json::FromString(std::string(filter_name)));
// The policy JSON may be empty other than the filter name, that's allowed.
return ServiceConfigJsonEntry{"rbacPolicy", JsonDump(Json(json_object))};
return ServiceConfigJsonEntry{"rbacPolicy",
JsonDump(Json::FromObject(json_object))};
}
} // namespace grpc_core

@ -119,20 +119,20 @@ Json::Object ValidateStatefulSession(
ValidationErrors::ScopedField field(errors, ".name");
errors->AddError("field not present");
}
cookie_config["name"] = std::move(cookie_name);
cookie_config["name"] = Json::FromString(std::move(cookie_name));
// ttl
{
ValidationErrors::ScopedField field(errors, ".ttl");
const auto* duration = envoy_type_http_v3_Cookie_ttl(cookie);
if (duration != nullptr) {
Duration ttl = ParseDuration(duration, errors);
cookie_config["ttl"] = ttl.ToJsonString();
cookie_config["ttl"] = Json::FromString(ttl.ToJsonString());
}
}
// path
std::string path =
UpbStringToStdString(envoy_type_http_v3_Cookie_path(cookie));
if (!path.empty()) cookie_config["path"] = std::move(path);
if (!path.empty()) cookie_config["path"] = Json::FromString(std::move(path));
return cookie_config;
}
@ -156,9 +156,9 @@ XdsHttpStatefulSessionFilter::GenerateFilterConfig(
errors->AddError("could not parse stateful session filter config");
return absl::nullopt;
}
return FilterConfig{
ConfigProtoName(),
ValidateStatefulSession(context, stateful_session, errors)};
return FilterConfig{ConfigProtoName(),
Json::FromObject(ValidateStatefulSession(
context, stateful_session, errors))};
}
absl::optional<XdsHttpFilterImpl::FilterConfig>
@ -192,7 +192,8 @@ XdsHttpStatefulSessionFilter::GenerateFilterConfigOverride(
config = ValidateStatefulSession(context, stateful_session, errors);
}
}
return FilterConfig{OverrideConfigProtoName(), Json(std::move(config))};
return FilterConfig{OverrideConfigProtoName(),
Json::FromObject(std::move(config))};
}
const grpc_channel_filter* XdsHttpStatefulSessionFilter::channel_filter()
@ -210,9 +211,9 @@ XdsHttpStatefulSessionFilter::GenerateServiceConfig(
const FilterConfig& hcm_filter_config,
const FilterConfig* filter_config_override,
absl::string_view /*filter_name*/) const {
Json config = filter_config_override != nullptr
? filter_config_override->config
: hcm_filter_config.config;
const Json& config = filter_config_override != nullptr
? filter_config_override->config
: hcm_filter_config.config;
return ServiceConfigJsonEntry{"stateful_session", JsonDump(config)};
}

@ -51,7 +51,7 @@ class RoundRobinLbPolicyConfigFactory
const XdsResourceType::DecodeContext& /*context*/,
absl::string_view /*configuration*/, ValidationErrors* /*errors*/,
int /*recursion_depth*/) override {
return Json::Object{{"round_robin", Json::Object()}};
return Json::Object{{"round_robin", Json::FromObject({})}};
}
absl::string_view type() override { return Type(); }
@ -84,7 +84,7 @@ class ClientSideWeightedRoundRobinLbPolicyConfigFactory
resource);
if (enable_oob_load_report != nullptr &&
google_protobuf_BoolValue_value(enable_oob_load_report)) {
config["enableOobLoadReport"] = true;
config["enableOobLoadReport"] = Json::FromBool(true);
}
// oob_reporting_period
auto* duration_proto =
@ -93,7 +93,7 @@ class ClientSideWeightedRoundRobinLbPolicyConfigFactory
if (duration_proto != nullptr) {
ValidationErrors::ScopedField field(errors, ".oob_reporting_period");
Duration duration = ParseDuration(duration_proto, errors);
config["oobReportingPeriod"] = duration.ToJsonString();
config["oobReportingPeriod"] = Json::FromString(duration.ToJsonString());
}
// blackout_period
duration_proto =
@ -102,7 +102,7 @@ class ClientSideWeightedRoundRobinLbPolicyConfigFactory
if (duration_proto != nullptr) {
ValidationErrors::ScopedField field(errors, ".blackout_period");
Duration duration = ParseDuration(duration_proto, errors);
config["blackoutPeriod"] = duration.ToJsonString();
config["blackoutPeriod"] = Json::FromString(duration.ToJsonString());
}
// weight_update_period
duration_proto =
@ -111,7 +111,7 @@ class ClientSideWeightedRoundRobinLbPolicyConfigFactory
if (duration_proto != nullptr) {
ValidationErrors::ScopedField field(errors, ".weight_update_period");
Duration duration = ParseDuration(duration_proto, errors);
config["weightUpdatePeriod"] = duration.ToJsonString();
config["weightUpdatePeriod"] = Json::FromString(duration.ToJsonString());
}
// weight_expiration_period
duration_proto =
@ -120,7 +120,8 @@ class ClientSideWeightedRoundRobinLbPolicyConfigFactory
if (duration_proto != nullptr) {
ValidationErrors::ScopedField field(errors, ".weight_expiration_period");
Duration duration = ParseDuration(duration_proto, errors);
config["weightExpirationPeriod"] = duration.ToJsonString();
config["weightExpirationPeriod"] =
Json::FromString(duration.ToJsonString());
}
// error_utilization_penalty
auto* error_utilization_penalty =
@ -133,9 +134,10 @@ class ClientSideWeightedRoundRobinLbPolicyConfigFactory
if (value < 0.0) {
errors->AddError("value must be non-negative");
}
config["errorUtilizationPenalty"] = value;
config["errorUtilizationPenalty"] = Json::FromNumber(value);
}
return Json::Object{{"weighted_round_robin", std::move(config)}};
return Json::Object{
{"weighted_round_robin", Json::FromObject(std::move(config))}};
}
absl::string_view type() override { return Type(); }
@ -197,10 +199,10 @@ class RingHashLbPolicyConfigFactory
}
return Json::Object{
{"ring_hash_experimental",
Json::Object{
{"minRingSize", min_ring_size},
{"maxRingSize", max_ring_size},
}},
Json::FromObject({
{"minRingSize", Json::FromNumber(min_ring_size)},
{"maxRingSize", Json::FromNumber(max_ring_size)},
})},
};
}
@ -238,7 +240,8 @@ class WrrLocalityLbPolicyConfigFactory
context, endpoint_picking_policy, errors, recursion_depth + 1);
return Json::Object{
{"xds_wrr_locality_experimental",
Json::Object{{"childPolicy", std::move(child_policy)}}}};
Json::FromObject(
{{"childPolicy", Json::FromArray(std::move(child_policy))}})}};
}
absl::string_view type() override { return Type(); }
@ -306,8 +309,9 @@ Json::Array XdsLbPolicyRegistry::ConvertXdsLbPolicyConfig(
if (serialized_value != nullptr) {
auto config_factory_it = policy_config_factories_.find(extension->type);
if (config_factory_it != policy_config_factories_.end()) {
return Json::Array{config_factory_it->second->ConvertXdsLbPolicyConfig(
this, context, *serialized_value, errors, recursion_depth)};
return Json::Array{Json::FromObject(
config_factory_it->second->ConvertXdsLbPolicyConfig(
this, context, *serialized_value, errors, recursion_depth))};
}
}
// Check for custom LB policy type.
@ -316,7 +320,7 @@ Json::Array XdsLbPolicyRegistry::ConvertXdsLbPolicyConfig(
CoreConfiguration::Get().lb_policy_registry().LoadBalancingPolicyExists(
extension->type, nullptr)) {
return Json::Array{
Json::Object{{std::string(extension->type), std::move(*json)}}};
Json::FromObject({{std::string(extension->type), std::move(*json)}})};
}
// Unsupported type. Continue to next entry.
}

@ -47,6 +47,7 @@
#include "src/core/lib/gprpp/time.h"
#include "src/core/lib/iomgr/closure.h"
#include "src/core/lib/iomgr/pollset_set.h"
#include "src/core/lib/json/json.h"
#include "src/core/lib/security/credentials/channel_creds_registry.h"
#include "src/core/lib/security/credentials/credentials.h"
#include "src/core/lib/slice/slice.h"
@ -255,7 +256,8 @@ grpc_channel* CreateXdsChannel(const ChannelArgs& args,
const GrpcXdsBootstrap::GrpcXdsServer& server) {
RefCountedPtr<grpc_channel_credentials> channel_creds =
CoreConfiguration::Get().channel_creds_registry().CreateChannelCreds(
server.channel_creds_type(), server.channel_creds_config());
server.channel_creds_type(),
Json::FromObject(server.channel_creds_config()));
return grpc_channel_create(server.server_uri().c_str(), channel_creds.get(),
args.ToC().get());
}

@ -21,9 +21,10 @@
#include "src/core/lib/channel/channel_trace.h"
#include <algorithm>
#include <string>
#include <utility>
#include "absl/strings/str_cat.h"
#include <grpc/support/alloc.h>
#include "src/core/lib/channel/channelz.h"
@ -140,21 +141,21 @@ const char* severity_string(ChannelTrace::Severity severity) {
Json ChannelTrace::TraceEvent::RenderTraceEvent() const {
char* description = grpc_slice_to_c_string(data_);
Json::Object object = {
{"description", description},
{"severity", severity_string(severity_)},
{"timestamp", gpr_format_timespec(timestamp_)},
{"description", Json::FromString(description)},
{"severity", Json::FromString(severity_string(severity_))},
{"timestamp", Json::FromString(gpr_format_timespec(timestamp_))},
};
gpr_free(description);
if (referenced_entity_ != nullptr) {
const bool is_channel =
(referenced_entity_->type() == BaseNode::EntityType::kTopLevelChannel ||
referenced_entity_->type() == BaseNode::EntityType::kInternalChannel);
object[is_channel ? "channelRef" : "subchannelRef"] = Json::Object{
object[is_channel ? "channelRef" : "subchannelRef"] = Json::FromObject({
{(is_channel ? "channelId" : "subchannelId"),
std::to_string(referenced_entity_->uuid())},
};
Json::FromString(absl::StrCat(referenced_entity_->uuid()))},
});
}
return object;
return Json::FromObject(std::move(object));
}
Json ChannelTrace::RenderJson() const {
@ -163,10 +164,12 @@ Json ChannelTrace::RenderJson() const {
return Json(); // JSON null
}
Json::Object object = {
{"creationTimestamp", gpr_format_timespec(time_created_)},
{"creationTimestamp",
Json::FromString(gpr_format_timespec(time_created_))},
};
if (num_events_logged_ > 0) {
object["numEventsLogged"] = std::to_string(num_events_logged_);
object["numEventsLogged"] =
Json::FromString(absl::StrCat(num_events_logged_));
}
// Only add in the event list if it is non-empty.
if (head_trace_ != nullptr) {
@ -174,9 +177,9 @@ Json ChannelTrace::RenderJson() const {
for (TraceEvent* it = head_trace_; it != nullptr; it = it->next()) {
array.emplace_back(it->RenderTraceEvent());
}
object["events"] = std::move(array);
object["events"] = Json::FromArray(std::move(array));
}
return object;
return Json::FromObject(std::move(object));
}
} // namespace channelz

@ -25,6 +25,7 @@
#include "absl/status/statusor.h"
#include "absl/strings/escaping.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/strip.h"
#include <grpc/support/cpu.h>
@ -116,17 +117,20 @@ void CallCountingHelper::PopulateCallCounts(Json::Object* json) {
CounterData data;
CollectData(&data);
if (data.calls_started != 0) {
(*json)["callsStarted"] = std::to_string(data.calls_started);
(*json)["callsStarted"] =
Json::FromString(absl::StrCat(data.calls_started));
gpr_timespec ts = gpr_convert_clock_type(
gpr_cycle_counter_to_time(data.last_call_started_cycle),
GPR_CLOCK_REALTIME);
(*json)["lastCallStartedTimestamp"] = gpr_format_timespec(ts);
(*json)["lastCallStartedTimestamp"] =
Json::FromString(gpr_format_timespec(ts));
}
if (data.calls_succeeded != 0) {
(*json)["callsSucceeded"] = std::to_string(data.calls_succeeded);
(*json)["callsSucceeded"] =
Json::FromString(absl::StrCat(data.calls_succeeded));
}
if (data.calls_failed) {
(*json)["callsFailed"] = std::to_string(data.calls_failed);
if (data.calls_failed != 0) {
(*json)["callsFailed"] = Json::FromString(absl::StrCat(data.calls_failed));
}
}
@ -161,7 +165,7 @@ const char* ChannelNode::GetChannelConnectivityStateChangeString(
Json ChannelNode::RenderJson() {
Json::Object data = {
{"target", target_},
{"target", Json::FromString(target_)},
};
// Connectivity state.
// If low-order bit is on, then the field is set.
@ -169,9 +173,9 @@ Json ChannelNode::RenderJson() {
if ((state_field & 1) != 0) {
grpc_connectivity_state state =
static_cast<grpc_connectivity_state>(state_field >> 1);
data["state"] = Json::Object{
{"state", ConnectivityStateName(state)},
};
data["state"] = Json::FromObject({
{"state", Json::FromString(ConnectivityStateName(state))},
});
}
// Fill in the channel trace if applicable.
Json trace_json = trace_.RenderJson();
@ -182,16 +186,15 @@ Json ChannelNode::RenderJson() {
call_counter_.PopulateCallCounts(&data);
// Construct outer object.
Json::Object json = {
{"ref",
Json::Object{
{"channelId", std::to_string(uuid())},
}},
{"data", std::move(data)},
{"ref", Json::FromObject({
{"channelId", Json::FromString(absl::StrCat(uuid()))},
})},
{"data", Json::FromObject(std::move(data))},
};
// Template method. Child classes may override this to add their specific
// functionality.
PopulateChildRefs(&json);
return json;
return Json::FromObject(std::move(json));
}
void ChannelNode::PopulateChildRefs(Json::Object* json) {
@ -199,20 +202,20 @@ void ChannelNode::PopulateChildRefs(Json::Object* json) {
if (!child_subchannels_.empty()) {
Json::Array array;
for (intptr_t subchannel_uuid : child_subchannels_) {
array.emplace_back(Json::Object{
{"subchannelId", std::to_string(subchannel_uuid)},
});
array.emplace_back(Json::FromObject({
{"subchannelId", Json::FromString(absl::StrCat(subchannel_uuid))},
}));
}
(*json)["subchannelRef"] = std::move(array);
(*json)["subchannelRef"] = Json::FromArray(std::move(array));
}
if (!child_channels_.empty()) {
Json::Array array;
for (intptr_t channel_uuid : child_channels_) {
array.emplace_back(Json::Object{
{"channelId", std::to_string(channel_uuid)},
});
array.emplace_back(Json::FromObject({
{"channelId", Json::FromString(absl::StrCat(channel_uuid))},
}));
}
(*json)["channelRef"] = std::move(array);
(*json)["channelRef"] = Json::FromArray(std::move(array));
}
}
@ -286,16 +289,17 @@ std::string ServerNode::RenderServerSockets(intptr_t start_socket_id,
auto it = child_sockets_.lower_bound(start_socket_id);
for (; it != child_sockets_.end() && sockets_rendered < pagination_limit;
++it, ++sockets_rendered) {
array.emplace_back(Json::Object{
{"socketId", std::to_string(it->first)},
{"name", it->second->name()},
});
array.emplace_back(Json::FromObject({
{"socketId", Json::FromString(absl::StrCat(it->first))},
{"name", Json::FromString(it->second->name())},
}));
}
object["socketRef"] = Json::FromArray(std::move(array));
if (it == child_sockets_.end()) {
object["end"] = Json::FromBool(true);
}
object["socketRef"] = std::move(array);
if (it == child_sockets_.end()) object["end"] = true;
}
Json json = std::move(object);
return JsonDump(json);
return JsonDump(Json::FromObject(std::move(object)));
}
Json ServerNode::RenderJson() {
@ -309,11 +313,10 @@ Json ServerNode::RenderJson() {
call_counter_.PopulateCallCounts(&data);
// Construct top-level object.
Json::Object object = {
{"ref",
Json::Object{
{"serverId", std::to_string(uuid())},
}},
{"data", std::move(data)},
{"ref", Json::FromObject({
{"serverId", Json::FromString(absl::StrCat(uuid()))},
})},
{"data", Json::FromObject(std::move(data))},
};
// Render listen sockets.
{
@ -321,15 +324,15 @@ Json ServerNode::RenderJson() {
if (!child_listen_sockets_.empty()) {
Json::Array array;
for (const auto& it : child_listen_sockets_) {
array.emplace_back(Json::Object{
{"socketId", std::to_string(it.first)},
{"name", it.second->name()},
});
array.emplace_back(Json::FromObject({
{"socketId", Json::FromString(absl::StrCat(it.first))},
{"name", Json::FromString(it.second->name())},
}));
}
object["listenSocket"] = std::move(array);
object["listenSocket"] = Json::FromArray(std::move(array));
}
}
return object;
return Json::FromObject(std::move(object));
}
//
@ -339,17 +342,19 @@ Json ServerNode::RenderJson() {
Json SocketNode::Security::Tls::RenderJson() {
Json::Object data;
if (type == NameType::kStandardName) {
data["standard_name"] = name;
data["standard_name"] = Json::FromString(name);
} else if (type == NameType::kOtherName) {
data["other_name"] = name;
data["other_name"] = Json::FromString(name);
}
if (!local_certificate.empty()) {
data["local_certificate"] = absl::Base64Escape(local_certificate);
data["local_certificate"] =
Json::FromString(absl::Base64Escape(local_certificate));
}
if (!remote_certificate.empty()) {
data["remote_certificate"] = absl::Base64Escape(remote_certificate);
data["remote_certificate"] =
Json::FromString(absl::Base64Escape(remote_certificate));
}
return data;
return Json::FromObject(std::move(data));
}
//
@ -367,12 +372,12 @@ Json SocketNode::Security::RenderJson() {
}
break;
case ModelType::kOther:
if (other) {
if (other.has_value()) {
data["other"] = *other;
}
break;
}
return data;
return Json::FromObject(std::move(data));
}
namespace {
@ -424,32 +429,32 @@ void PopulateSocketAddressJson(Json::Object* json, const char* name,
auto address = StringToSockaddr(absl::StripPrefix(uri->path(), "/"));
if (address.ok()) {
std::string packed_host = grpc_sockaddr_get_packed_host(&*address);
(*json)[name] = Json::Object{
(*json)[name] = Json::FromObject({
{"tcpip_address",
Json::Object{
{"port", grpc_sockaddr_get_port(&*address)},
{"ip_address", absl::Base64Escape(packed_host)},
}},
};
Json::FromObject({
{"port", Json::FromString(
absl::StrCat(grpc_sockaddr_get_port(&*address)))},
{"ip_address",
Json::FromString(absl::Base64Escape(packed_host))},
})},
});
return;
}
} else if (uri->scheme() == "unix") {
(*json)[name] = Json::Object{
{"uds_address",
Json::Object{
{"filename", uri->path()},
}},
};
(*json)[name] = Json::FromObject({
{"uds_address", Json::FromObject({
{"filename", Json::FromString(uri->path())},
})},
});
return;
}
}
// Unknown address type.
(*json)[name] = Json::Object{
{"other_address",
Json::Object{
{"name", addr_str},
}},
};
(*json)[name] = Json::FromObject({
{"other_address", Json::FromObject({
{"name", Json::FromString(addr_str)},
})},
});
}
} // namespace
@ -491,14 +496,15 @@ Json SocketNode::RenderJson() {
gpr_timespec ts;
int64_t streams_started = streams_started_.load(std::memory_order_relaxed);
if (streams_started != 0) {
data["streamsStarted"] = std::to_string(streams_started);
data["streamsStarted"] = Json::FromString(absl::StrCat(streams_started));
gpr_cycle_counter last_local_stream_created_cycle =
last_local_stream_created_cycle_.load(std::memory_order_relaxed);
if (last_local_stream_created_cycle != 0) {
ts = gpr_convert_clock_type(
gpr_cycle_counter_to_time(last_local_stream_created_cycle),
GPR_CLOCK_REALTIME);
data["lastLocalStreamCreatedTimestamp"] = gpr_format_timespec(ts);
data["lastLocalStreamCreatedTimestamp"] =
Json::FromString(gpr_format_timespec(ts));
}
gpr_cycle_counter last_remote_stream_created_cycle =
last_remote_stream_created_cycle_.load(std::memory_order_relaxed);
@ -506,49 +512,53 @@ Json SocketNode::RenderJson() {
ts = gpr_convert_clock_type(
gpr_cycle_counter_to_time(last_remote_stream_created_cycle),
GPR_CLOCK_REALTIME);
data["lastRemoteStreamCreatedTimestamp"] = gpr_format_timespec(ts);
data["lastRemoteStreamCreatedTimestamp"] =
Json::FromString(gpr_format_timespec(ts));
}
}
int64_t streams_succeeded =
streams_succeeded_.load(std::memory_order_relaxed);
if (streams_succeeded != 0) {
data["streamsSucceeded"] = std::to_string(streams_succeeded);
data["streamsSucceeded"] =
Json::FromString(absl::StrCat(streams_succeeded));
}
int64_t streams_failed = streams_failed_.load(std::memory_order_relaxed);
if (streams_failed != 0) {
data["streamsFailed"] = std::to_string(streams_failed);
data["streamsFailed"] = Json::FromString(absl::StrCat(streams_failed));
}
int64_t messages_sent = messages_sent_.load(std::memory_order_relaxed);
if (messages_sent != 0) {
data["messagesSent"] = std::to_string(messages_sent);
data["messagesSent"] = Json::FromString(absl::StrCat(messages_sent));
ts = gpr_convert_clock_type(
gpr_cycle_counter_to_time(
last_message_sent_cycle_.load(std::memory_order_relaxed)),
GPR_CLOCK_REALTIME);
data["lastMessageSentTimestamp"] = gpr_format_timespec(ts);
data["lastMessageSentTimestamp"] =
Json::FromString(gpr_format_timespec(ts));
}
int64_t messages_received =
messages_received_.load(std::memory_order_relaxed);
if (messages_received != 0) {
data["messagesReceived"] = std::to_string(messages_received);
data["messagesReceived"] =
Json::FromString(absl::StrCat(messages_received));
ts = gpr_convert_clock_type(
gpr_cycle_counter_to_time(
last_message_received_cycle_.load(std::memory_order_relaxed)),
GPR_CLOCK_REALTIME);
data["lastMessageReceivedTimestamp"] = gpr_format_timespec(ts);
data["lastMessageReceivedTimestamp"] =
Json::FromString(gpr_format_timespec(ts));
}
int64_t keepalives_sent = keepalives_sent_.load(std::memory_order_relaxed);
if (keepalives_sent != 0) {
data["keepAlivesSent"] = std::to_string(keepalives_sent);
data["keepAlivesSent"] = Json::FromString(absl::StrCat(keepalives_sent));
}
// Create and fill the parent object.
Json::Object object = {
{"ref",
Json::Object{
{"socketId", std::to_string(uuid())},
{"name", name()},
}},
{"data", std::move(data)},
{"ref", Json::FromObject({
{"socketId", Json::FromString(absl::StrCat(uuid()))},
{"name", Json::FromString(name())},
})},
{"data", Json::FromObject(std::move(data))},
};
if (security_ != nullptr &&
security_->type != SocketNode::Security::ModelType::kUnset) {
@ -556,7 +566,7 @@ Json SocketNode::RenderJson() {
}
PopulateSocketAddressJson(&object, "remote", remote_.c_str());
PopulateSocketAddressJson(&object, "local", local_.c_str());
return object;
return Json::FromObject(std::move(object));
}
//
@ -569,14 +579,13 @@ ListenSocketNode::ListenSocketNode(std::string local_addr, std::string name)
Json ListenSocketNode::RenderJson() {
Json::Object object = {
{"ref",
Json::Object{
{"socketId", std::to_string(uuid())},
{"name", name()},
}},
{"ref", Json::FromObject({
{"socketId", Json::FromString(absl::StrCat(uuid()))},
{"name", Json::FromString(name())},
})},
};
PopulateSocketAddressJson(&object, "local", local_addr_.c_str());
return object;
return Json::FromObject(std::move(object));
}
} // namespace channelz

@ -108,11 +108,12 @@ std::string ChannelzRegistry::InternalGetTopChannels(
for (size_t i = 0; i < top_level_channels.size(); ++i) {
array.emplace_back(top_level_channels[i]->RenderJson());
}
object["channel"] = std::move(array);
object["channel"] = Json::FromArray(std::move(array));
}
if (node_after_pagination_limit == nullptr) object["end"] = true;
Json json(std::move(object));
return JsonDump(json);
if (node_after_pagination_limit == nullptr) {
object["end"] = Json::FromBool(true);
}
return JsonDump(Json::FromObject(std::move(object)));
}
std::string ChannelzRegistry::InternalGetServers(intptr_t start_server_id) {
@ -147,11 +148,12 @@ std::string ChannelzRegistry::InternalGetServers(intptr_t start_server_id) {
for (size_t i = 0; i < servers.size(); ++i) {
array.emplace_back(servers[i]->RenderJson());
}
object["server"] = std::move(array);
object["server"] = Json::FromArray(std::move(array));
}
if (node_after_pagination_limit == nullptr) {
object["end"] = Json::FromBool(true);
}
if (node_after_pagination_limit == nullptr) object["end"] = true;
Json json(std::move(object));
return JsonDump(json);
return JsonDump(Json::FromObject(std::move(object)));
}
void ChannelzRegistry::InternalLogAllEntities() {
@ -200,9 +202,9 @@ char* grpc_channelz_get_server(intptr_t server_id) {
grpc_core::channelz::BaseNode::EntityType::kServer) {
return nullptr;
}
grpc_core::Json json = grpc_core::Json::Object{
grpc_core::Json json = grpc_core::Json::FromObject({
{"server", server_node->RenderJson()},
};
});
return gpr_strdup(JsonDump(json).c_str());
}
@ -239,9 +241,9 @@ char* grpc_channelz_get_channel(intptr_t channel_id) {
grpc_core::channelz::BaseNode::EntityType::kInternalChannel)) {
return nullptr;
}
grpc_core::Json json = grpc_core::Json::Object{
grpc_core::Json json = grpc_core::Json::FromObject({
{"channel", channel_node->RenderJson()},
};
});
return gpr_strdup(JsonDump(json).c_str());
}
@ -255,9 +257,9 @@ char* grpc_channelz_get_subchannel(intptr_t subchannel_id) {
grpc_core::channelz::BaseNode::EntityType::kSubchannel) {
return nullptr;
}
grpc_core::Json json = grpc_core::Json::Object{
grpc_core::Json json = grpc_core::Json::FromObject({
{"subchannel", subchannel_node->RenderJson()},
};
});
return gpr_strdup(JsonDump(json).c_str());
}
@ -271,8 +273,8 @@ char* grpc_channelz_get_socket(intptr_t socket_id) {
grpc_core::channelz::BaseNode::EntityType::kSocket) {
return nullptr;
}
grpc_core::Json json = grpc_core::Json::Object{
grpc_core::Json json = grpc_core::Json::FromObject({
{"socket", socket_node->RenderJson()},
};
});
return gpr_strdup(JsonDump(json).c_str());
}

@ -19,126 +19,139 @@
#include <grpc/support/port_platform.h>
#include <stdint.h>
#include <map>
#include <string>
#include <utility>
#include <vector>
#include "absl/strings/str_cat.h"
#include "absl/types/variant.h"
namespace grpc_core {
// A JSON value, which can be any one of object, array, string,
// number, true, false, or null.
// A JSON value, which can be any one of null, boolean, number, string,
// object, or array.
class Json {
public:
// TODO(roth): Currently, numbers are stored internally as strings,
// which makes the API a bit cumbersome to use. When we have time,
// consider whether there's a better alternative (e.g., maybe storing
// each numeric type as the native C++ type and automatically converting
// to string as needed).
enum class Type { kNull, kTrue, kFalse, kNumber, kString, kObject, kArray };
// The JSON type.
enum class Type {
kNull, // No payload. Default type when using the zero-arg ctor.
kBoolean, // Use boolean() for payload.
kNumber, // Numbers are stored in string form to avoid precision
// and integer capacity issues. Use string() for payload.
kString, // Use string() for payload.
kObject, // Use object() for payload.
kArray, // Use array() for payload.
};
using Object = std::map<std::string, Json>;
using Array = std::vector<Json>;
Json() = default;
// Copyable.
Json(const Json& other) = default;
Json& operator=(const Json& other) = default;
// Factory method for kBoolean.
static Json FromBool(bool b) {
Json json;
json.value_ = b;
return json;
}
// Moveable.
Json(Json&& other) noexcept : value_(std::move(other.value_)) {
other.value_ = absl::monostate();
// Factory methods for kNumber.
static Json FromNumber(const std::string& str) {
Json json;
json.value_ = NumberValue{str};
return json;
}
Json& operator=(Json&& other) noexcept {
value_ = std::move(other.value_);
other.value_ = absl::monostate();
return *this;
static Json FromNumber(const char* str) {
Json json;
json.value_ = NumberValue{std::string(str)};
return json;
}
// Construct from copying a string.
// If is_number is true, the type will be kNumber instead of kString.
// NOLINTNEXTLINE(google-explicit-constructor)
Json(const std::string& string, bool is_number = false)
: value_(is_number ? Value(NumberValue{string}) : Value(string)) {}
Json& operator=(const std::string& string) {
value_ = string;
return *this;
static Json FromNumber(std::string&& str) {
Json json;
json.value_ = NumberValue{std::move(str)};
return json;
}
// Same thing for C-style strings, both const and mutable.
// NOLINTNEXTLINE(google-explicit-constructor)
Json(const char* string, bool is_number = false)
: Json(std::string(string), is_number) {}
Json& operator=(const char* string) {
*this = std::string(string);
return *this;
static Json FromNumber(int32_t value) {
Json json;
json.value_ = NumberValue{absl::StrCat(value)};
return json;
}
// NOLINTNEXTLINE(google-explicit-constructor)
Json(char* string, bool is_number = false)
: Json(std::string(string), is_number) {}
Json& operator=(char* string) {
*this = std::string(string);
return *this;
static Json FromNumber(uint32_t value) {
Json json;
json.value_ = NumberValue{absl::StrCat(value)};
return json;
}
// Construct by moving a string.
// NOLINTNEXTLINE(google-explicit-constructor)
Json(std::string&& string) : value_(Value(std::move(string))) {}
Json& operator=(std::string&& string) {
value_ = Value(std::move(string));
return *this;
static Json FromNumber(int64_t value) {
Json json;
json.value_ = NumberValue{absl::StrCat(value)};
return json;
}
// Construct from bool.
// NOLINTNEXTLINE(google-explicit-constructor)
Json(bool b) : value_(b) {}
Json& operator=(bool b) {
value_ = b;
return *this;
static Json FromNumber(uint64_t value) {
Json json;
json.value_ = NumberValue{absl::StrCat(value)};
return json;
}
// Construct from any numeric type.
template <typename NumericType>
// NOLINTNEXTLINE(google-explicit-constructor)
Json(NumericType number) : value_(NumberValue{std::to_string(number)}) {}
template <typename NumericType>
Json& operator=(NumericType number) {
value_ = NumberValue{std::to_string(number)};
return *this;
static Json FromNumber(double value) {
Json json;
json.value_ = NumberValue{absl::StrCat(value)};
return json;
}
// Construct by copying object.
// NOLINTNEXTLINE(google-explicit-constructor)
Json(const Object& object) : value_(object) {}
Json& operator=(const Object& object) {
value_ = object;
return *this;
// Factory methods for kString.
static Json FromString(const std::string& str) {
Json json;
json.value_ = str;
return json;
}
static Json FromString(const char* str) {
Json json;
json.value_ = std::string(str);
return json;
}
static Json FromString(std::string&& str) {
Json json;
json.value_ = std::move(str);
return json;
}
// Construct by moving object.
// NOLINTNEXTLINE(google-explicit-constructor)
Json(Object&& object) : value_(std::move(object)) {}
Json& operator=(Object&& object) {
value_ = std::move(object);
return *this;
// Factory methods for kObject.
static Json FromObject(const Object& object) {
Json json;
json.value_ = object;
return json;
}
static Json FromObject(Object&& object) {
Json json;
json.value_ = std::move(object);
return json;
}
// Construct by copying array.
// NOLINTNEXTLINE(google-explicit-constructor)
Json(const Array& array) : value_(array) {}
Json& operator=(const Array& array) {
value_ = array;
return *this;
// Factory methods for kArray.
static Json FromArray(const Array& array) {
Json json;
json.value_ = array;
return json;
}
static Json FromArray(Array&& array) {
Json json;
json.value_ = std::move(array);
return json;
}
// Construct by moving array.
// NOLINTNEXTLINE(google-explicit-constructor)
Json(Array&& array) : value_(std::move(array)) {}
Json& operator=(Array&& array) {
value_ = std::move(array);
Json() = default;
// Copyable.
Json(const Json& other) = default;
Json& operator=(const Json& other) = default;
// Moveable.
Json(Json&& other) noexcept : value_(std::move(other.value_)) {
other.value_ = absl::monostate();
}
Json& operator=(Json&& other) noexcept {
value_ = std::move(other.value_);
other.value_ = absl::monostate();
return *this;
}
@ -146,9 +159,7 @@ class Json {
Type type() const {
struct ValueFunctor {
Json::Type operator()(const absl::monostate&) { return Type::kNull; }
Json::Type operator()(bool value) {
return value ? Type::kTrue : Type::kFalse;
}
Json::Type operator()(bool) { return Type::kBoolean; }
Json::Type operator()(const NumberValue&) { return Type::kNumber; }
Json::Type operator()(const std::string&) { return Type::kString; }
Json::Type operator()(const Object&) { return Type::kObject; }
@ -157,13 +168,24 @@ class Json {
return absl::visit(ValueFunctor(), value_);
}
// Accessor methods.
// Payload accessor for kBoolean.
// Must not be called for other types.
bool boolean() const { return absl::get<bool>(value_); }
// Payload accessor for kNumber or kString.
// Must not be called for other types.
const std::string& string() const {
const NumberValue* num = absl::get_if<NumberValue>(&value_);
if (num != nullptr) return num->value;
return absl::get<std::string>(value_);
}
// Payload accessor for kObject.
// Must not be called for other types.
const Object& object() const { return absl::get<Object>(value_); }
// Payload accessor for kArray.
// Must not be called for other types.
const Array& array() const { return absl::get<Array>(value_); }
bool operator==(const Json& other) const { return value_ == other.value_; }
@ -178,7 +200,7 @@ class Json {
}
};
using Value = absl::variant<absl::monostate, // kNull
bool, // kTrue or kFalse
bool, // kBoolean
NumberValue, // kNumber
std::string, // kString
Object, // kObject

@ -91,13 +91,11 @@ bool LoadNumber::IsNumber() const { return true; }
void LoadBool::LoadInto(const Json& json, const JsonArgs&, void* dst,
ValidationErrors* errors) const {
if (json.type() == Json::Type::kTrue) {
*static_cast<bool*>(dst) = true;
} else if (json.type() == Json::Type::kFalse) {
*static_cast<bool*>(dst) = false;
} else {
if (json.type() != Json::Type::kBoolean) {
errors->AddError("is not a boolean");
return;
}
*static_cast<bool*>(dst) = json.boolean();
}
void LoadUnprocessedJsonObject::LoadInto(const Json& json, const JsonArgs&,

@ -107,8 +107,13 @@ class JsonReader {
Json TakeAsJson() {
return MatchMutable(
&data, [&](Json::Object* object) { return Json(std::move(*object)); },
[&](Json::Array* array) { return Json(std::move(*array)); });
&data,
[&](Json::Object* object) {
return Json::FromObject(std::move(*object));
},
[&](Json::Array* array) {
return Json::FromArray(std::move(*array));
});
}
};
@ -307,26 +312,26 @@ void JsonReader::SetKey() {
void JsonReader::SetString() {
Json* value = CreateAndLinkValue();
*value = std::move(string_);
*value = Json::FromString(std::move(string_));
string_.clear();
}
bool JsonReader::SetNumber() {
Json* value = CreateAndLinkValue();
*value = Json(string_, /*is_number=*/true);
*value = Json::FromNumber(std::move(string_));
string_.clear();
return true;
}
void JsonReader::SetTrue() {
Json* value = CreateAndLinkValue();
*value = true;
*value = Json::FromBool(true);
string_.clear();
}
void JsonReader::SetFalse() {
Json* value = CreateAndLinkValue();
*value = false;
*value = Json::FromBool(false);
string_.clear();
}

@ -37,18 +37,13 @@ bool ParseDurationFromJson(const Json& field, Duration* duration) {
bool ExtractJsonBool(const Json& json, absl::string_view field_name,
bool* output, std::vector<grpc_error_handle>* error_list) {
switch (json.type()) {
case Json::Type::kTrue:
*output = true;
return true;
case Json::Type::kFalse:
*output = false;
return true;
default:
error_list->push_back(GRPC_ERROR_CREATE(
absl::StrCat("field:", field_name, " error:type should be BOOLEAN")));
return false;
if (json.type() != Json::Type::kBoolean) {
error_list->push_back(GRPC_ERROR_CREATE(
absl::StrCat("field:", field_name, " error:type should be BOOLEAN")));
return false;
}
*output = json.boolean();
return true;
}
bool ExtractJsonArray(const Json& json, absl::string_view field_name,

@ -311,11 +311,12 @@ void JsonWriter::DumpValue(const Json& value) {
case Json::Type::kNumber:
ValueRaw(value.string());
break;
case Json::Type::kTrue:
ValueRaw(std::string("true", 4));
break;
case Json::Type::kFalse:
ValueRaw(std::string("false", 5));
case Json::Type::kBoolean:
if (value.boolean()) {
ValueRaw(std::string("true", 4));
} else {
ValueRaw(std::string("false", 5));
}
break;
case Json::Type::kNull:
ValueRaw(std::string("null", 4));

@ -487,19 +487,25 @@ void AwsExternalAccountCredentials::BuildSubjectToken() {
}
// Construct subject token
Json::Array headers;
headers.push_back(Json(
{{"key", "Authorization"}, {"value", signed_headers["Authorization"]}}));
headers.push_back(Json({{"key", "host"}, {"value", signed_headers["host"]}}));
headers.push_back(Json::FromObject(
{{"key", Json::FromString("Authorization")},
{"value", Json::FromString(signed_headers["Authorization"])}}));
headers.push_back(
Json({{"key", "x-amz-date"}, {"value", signed_headers["x-amz-date"]}}));
headers.push_back(Json({{"key", "x-amz-security-token"},
{"value", signed_headers["x-amz-security-token"]}}));
headers.push_back(
Json({{"key", "x-goog-cloud-target-resource"}, {"value", audience_}}));
Json::Object object{{"url", Json(cred_verification_url_)},
{"method", Json("POST")},
{"headers", Json(headers)}};
Json subject_token_json(object);
Json::FromObject({{"key", Json::FromString("host")},
{"value", Json::FromString(signed_headers["host"])}}));
headers.push_back(Json::FromObject(
{{"key", Json::FromString("x-amz-date")},
{"value", Json::FromString(signed_headers["x-amz-date"])}}));
headers.push_back(Json::FromObject(
{{"key", Json::FromString("x-amz-security-token")},
{"value", Json::FromString(signed_headers["x-amz-security-token"])}}));
headers.push_back(Json::FromObject(
{{"key", Json::FromString("x-goog-cloud-target-resource")},
{"value", Json::FromString(audience_)}}));
Json subject_token_json =
Json::FromObject({{"url", Json::FromString(cred_verification_url_)},
{"method", Json::FromString("POST")},
{"headers", Json::FromArray(headers)}});
std::string subject_token = UrlEncode(JsonDump(subject_token_json));
FinishRetrieveSubjectToken(subject_token, absl::OkStatus());
}

@ -328,9 +328,10 @@ void ExternalAccountCredentials::ExchangeToken(
Json::Object addtional_options_json_object;
if (options_.client_id.empty() && options_.client_secret.empty()) {
addtional_options_json_object["userProject"] =
options_.workforce_pool_user_project;
Json::FromString(options_.workforce_pool_user_project);
}
Json addtional_options_json(std::move(addtional_options_json_object));
Json addtional_options_json =
Json::FromObject(std::move(addtional_options_json_object));
body_parts.push_back(absl::StrFormat(
"options=%s", UrlEncode(JsonDump(addtional_options_json)).c_str()));
std::string body = absl::StrJoin(body_parts, "&");

@ -165,11 +165,11 @@ void grpc_auth_json_key_destruct(grpc_auth_json_key* json_key) {
// --- jwt encoding and signature. ---
static char* encoded_jwt_header(const char* key_id, const char* algorithm) {
Json json = Json::Object{
{"alg", algorithm},
{"typ", GRPC_JWT_TYPE},
{"kid", key_id},
};
Json json = Json::FromObject({
{"alg", Json::FromString(algorithm)},
{"typ", Json::FromString(GRPC_JWT_TYPE)},
{"kid", Json::FromString(key_id)},
});
std::string json_str = JsonDump(json);
return grpc_base64_encode(json_str.c_str(), json_str.size(), 1, 0);
}
@ -185,20 +185,19 @@ static char* encoded_jwt_claim(const grpc_auth_json_key* json_key,
}
Json::Object object = {
{"iss", json_key->client_email},
{"aud", audience},
{"iat", now.tv_sec},
{"exp", expiration.tv_sec},
{"iss", Json::FromString(json_key->client_email)},
{"aud", Json::FromString(audience)},
{"iat", Json::FromNumber(now.tv_sec)},
{"exp", Json::FromNumber(expiration.tv_sec)},
};
if (scope != nullptr) {
object["scope"] = scope;
object["scope"] = Json::FromString(scope);
} else {
// Unscoped JWTs need a sub field.
object["sub"] = json_key->client_email;
object["sub"] = Json::FromString(json_key->client_email);
}
Json json(object);
std::string json_str = JsonDump(json);
std::string json_str = JsonDump(Json::FromObject(std::move(object)));
return grpc_base64_encode(json_str.c_str(), json_str.size(), 1, 0);
}

@ -145,9 +145,10 @@ static char* redact_private_key(const char* json_key) {
return gpr_strdup("<Json failed to parse.>");
}
Json::Object object = json->object();
object["private_key"] = "<redacted>";
object["private_key"] = Json::FromString("<redacted>");
return gpr_strdup(
grpc_core::JsonDump(Json(std::move(object)), /*indent=*/2).c_str());
grpc_core::JsonDump(Json::FromObject(std::move(object)), /*indent=*/2)
.c_str());
}
grpc_call_credentials* grpc_service_account_jwt_access_credentials_create(

@ -121,7 +121,8 @@ RefCountedPtr<ServiceConfig> ServiceConfigImpl::Create(
service_config->parsed_method_config_vectors_storage_.reserve(
method_configs->size());
for (size_t i = 0; i < method_configs->size(); ++i) {
const Json::Object& method_config_json = (*method_configs)[i];
const Json method_config_json =
Json::FromObject(std::move((*method_configs)[i]));
ValidationErrors::ScopedField field(
errors, absl::StrCat(".methodConfig[", i, "]"));
// Have each parser read this method config.

@ -98,7 +98,8 @@ void ValidateJsonEnd(const Json& json, bool end) {
auto it = json.object().find("end");
if (end) {
ASSERT_NE(it, json.object().end());
EXPECT_EQ(it->second.type(), Json::Type::kTrue);
ASSERT_EQ(it->second.type(), Json::Type::kBoolean);
EXPECT_TRUE(it->second.boolean());
} else {
ASSERT_EQ(it, json.object().end());
}

@ -43,74 +43,77 @@ class OutlierDetectionTest : public LoadBalancingPolicyTest {
class ConfigBuilder {
public:
ConfigBuilder() {
SetChildPolicy(Json::Object{{"round_robin", Json::Object()}});
SetChildPolicy(Json::Object{{"round_robin", Json::FromObject({})}});
}
ConfigBuilder& SetInterval(Duration duration) {
json_["interval"] = duration.ToJsonString();
json_["interval"] = Json::FromString(duration.ToJsonString());
return *this;
}
ConfigBuilder& SetBaseEjectionTime(Duration duration) {
json_["baseEjectionTime"] = duration.ToJsonString();
json_["baseEjectionTime"] = Json::FromString(duration.ToJsonString());
return *this;
}
ConfigBuilder& SetMaxEjectionTime(Duration duration) {
json_["maxEjectionTime"] = duration.ToJsonString();
json_["maxEjectionTime"] = Json::FromString(duration.ToJsonString());
return *this;
}
ConfigBuilder& SetMaxEjectionPercent(uint32_t value) {
json_["maxEjectionPercent"] = value;
json_["maxEjectionPercent"] = Json::FromNumber(value);
return *this;
}
ConfigBuilder& SetChildPolicy(Json::Object child_policy) {
json_["childPolicy"] = Json::Array{std::move(child_policy)};
json_["childPolicy"] =
Json::FromArray({Json::FromObject(std::move(child_policy))});
return *this;
}
ConfigBuilder& SetSuccessRateStdevFactor(uint32_t value) {
GetSuccessRate()["stdevFactor"] = value;
GetSuccessRate()["stdevFactor"] = Json::FromNumber(value);
return *this;
}
ConfigBuilder& SetSuccessRateEnforcementPercentage(uint32_t value) {
GetSuccessRate()["enforcementPercentage"] = value;
GetSuccessRate()["enforcementPercentage"] = Json::FromNumber(value);
return *this;
}
ConfigBuilder& SetSuccessRateMinHosts(uint32_t value) {
GetSuccessRate()["minimumHosts"] = value;
GetSuccessRate()["minimumHosts"] = Json::FromNumber(value);
return *this;
}
ConfigBuilder& SetSuccessRateRequestVolume(uint32_t value) {
GetSuccessRate()["requestVolume"] = value;
GetSuccessRate()["requestVolume"] = Json::FromNumber(value);
return *this;
}
ConfigBuilder& SetFailurePercentageThreshold(uint32_t value) {
GetFailurePercentage()["threshold"] = value;
GetFailurePercentage()["threshold"] = Json::FromNumber(value);
return *this;
}
ConfigBuilder& SetFailurePercentageEnforcementPercentage(uint32_t value) {
GetFailurePercentage()["enforcementPercentage"] = value;
GetFailurePercentage()["enforcementPercentage"] = Json::FromNumber(value);
return *this;
}
ConfigBuilder& SetFailurePercentageMinimumHosts(uint32_t value) {
GetFailurePercentage()["minimumHosts"] = value;
GetFailurePercentage()["minimumHosts"] = Json::FromNumber(value);
return *this;
}
ConfigBuilder& SetFailurePercentageRequestVolume(uint32_t value) {
GetFailurePercentage()["requestVolume"] = value;
GetFailurePercentage()["requestVolume"] = Json::FromNumber(value);
return *this;
}
RefCountedPtr<LoadBalancingPolicy::Config> Build() {
Json::Object fields = json_;
if (success_rate_.has_value()) {
fields["successRateEjection"] = *success_rate_;
fields["successRateEjection"] = Json::FromObject(*success_rate_);
}
if (failure_percentage_.has_value()) {
fields["failurePercentageEjection"] = *failure_percentage_;
fields["failurePercentageEjection"] =
Json::FromObject(*failure_percentage_);
}
Json config = Json::Array{
Json::Object{{"outlier_detection_experimental", std::move(fields)}}};
Json config = Json::FromArray(
{Json::FromObject({{"outlier_detection_experimental",
Json::FromObject(std::move(fields))}})});
return MakeConfig(config);
}

@ -80,32 +80,34 @@ class WeightedRoundRobinTest : public LoadBalancingPolicyTest {
}
ConfigBuilder& SetEnableOobLoadReport(bool value) {
json_["enableOobLoadReport"] = value;
json_["enableOobLoadReport"] = Json::FromBool(value);
return *this;
}
ConfigBuilder& SetOobReportingPeriod(Duration duration) {
json_["oobReportingPeriod"] = duration.ToJsonString();
json_["oobReportingPeriod"] = Json::FromString(duration.ToJsonString());
return *this;
}
ConfigBuilder& SetBlackoutPeriod(Duration duration) {
json_["blackoutPeriod"] = duration.ToJsonString();
json_["blackoutPeriod"] = Json::FromString(duration.ToJsonString());
return *this;
}
ConfigBuilder& SetWeightUpdatePeriod(Duration duration) {
json_["weightUpdatePeriod"] = duration.ToJsonString();
json_["weightUpdatePeriod"] = Json::FromString(duration.ToJsonString());
return *this;
}
ConfigBuilder& SetWeightExpirationPeriod(Duration duration) {
json_["weightExpirationPeriod"] = duration.ToJsonString();
json_["weightExpirationPeriod"] =
Json::FromString(duration.ToJsonString());
return *this;
}
ConfigBuilder& SetErrorUtilizationPenalty(float value) {
json_["errorUtilizationPenalty"] = value;
json_["errorUtilizationPenalty"] = Json::FromNumber(value);
return *this;
}
RefCountedPtr<LoadBalancingPolicy::Config> Build() {
Json config = Json::Array{Json::Object{{"weighted_round_robin", json_}}};
Json config = Json::FromArray({Json::FromObject(
{{"weighted_round_robin", Json::FromObject(json_)}})});
gpr_log(GPR_INFO, "CONFIG: %s", JsonDump(config).c_str());
return MakeConfig(config);
}

@ -51,13 +51,22 @@ class XdsOverrideHostTest : public LoadBalancingPolicyTest {
: policy_(MakeLbPolicy("xds_override_host_experimental")) {}
static RefCountedPtr<LoadBalancingPolicy::Config> MakeXdsOverrideHostConfig(
Json::Array override_host_status = {"UNKNOWN", "HEALTHY"},
absl::Span<const absl::string_view> override_host_status = {"UNKNOWN",
"HEALTHY"},
std::string child_policy = "round_robin") {
Json::Object child_policy_config = {{child_policy, Json::Object()}};
return MakeConfig(Json::Array{Json::Object{
{"xds_override_host_experimental",
Json::Object{{"childPolicy", Json::Array{{child_policy_config}}},
{"overrideHostStatus", override_host_status}}}}});
Json child_policy_config =
Json::FromObject({{child_policy, Json::FromObject({})}});
Json::Array override_host_status_array;
for (const absl::string_view host_status : override_host_status) {
override_host_status_array.push_back(
Json::FromString(std::string(host_status)));
}
return MakeConfig(Json::FromArray({Json::FromObject(
{{"xds_override_host_experimental",
Json::FromObject(
{{"childPolicy", Json::FromArray({child_policy_config})},
{"overrideHostStatus",
Json::FromArray(override_host_status_array)}})}})}));
}
RefCountedPtr<LoadBalancingPolicy::SubchannelPicker>
@ -101,9 +110,10 @@ class XdsOverrideHostTest : public LoadBalancingPolicyTest {
absl::Span<const std::pair<const absl::string_view,
XdsHealthStatus::HealthStatus>>
addresses_and_statuses,
Json::Array override_host_status = {"UNKNOWN", "HEALTHY"}) {
absl::Span<const absl::string_view> override_host_status = {"UNKNOWN",
"HEALTHY"}) {
LoadBalancingPolicy::UpdateArgs update;
update.config = MakeXdsOverrideHostConfig(std::move(override_host_status));
update.config = MakeXdsOverrideHostConfig(override_host_status);
update.addresses.emplace();
for (auto address_and_status : addresses_and_statuses) {
update.addresses->push_back(MakeAddressWithHealthStatus(

@ -537,8 +537,8 @@ TEST(JsonObjectLoader, JsonObjectFields) {
// Valid object.
auto test_struct = Parse<TestStruct>("{\"value\": {\"a\":1}}");
ASSERT_TRUE(test_struct.ok()) << test_struct.status();
EXPECT_EQ(JsonDump(Json{test_struct->value}), "{\"a\":1}");
EXPECT_EQ(JsonDump(Json{test_struct->optional_value}), "{}");
EXPECT_EQ(JsonDump(Json::FromObject(test_struct->value)), "{\"a\":1}");
EXPECT_EQ(JsonDump(Json::FromObject(test_struct->optional_value)), "{}");
EXPECT_FALSE(test_struct->absl_optional_value.has_value());
// Fails if required field is not present.
test_struct = Parse<TestStruct>("{}");
@ -551,12 +551,15 @@ TEST(JsonObjectLoader, JsonObjectFields) {
"{\"value\": {\"a\":1}, \"optional_value\": {\"b\":2}, "
"\"absl_optional_value\": {\"c\":3}, \"unique_ptr_value\": {\"d\":4}}");
ASSERT_TRUE(test_struct.ok()) << test_struct.status();
EXPECT_EQ(JsonDump(Json{test_struct->value}), "{\"a\":1}");
EXPECT_EQ(JsonDump(Json{test_struct->optional_value}), "{\"b\":2}");
EXPECT_EQ(JsonDump(Json::FromObject(test_struct->value)), "{\"a\":1}");
EXPECT_EQ(JsonDump(Json::FromObject(test_struct->optional_value)),
"{\"b\":2}");
ASSERT_TRUE(test_struct->absl_optional_value.has_value());
EXPECT_EQ(JsonDump(Json{*test_struct->absl_optional_value}), "{\"c\":3}");
EXPECT_EQ(JsonDump(Json::FromObject(*test_struct->absl_optional_value)),
"{\"c\":3}");
ASSERT_NE(test_struct->unique_ptr_value, nullptr);
EXPECT_EQ(JsonDump(Json{*test_struct->unique_ptr_value}), "{\"d\":4}");
EXPECT_EQ(JsonDump(Json::FromObject(*test_struct->unique_ptr_value)),
"{\"d\":4}");
// Wrong JSON type.
test_struct = Parse<TestStruct>(
"{\"value\": [], \"optional_value\": true, "
@ -597,8 +600,8 @@ TEST(JsonObjectLoader, JsonArrayFields) {
// Valid object.
auto test_struct = Parse<TestStruct>("{\"value\": [1, \"a\"]}");
ASSERT_TRUE(test_struct.ok()) << test_struct.status();
EXPECT_EQ(JsonDump(Json{test_struct->value}), "[1,\"a\"]");
EXPECT_EQ(JsonDump(Json{test_struct->optional_value}), "[]");
EXPECT_EQ(JsonDump(Json::FromArray(test_struct->value)), "[1,\"a\"]");
EXPECT_EQ(JsonDump(Json::FromArray(test_struct->optional_value)), "[]");
EXPECT_FALSE(test_struct->absl_optional_value.has_value());
EXPECT_EQ(test_struct->unique_ptr_value, nullptr);
// Fails if required field is not present.
@ -612,12 +615,15 @@ TEST(JsonObjectLoader, JsonArrayFields) {
"{\"value\": [1, \"a\"], \"optional_value\": [2, \"b\"], "
"\"absl_optional_value\": [3, \"c\"], \"unique_ptr_value\": [4, \"d\"]}");
ASSERT_TRUE(test_struct.ok()) << test_struct.status();
EXPECT_EQ(JsonDump(Json{test_struct->value}), "[1,\"a\"]");
EXPECT_EQ(JsonDump(Json{test_struct->optional_value}), "[2,\"b\"]");
EXPECT_EQ(JsonDump(Json::FromArray(test_struct->value)), "[1,\"a\"]");
EXPECT_EQ(JsonDump(Json::FromArray(test_struct->optional_value)),
"[2,\"b\"]");
ASSERT_TRUE(test_struct->absl_optional_value.has_value());
EXPECT_EQ(JsonDump(Json{*test_struct->absl_optional_value}), "[3,\"c\"]");
EXPECT_EQ(JsonDump(Json::FromArray(*test_struct->absl_optional_value)),
"[3,\"c\"]");
ASSERT_NE(test_struct->unique_ptr_value, nullptr);
EXPECT_EQ(JsonDump(Json{*test_struct->unique_ptr_value}), "[4,\"d\"]");
EXPECT_EQ(JsonDump(Json::FromArray(*test_struct->unique_ptr_value)),
"[4,\"d\"]");
// Wrong JSON type.
test_struct = Parse<TestStruct>(
"{\"value\": {}, \"optional_value\": true, "

@ -56,8 +56,9 @@ void ValidateValue(const Json& actual, const Json& expected) {
ASSERT_EQ(actual.type(), expected.type());
switch (expected.type()) {
case Json::Type::kNull:
case Json::Type::kTrue:
case Json::Type::kFalse:
break;
case Json::Type::kBoolean:
EXPECT_EQ(actual.boolean(), expected.boolean());
break;
case Json::Type::kString:
case Json::Type::kNumber:
@ -83,16 +84,16 @@ void RunSuccessTest(const char* input, const Json& expected,
}
TEST(Json, Whitespace) {
RunSuccessTest(" 0 ", 0, "0");
RunSuccessTest(" 1 ", 1, "1");
RunSuccessTest(" \" \" ", " ", "\" \"");
RunSuccessTest(" \"a\" ", "a", "\"a\"");
RunSuccessTest(" true ", true, "true");
RunSuccessTest(" 0 ", Json::FromNumber(0), "0");
RunSuccessTest(" 1 ", Json::FromNumber(1), "1");
RunSuccessTest(" \" \" ", Json::FromString(" "), "\" \"");
RunSuccessTest(" \"a\" ", Json::FromString("a"), "\"a\"");
RunSuccessTest(" true ", Json::FromBool(true), "true");
}
TEST(Json, Utf16) {
RunSuccessTest("\"\\u0020\\\\\\u0010\\u000a\\u000D\"", " \\\u0010\n\r",
"\" \\\\\\u0010\\n\\r\"");
RunSuccessTest("\"\\u0020\\\\\\u0010\\u000a\\u000D\"",
Json::FromString(" \\\u0010\n\r"), "\" \\\\\\u0010\\n\\r\"");
}
MATCHER(ContainsInvalidUtf8,
@ -104,17 +105,18 @@ MATCHER(ContainsInvalidUtf8,
}
TEST(Json, Utf8) {
RunSuccessTest("\"ßâñć௵⇒\"", "ßâñć௵⇒",
RunSuccessTest("\"ßâñć௵⇒\"", Json::FromString("ßâñć௵⇒"),
"\"\\u00df\\u00e2\\u00f1\\u0107\\u0bf5\\u21d2\"");
RunSuccessTest("\"\\u00df\\u00e2\\u00f1\\u0107\\u0bf5\\u21d2\"", "ßâñć௵⇒",
RunSuccessTest("\"\\u00df\\u00e2\\u00f1\\u0107\\u0bf5\\u21d2\"",
Json::FromString("ßâñć௵⇒"),
"\"\\u00df\\u00e2\\u00f1\\u0107\\u0bf5\\u21d2\"");
// Testing UTF-8 character "𝄞", U+11D1E.
RunSuccessTest("\"\xf0\x9d\x84\x9e\"", "\xf0\x9d\x84\x9e",
RunSuccessTest("\"\xf0\x9d\x84\x9e\"", Json::FromString("\xf0\x9d\x84\x9e"),
"\"\\ud834\\udd1e\"");
RunSuccessTest("\"\\ud834\\udd1e\"", "\xf0\x9d\x84\x9e",
RunSuccessTest("\"\\ud834\\udd1e\"", Json::FromString("\xf0\x9d\x84\x9e"),
"\"\\ud834\\udd1e\"");
RunSuccessTest("{\"\\ud834\\udd1e\":0}",
Json::Object{{"\xf0\x9d\x84\x9e", 0}},
Json::FromObject({{"\xf0\x9d\x84\x9e", Json::FromNumber(0)}}),
"{\"\\ud834\\udd1e\":0}");
/// For UTF-8 characters with length of 1 byte, the range of it is [0x00,
@ -143,53 +145,53 @@ TEST(Json, Utf8) {
TEST(Json, NestedEmptyContainers) {
RunSuccessTest(" [ [ ] , { } , [ ] ] ",
Json::Array{
Json::Array(),
Json::Object(),
Json::Array(),
},
Json::FromArray({
Json::FromArray({}),
Json::FromObject({}),
Json::FromArray({}),
}),
"[[],{},[]]");
}
TEST(Json, EscapesAndControlCharactersInKeyStrings) {
RunSuccessTest(" { \"\\u007f\x7f\\n\\r\\\"\\f\\b\\\\a , b\": 1, \"\": 0 } ",
Json::Object{
{"\u007f\u007f\n\r\"\f\b\\a , b", 1},
{"", 0},
},
Json::FromObject({
{"\u007f\u007f\n\r\"\f\b\\a , b", Json::FromNumber(1)},
{"", Json::FromNumber(0)},
}),
"{\"\":0,\"\\u007f\\u007f\\n\\r\\\"\\f\\b\\\\a , b\":1}");
}
TEST(Json, WriterCutsOffInvalidUtf8) {
EXPECT_EQ(JsonDump(Json("abc\xf0\x9d\x24")), "\"abc\"");
EXPECT_EQ(JsonDump(Json("\xff")), "\"\"");
EXPECT_EQ(JsonDump(Json::FromString("abc\xf0\x9d\x24")), "\"abc\"");
EXPECT_EQ(JsonDump(Json::FromString("\xff")), "\"\"");
}
TEST(Json, ValidNumbers) {
RunSuccessTest("[0, 42 , 0.0123, 123.456]",
Json::Array{
0,
42,
Json("0.0123", /*is_number=*/true),
Json("123.456", /*is_number=*/true),
},
Json::FromArray({
Json::FromNumber(0),
Json::FromNumber(42),
Json::FromNumber("0.0123"),
Json::FromNumber("123.456"),
}),
"[0,42,0.0123,123.456]");
RunSuccessTest("[1e4,-53.235e-31, 0.3e+3]",
Json::Array{
Json("1e4", /*is_number=*/true),
Json("-53.235e-31", /*is_number=*/true),
Json("0.3e+3", /*is_number=*/true),
},
Json::FromArray({
Json::FromNumber("1e4"),
Json::FromNumber("-53.235e-31"),
Json::FromNumber("0.3e+3"),
}),
"[1e4,-53.235e-31,0.3e+3]");
}
TEST(Json, Keywords) {
RunSuccessTest("[true, false, null]",
Json::Array{
Json(true),
Json(false),
Json::FromArray({
Json::FromBool(true),
Json::FromBool(false),
Json(),
},
}),
"[true,false,null]");
}
@ -287,30 +289,35 @@ TEST(Json, Equality) {
// Null.
EXPECT_EQ(Json(), Json());
// Numbers.
EXPECT_EQ(Json(1), Json(1));
EXPECT_NE(Json(1), Json(2));
EXPECT_EQ(Json(1), Json("1", /*is_number=*/true));
EXPECT_EQ(Json("-5e5", /*is_number=*/true), Json("-5e5", /*is_number=*/true));
EXPECT_EQ(Json::FromNumber(1), Json::FromNumber(1));
EXPECT_NE(Json::FromNumber(1), Json::FromNumber(2));
EXPECT_EQ(Json::FromNumber(1), Json::FromNumber("1"));
EXPECT_EQ(Json::FromNumber("-5e5"), Json::FromNumber("-5e5"));
// Booleans.
EXPECT_EQ(Json(true), Json(true));
EXPECT_EQ(Json(false), Json(false));
EXPECT_NE(Json(true), Json(false));
EXPECT_EQ(Json::FromBool(true), Json::FromBool(true));
EXPECT_EQ(Json::FromBool(false), Json::FromBool(false));
EXPECT_NE(Json::FromBool(true), Json::FromBool(false));
// Strings.
EXPECT_EQ(Json("foo"), Json("foo"));
EXPECT_NE(Json("foo"), Json("bar"));
EXPECT_EQ(Json::FromString("foo"), Json::FromString("foo"));
EXPECT_NE(Json::FromString("foo"), Json::FromString("bar"));
// Arrays.
EXPECT_EQ(Json(Json::Array{"foo"}), Json(Json::Array{"foo"}));
EXPECT_NE(Json(Json::Array{"foo"}), Json(Json::Array{"bar"}));
EXPECT_EQ(Json::FromArray({Json::FromString("foo")}),
Json::FromArray({Json::FromString("foo")}));
EXPECT_NE(Json::FromArray({Json::FromString("foo")}),
Json::FromArray({Json::FromString("bar")}));
// Objects.
EXPECT_EQ(Json(Json::Object{{"foo", 1}}), Json(Json::Object{{"foo", 1}}));
EXPECT_NE(Json(Json::Object{{"foo", 1}}), Json(Json::Object{{"foo", 2}}));
EXPECT_NE(Json(Json::Object{{"foo", 1}}), Json(Json::Object{{"bar", 1}}));
EXPECT_EQ(Json::FromObject({{"foo", Json::FromNumber(1)}}),
Json::FromObject({{"foo", Json::FromNumber(1)}}));
EXPECT_NE(Json::FromObject({{"foo", Json::FromNumber(1)}}),
Json::FromObject({{"foo", Json::FromNumber(2)}}));
EXPECT_NE(Json::FromObject({{"foo", Json::FromNumber(1)}}),
Json::FromObject({{"bar", Json::FromNumber(1)}}));
// Differing types.
EXPECT_NE(Json(1), Json("foo"));
EXPECT_NE(Json(1), Json(true));
EXPECT_NE(Json(1), Json(Json::Array{}));
EXPECT_NE(Json(1), Json(Json::Object{}));
EXPECT_NE(Json(1), Json());
EXPECT_NE(Json::FromNumber(1), Json::FromString("foo"));
EXPECT_NE(Json::FromNumber(1), Json::FromBool(true));
EXPECT_NE(Json::FromNumber(1), Json::FromArray({}));
EXPECT_NE(Json::FromNumber(1), Json::FromObject({}));
EXPECT_NE(Json::FromNumber(1), Json());
}
} // namespace grpc_core

@ -2350,7 +2350,7 @@ class TestExternalAccountCredentials final : public ExternalAccountCredentials {
TEST(CredentialsTest, TestExternalAccountCredsSuccess) {
ExecCtx exec_ctx;
Json credential_source("");
Json credential_source = Json::FromString("");
TestExternalAccountCredentials::Options options = {
"external_account", // type;
"audience", // audience;
@ -2392,7 +2392,7 @@ TEST(CredentialsTest, TestExternalAccountCredsSuccessWithUrlEncode) {
std::map<std::string, std::string> emd = {
{"authorization", "Bearer token_exchange_access_token"}};
ExecCtx exec_ctx;
Json credential_source("");
Json credential_source = Json::FromString("");
TestExternalAccountCredentials::Options options = {
"external_account", // type;
"audience_!@#$", // audience;
@ -2421,7 +2421,7 @@ TEST(CredentialsTest, TestExternalAccountCredsSuccessWithUrlEncode) {
TEST(CredentialsTest,
TestExternalAccountCredsSuccessWithServiceAccountImpersonation) {
ExecCtx exec_ctx;
Json credential_source("");
Json credential_source = Json::FromString("");
TestExternalAccountCredentials::Options options = {
"external_account", // type;
"audience", // audience;
@ -2453,7 +2453,7 @@ TEST(CredentialsTest,
TEST(CredentialsTest, TestExternalAccountCredsFailureInvalidTokenUrl) {
ExecCtx exec_ctx;
Json credential_source("");
Json credential_source = Json::FromString("");
TestExternalAccountCredentials::Options options = {
"external_account", // type;
"audience", // audience;
@ -2485,7 +2485,7 @@ TEST(CredentialsTest, TestExternalAccountCredsFailureInvalidTokenUrl) {
TEST(CredentialsTest,
TestExternalAccountCredsFailureInvalidServiceAccountImpersonationUrl) {
ExecCtx exec_ctx;
Json credential_source("");
Json credential_source = Json::FromString("");
TestExternalAccountCredentials::Options options = {
"external_account", // type;
"audience", // audience;
@ -2518,7 +2518,7 @@ TEST(CredentialsTest,
TEST(CredentialsTest,
TestExternalAccountCredsFailureTokenExchangeResponseMissingAccessToken) {
ExecCtx exec_ctx;
Json credential_source("");
Json credential_source = Json::FromString("");
TestExternalAccountCredentials::Options options = {
"external_account", // type;
"audience", // audience;

@ -127,13 +127,13 @@ TEST_F(CertificateProviderStoreTest, Basic) {
CertificateProviderStore::PluginDefinitionMap map = {
{"fake_plugin_1",
{"fake1", fake_factory_1->CreateCertificateProviderConfig(
Json::Object(), nullptr)}},
Json::FromObject({}), nullptr)}},
{"fake_plugin_2",
{"fake2", fake_factory_2->CreateCertificateProviderConfig(
Json::Object(), nullptr)}},
Json::FromObject({}), nullptr)}},
{"fake_plugin_3",
{"fake1", fake_factory_1->CreateCertificateProviderConfig(
Json::Object(), nullptr)}},
Json::FromObject({}), nullptr)}},
};
auto store = MakeOrphanable<CertificateProviderStore>(std::move(map));
// Test for creating certificate providers with known plugin
@ -175,7 +175,7 @@ TEST_F(CertificateProviderStoreTest, Multithreaded) {
CertificateProviderStore::PluginDefinitionMap map = {
{"fake_plugin_1",
{"fake1", fake_factory_1->CreateCertificateProviderConfig(
Json::Object(), nullptr)}}};
Json::FromObject({}), nullptr)}}};
auto store = MakeOrphanable<CertificateProviderStore>(std::move(map));
// Test concurrent `CreateOrGetCertificateProvider()` with the same key.
std::vector<std::thread> threads;

@ -145,7 +145,7 @@ TEST(XdsBootstrapTest, Basic) {
EXPECT_EQ(server->server_uri(), "fake:///lb");
EXPECT_EQ(server->channel_creds_type(), "fake");
EXPECT_TRUE(server->channel_creds_config().empty())
<< JsonDump(Json{server->channel_creds_config()});
<< JsonDump(Json::FromObject(server->channel_creds_config()));
EXPECT_EQ(bootstrap->authorities().size(), 2);
auto* authority = static_cast<const GrpcXdsBootstrap::GrpcAuthority*>(
bootstrap->LookupAuthority("xds.example.com"));
@ -159,7 +159,7 @@ TEST(XdsBootstrapTest, Basic) {
EXPECT_EQ(server->server_uri(), "fake:///xds_server");
EXPECT_EQ(server->channel_creds_type(), "fake");
EXPECT_TRUE(server->channel_creds_config().empty())
<< JsonDump(Json{server->channel_creds_config()});
<< JsonDump(Json::FromObject(server->channel_creds_config()));
authority = static_cast<const GrpcXdsBootstrap::GrpcAuthority*>(
bootstrap->LookupAuthority("xds.example2.com"));
ASSERT_NE(authority, nullptr);
@ -172,7 +172,7 @@ TEST(XdsBootstrapTest, Basic) {
EXPECT_EQ(server->server_uri(), "fake:///xds_server2");
EXPECT_EQ(server->channel_creds_type(), "fake");
EXPECT_TRUE(server->channel_creds_config().empty())
<< JsonDump(Json{server->channel_creds_config()});
<< JsonDump(Json::FromObject(server->channel_creds_config()));
ASSERT_NE(bootstrap->node(), nullptr);
EXPECT_EQ(bootstrap->node()->id(), "foo");
EXPECT_EQ(bootstrap->node()->cluster(), "bar");

@ -713,9 +713,11 @@ class XdsClientTest : public ::testing::Test {
ASSERT_TRUE(metadata_json.ok())
<< metadata_json.status() << " on " << location.file() << ":"
<< location.line();
EXPECT_EQ(*metadata_json, xds_client_->bootstrap().node()->metadata())
<< location.file() << ":" << location.line() << ":\nexpected: "
<< JsonDump(Json{xds_client_->bootstrap().node()->metadata()})
Json expected =
Json::FromObject(xds_client_->bootstrap().node()->metadata());
EXPECT_EQ(*metadata_json, expected)
<< location.file() << ":" << location.line()
<< ":\nexpected: " << JsonDump(expected)
<< "\nactual: " << JsonDump(*metadata_json);
}
EXPECT_EQ(request.node().user_agent_name(), "foo agent")

@ -163,7 +163,7 @@ TEST_F(XdsClusterTest, MinimumValidConfig) {
ASSERT_NE(eds, nullptr);
EXPECT_EQ(eds->eds_service_name, "");
// Check defaults.
EXPECT_EQ(JsonDump(Json{resource.lb_policy_config}),
EXPECT_EQ(JsonDump(Json::FromArray(resource.lb_policy_config)),
"[{\"xds_wrr_locality_experimental\":{\"childPolicy\":"
"[{\"round_robin\":{}}]}}]");
EXPECT_FALSE(resource.lrs_load_reporting_server.has_value());
@ -626,7 +626,7 @@ TEST_F(LbPolicyTest, EnumLbPolicyRingHash) {
ASSERT_TRUE(decode_result.name.has_value());
EXPECT_EQ(*decode_result.name, "foo");
auto& resource = static_cast<XdsClusterResource&>(**decode_result.resource);
EXPECT_EQ(JsonDump(Json{resource.lb_policy_config}),
EXPECT_EQ(JsonDump(Json::FromArray(resource.lb_policy_config)),
"[{\"ring_hash_experimental\":{"
"\"maxRingSize\":8388608,\"minRingSize\":1024}}]");
}
@ -649,7 +649,7 @@ TEST_F(LbPolicyTest, EnumLbPolicyRingHashSetMinAndMaxRingSize) {
ASSERT_TRUE(decode_result.name.has_value());
EXPECT_EQ(*decode_result.name, "foo");
auto& resource = static_cast<XdsClusterResource&>(**decode_result.resource);
EXPECT_EQ(JsonDump(Json{resource.lb_policy_config}),
EXPECT_EQ(JsonDump(Json::FromArray(resource.lb_policy_config)),
"[{\"ring_hash_experimental\":{"
"\"maxRingSize\":4096,\"minRingSize\":2048}}]");
}
@ -804,7 +804,7 @@ TEST_F(LbPolicyTest, LoadBalancingPolicyField) {
ASSERT_TRUE(decode_result.name.has_value());
EXPECT_EQ(*decode_result.name, "foo");
auto& resource = static_cast<XdsClusterResource&>(**decode_result.resource);
EXPECT_EQ(JsonDump(Json{resource.lb_policy_config}),
EXPECT_EQ(JsonDump(Json::FromArray(resource.lb_policy_config)),
"[{\"xds_wrr_locality_experimental\":{"
"\"childPolicy\":[{\"round_robin\":{}}]}}]");
}

@ -302,7 +302,7 @@ TEST_F(XdsFaultInjectionFilterTest, ModifyChannelArgs) {
TEST_F(XdsFaultInjectionFilterTest, GenerateServiceConfigTopLevelConfig) {
XdsHttpFilterImpl::FilterConfig config;
config.config = Json::Object{{"foo", "bar"}};
config.config = Json::FromObject({{"foo", Json::FromString("bar")}});
auto service_config =
filter_->GenerateServiceConfig(config, nullptr, /*filter_name=*/"");
ASSERT_TRUE(service_config.ok()) << service_config.status();
@ -312,9 +312,10 @@ TEST_F(XdsFaultInjectionFilterTest, GenerateServiceConfigTopLevelConfig) {
TEST_F(XdsFaultInjectionFilterTest, GenerateServiceConfigOverrideConfig) {
XdsHttpFilterImpl::FilterConfig top_config;
top_config.config = Json::Object{{"foo", "bar"}};
top_config.config = Json::FromObject({{"foo", Json::FromString("bar")}});
XdsHttpFilterImpl::FilterConfig override_config;
override_config.config = Json::Object{{"baz", "quux"}};
override_config.config =
Json::FromObject({{"baz", Json::FromString("quux")}});
auto service_config = filter_->GenerateServiceConfig(
top_config, &override_config, /*filter_name=*/"");
ASSERT_TRUE(service_config.ok()) << service_config.status();
@ -350,7 +351,7 @@ TEST_P(XdsFaultInjectionFilterConfigTest, EmptyConfig) {
absl::StatusCode::kInvalidArgument, "unexpected errors");
ASSERT_TRUE(config.has_value());
EXPECT_EQ(config->config_proto_type_name, filter_->ConfigProtoName());
EXPECT_EQ(config->config, Json(Json::Object())) << JsonDump(config->config);
EXPECT_EQ(config->config, Json::FromObject({})) << JsonDump(config->config);
}
TEST_P(XdsFaultInjectionFilterConfigTest, BasicConfig) {
@ -514,7 +515,7 @@ TEST_F(XdsRbacFilterTest, GenerateFilterConfig) {
absl::StatusCode::kInvalidArgument, "unexpected errors");
ASSERT_TRUE(config.has_value());
EXPECT_EQ(config->config_proto_type_name, filter_->ConfigProtoName());
EXPECT_EQ(config->config, Json(Json::Object())) << JsonDump(config->config);
EXPECT_EQ(config->config, Json::FromObject({})) << JsonDump(config->config);
}
TEST_F(XdsRbacFilterTest, GenerateFilterConfigTypedStruct) {
@ -558,7 +559,7 @@ TEST_F(XdsRbacFilterTest, GenerateFilterConfigOverride) {
absl::StatusCode::kInvalidArgument, "unexpected errors");
ASSERT_TRUE(config.has_value());
EXPECT_EQ(config->config_proto_type_name, filter_->OverrideConfigProtoName());
EXPECT_EQ(config->config, Json(Json::Object())) << JsonDump(config->config);
EXPECT_EQ(config->config, Json::FromObject({})) << JsonDump(config->config);
}
TEST_F(XdsRbacFilterTest, GenerateFilterConfigOverrideTypedStruct) {
@ -593,14 +594,16 @@ TEST_F(XdsRbacFilterTest, GenerateFilterConfigOverrideUnparseable) {
}
TEST_F(XdsRbacFilterTest, GenerateServiceConfig) {
XdsHttpFilterImpl::FilterConfig hcm_config = {filter_->ConfigProtoName(),
Json::Object{{"name", "foo"}}};
XdsHttpFilterImpl::FilterConfig hcm_config = {
filter_->ConfigProtoName(),
Json::FromObject({{"name", Json::FromString("foo")}})};
auto config = filter_->GenerateServiceConfig(hcm_config, nullptr, "rbac");
ASSERT_TRUE(config.ok()) << config.status();
EXPECT_EQ(config->service_config_field_name, "rbacPolicy");
EXPECT_EQ(
config->element,
JsonDump(Json(Json::Object{{"name", "foo"}, {"filter_name", "rbac"}})));
JsonDump(Json::FromObject({{"name", Json::FromString("foo")},
{"filter_name", Json::FromString("rbac")}})));
}
// For the RBAC filter, the override config is a superset of the
@ -641,7 +644,7 @@ TEST_P(XdsRbacFilterConfigTest, EmptyConfig) {
EXPECT_EQ(config->config_proto_type_name,
GetParam() ? filter_->OverrideConfigProtoName()
: filter_->ConfigProtoName());
EXPECT_EQ(config->config, Json(Json::Object())) << JsonDump(config->config);
EXPECT_EQ(config->config, Json::FromObject({})) << JsonDump(config->config);
}
TEST_P(XdsRbacFilterConfigTest, AllPermissionTypes) {
@ -1131,29 +1134,34 @@ TEST_F(XdsStatefulSessionFilterTest, OverrideConfigDisabled) {
absl::StatusCode::kInvalidArgument, "unexpected errors");
ASSERT_TRUE(config.has_value());
EXPECT_EQ(config->config_proto_type_name, filter_->OverrideConfigProtoName());
EXPECT_EQ(config->config, Json(Json::Object{})) << JsonDump(config->config);
EXPECT_EQ(config->config, Json::FromObject({})) << JsonDump(config->config);
}
TEST_F(XdsStatefulSessionFilterTest, GenerateServiceConfigNoOverride) {
XdsHttpFilterImpl::FilterConfig hcm_config = {filter_->ConfigProtoName(),
Json::Object{{"name", "foo"}}};
XdsHttpFilterImpl::FilterConfig hcm_config = {
filter_->ConfigProtoName(),
Json::FromObject({{"name", Json::FromString("foo")}})};
auto config =
filter_->GenerateServiceConfig(hcm_config, nullptr, /*filter_name=*/"");
ASSERT_TRUE(config.ok()) << config.status();
EXPECT_EQ(config->service_config_field_name, "stateful_session");
EXPECT_EQ(config->element, JsonDump(Json(Json::Object{{"name", "foo"}})));
EXPECT_EQ(config->element,
JsonDump(Json::FromObject({{"name", Json::FromString("foo")}})));
}
TEST_F(XdsStatefulSessionFilterTest, GenerateServiceConfigWithOverride) {
XdsHttpFilterImpl::FilterConfig hcm_config = {filter_->ConfigProtoName(),
Json::Object{{"name", "foo"}}};
XdsHttpFilterImpl::FilterConfig hcm_config = {
filter_->ConfigProtoName(),
Json::FromObject({{"name", Json::FromString("foo")}})};
XdsHttpFilterImpl::FilterConfig override_config = {
filter_->OverrideConfigProtoName(), Json::Object{{"name", "bar"}}};
filter_->OverrideConfigProtoName(),
Json::FromObject({{"name", Json::FromString("bar")}})};
auto config = filter_->GenerateServiceConfig(hcm_config, &override_config,
/*filter_name=*/"");
ASSERT_TRUE(config.ok()) << config.status();
EXPECT_EQ(config->service_config_field_name, "stateful_session");
EXPECT_EQ(config->element, JsonDump(Json(Json::Object{{"name", "bar"}})));
EXPECT_EQ(config->element,
JsonDump(Json::FromObject({{"name", Json::FromString("bar")}})));
}
TEST_F(XdsStatefulSessionFilterTest, GenerateFilterConfigTypedStruct) {
@ -1271,7 +1279,8 @@ TEST_P(XdsStatefulSessionFilterConfigTest, MinimalConfig) {
EXPECT_EQ(config->config_proto_type_name,
GetParam() ? filter_->OverrideConfigProtoName()
: filter_->ConfigProtoName());
EXPECT_EQ(config->config, Json(Json::Object{{"name", "foo"}}))
EXPECT_EQ(config->config,
Json::FromObject({{"name", Json::FromString("foo")}}))
<< JsonDump(config->config);
}
@ -1291,10 +1300,10 @@ TEST_P(XdsStatefulSessionFilterConfigTest, PathAndTtl) {
EXPECT_EQ(config->config_proto_type_name,
GetParam() ? filter_->OverrideConfigProtoName()
: filter_->ConfigProtoName());
EXPECT_EQ(config->config, Json(Json::Object{
{"name", "foo"},
{"path", "/service/method"},
{"ttl", "3.000000000s"},
EXPECT_EQ(config->config, Json::FromObject({
{"name", Json::FromString("foo")},
{"path", Json::FromString("/service/method")},
{"ttl", Json::FromString("3.000000000s")},
}))
<< JsonDump(config->config);
}

@ -159,7 +159,7 @@ TEST(ClientSideWeightedRoundRobinTest, FieldsExplicitlySet) {
"{\"weighted_round_robin\":{"
"\"blackoutPeriod\":\"2.000000000s\","
"\"enableOobLoadReport\":true,"
"\"errorUtilizationPenalty\":5.000000,"
"\"errorUtilizationPenalty\":5,"
"\"oobReportingPeriod\":\"1.000000000s\","
"\"weightExpirationPeriod\":\"3.000000000s\","
"\"weightUpdatePeriod\":\"4.000000000s\""

@ -472,7 +472,7 @@ class ChannelzSampler final {
std::string type = "Channel";
std::string description;
::google::protobuf::TextFormat::PrintToString(channel.data(), &description);
grpc_core::Json description_json = grpc_core::Json(description);
grpc_core::Json description_json = grpc_core::Json::FromString(description);
StoreEntityInJson(id, type, description_json);
}
@ -483,7 +483,7 @@ class ChannelzSampler final {
std::string description;
::google::protobuf::TextFormat::PrintToString(subchannel.data(),
&description);
grpc_core::Json description_json = grpc_core::Json(description);
grpc_core::Json description_json = grpc_core::Json::FromString(description);
StoreEntityInJson(id, type, description_json);
}
@ -493,7 +493,7 @@ class ChannelzSampler final {
std::string type = "Server";
std::string description;
::google::protobuf::TextFormat::PrintToString(server.data(), &description);
grpc_core::Json description_json = grpc_core::Json(description);
grpc_core::Json description_json = grpc_core::Json::FromString(description);
StoreEntityInJson(id, type, description_json);
}
@ -503,7 +503,7 @@ class ChannelzSampler final {
std::string type = "Socket";
std::string description;
::google::protobuf::TextFormat::PrintToString(socket.data(), &description);
grpc_core::Json description_json = grpc_core::Json(description);
grpc_core::Json description_json = grpc_core::Json::FromString(description);
StoreEntityInJson(id, type, description_json);
}
@ -523,18 +523,19 @@ class ChannelzSampler final {
const time_t time_ago = ago.tv_sec;
ss << std::put_time(std::localtime(&time_ago), "%F %T");
start = ss.str();
grpc_core::Json obj =
grpc_core::Json::Object{{"Task", absl::StrFormat("%s_ID%s", type, id)},
{"Start", start},
{"Finish", finish},
{"ID", id},
{"Type", type},
{"Description", description}};
grpc_core::Json obj = grpc_core::Json::FromObject(
{{"Task",
grpc_core::Json::FromString(absl::StrFormat("%s_ID%s", type, id))},
{"Start", grpc_core::Json::FromString(start)},
{"Finish", grpc_core::Json::FromString(finish)},
{"ID", grpc_core::Json::FromString(id)},
{"Type", grpc_core::Json::FromString(type)},
{"Description", description}});
json_.push_back(obj);
}
// Dump data in json
std::string DumpJson() { return JsonDump(grpc_core::Json(json_)); }
std::string DumpJson() { return JsonDump(grpc_core::Json::FromArray(json_)); }
// Check if one entity has been recorded
bool CheckID(int64_t id) {

Loading…
Cancel
Save