refactor: Rename static constants (#3073)

This commit is contained in:
Alex Kremer
2026-05-13 12:09:06 +01:00
committed by GitHub
parent d056c72212
commit dbc98894ba
301 changed files with 6954 additions and 7117 deletions

View File

@@ -169,7 +169,7 @@ CheckOptions:
readability-identifier-naming.EnumCase: CamelCase
readability-identifier-naming.EnumConstantCase: CamelCase
readability-identifier-naming.ScopedEnumConstantCase: CamelCase
readability-identifier-naming.GlobalConstantCase: UPPER_CASE
readability-identifier-naming.GlobalConstantCase: CamelCase
readability-identifier-naming.GlobalConstantPrefix: "k"
readability-identifier-naming.GlobalVariableCase: CamelCase
readability-identifier-naming.GlobalVariablePrefix: "g"
@@ -177,14 +177,12 @@ CheckOptions:
readability-identifier-naming.ConstexprMethodCase: camelBack
readability-identifier-naming.ClassMethodCase: camelBack
readability-identifier-naming.ClassMemberCase: camelBack
readability-identifier-naming.ClassConstantCase: UPPER_CASE
readability-identifier-naming.ClassConstantCase: CamelCase
readability-identifier-naming.ClassConstantPrefix: "k"
readability-identifier-naming.StaticConstantCase: UPPER_CASE
readability-identifier-naming.StaticConstantCase: CamelCase
readability-identifier-naming.StaticConstantPrefix: "k"
readability-identifier-naming.StaticVariableCase: UPPER_CASE
readability-identifier-naming.StaticVariablePrefix: "k"
readability-identifier-naming.ConstexprVariableCase: UPPER_CASE
readability-identifier-naming.ConstexprVariablePrefix: "k"
readability-identifier-naming.StaticVariableCase: camelBack
readability-identifier-naming.ConstexprVariableCase: camelBack
readability-identifier-naming.LocalConstantCase: camelBack
readability-identifier-naming.LocalVariableCase: camelBack
readability-identifier-naming.TemplateParameterCase: CamelCase

View File

@@ -26,7 +26,7 @@ using namespace util::config;
namespace {
auto const kCONFIG = ClioConfigDefinition{
auto const kConfig = ClioConfigDefinition{
{"prometheus.compress_reply", ConfigValue{ConfigType::Boolean}.defaultValue(true)},
{"prometheus.enabled", ConfigValue{ConfigType::Boolean}.defaultValue(true)},
{"log.channels.[].channel", Array{ConfigValue{ConfigType::String}}},
@@ -48,10 +48,10 @@ auto const kCONFIG = ClioConfigDefinition{
void
init()
{
static std::once_flag kONCE;
std::call_once(kONCE, [] {
PrometheusService::init(kCONFIG);
(void)util::LogService::init(kCONFIG);
static std::once_flag kOnce;
std::call_once(kOnce, [] {
PrometheusService::init(kConfig);
(void)util::LogService::init(kConfig);
});
}

View File

@@ -169,11 +169,11 @@ public:
static auto
generateData()
{
constexpr auto kTOTAL = 10'000;
constexpr auto kTotal = 10'000;
std::vector<uint64_t> data;
data.reserve(kTOTAL);
data.reserve(kTotal);
util::MTRandomGenerator randomGenerator;
for (auto i = 0; i < kTOTAL; ++i)
for (auto i = 0; i < kTotal; ++i)
data.push_back(randomGenerator.uniform(1, 100'000'000));
return data;

View File

@@ -21,7 +21,7 @@
using namespace util;
static constexpr auto kLOG_FORMAT = "%Y-%m-%d %H:%M:%S.%f %^%3!l:%n%$ - %v";
static constexpr auto kLogFormat = "%Y-%m-%d %H:%M:%S.%f %^%3!l:%n%$ - %v";
struct BenchmarkLoggingInitializer {
[[nodiscard]] static std::shared_ptr<spdlog::sinks::sink>
@@ -32,7 +32,7 @@ struct BenchmarkLoggingInitializer {
.logDir = logDir,
.rotation = LogService::RotationParams{.sizeMB = sizeMB, .maxFiles = maxFiles},
},
kLOG_FORMAT
kLogFormat
);
}
@@ -71,9 +71,9 @@ benchmarkConcurrentFileLogging(benchmark::State& state)
state.PauseTiming();
std::filesystem::create_directories(logDir);
static constexpr size_t kQUEUE_SIZE = 8192;
static constexpr size_t kTHREAD_COUNT = 1;
spdlog::init_thread_pool(kQUEUE_SIZE, kTHREAD_COUNT);
static constexpr size_t kQueueSize = 8192;
static constexpr size_t kThreadCount = 1;
spdlog::init_thread_pool(kQueueSize, kThreadCount);
auto fileSink = BenchmarkLoggingInitializer::createFileSink(logDir, 5, 25);

View File

@@ -28,7 +28,7 @@ CliArgs::parse(int argc, char const* argv[])
description.add_options()
("help,h", "Print help message and exit")
("version,v", "Print version and exit")
("conf,c", po::value<std::string>()->default_value(kDEFAULT_CONFIG_PATH), "Configuration file")
("conf,c", po::value<std::string>()->default_value(kDefaultConfigPath), "Configuration file")
("ng-web-server,w", "Use ng-web-server")
("migrate", po::value<std::string>(), "Start migration helper")
("verify", "Checks the validity of config values")

View File

@@ -16,7 +16,7 @@ public:
/**
* @brief Default configuration path.
*/
static constexpr char kDEFAULT_CONFIG_PATH[] = "/etc/opt/clio/config.json";
static constexpr char kDefaultConfigPath[] = "/etc/opt/clio/config.json";
/**
* @brief An action parsed from the command line.

View File

@@ -125,7 +125,7 @@ HealthCheckHandler::operator()(
boost::asio::yield_context
)
{
static constexpr auto kHEALTH_CHECK_HTML = R"html(
static constexpr auto kHealthCheckHtml = R"html(
<!DOCTYPE html>
<html>
<head><title>Test page for Clio</title></head>
@@ -133,7 +133,7 @@ HealthCheckHandler::operator()(
</html>
)html";
return web::ng::Response{boost::beast::http::status::ok, kHEALTH_CHECK_HTML, request};
return web::ng::Response{boost::beast::http::status::ok, kHealthCheckHtml, request};
}
web::ng::Response
@@ -144,7 +144,7 @@ CacheStateHandler::operator()(
boost::asio::yield_context
)
{
static constexpr auto kCACHE_CHECK_LOADED_HTML = R"html(
static constexpr auto kCacheCheckLoadedHtml = R"html(
<!DOCTYPE html>
<html>
<head><title>Cache state</title></head>
@@ -152,7 +152,7 @@ CacheStateHandler::operator()(
</html>
)html";
static constexpr auto kCACHE_CHECK_NOT_LOADED_HTML = R"html(
static constexpr auto kCacheCheckNotLoadedHtml = R"html(
<!DOCTYPE html>
<html>
<head><title>Cache state</title></head>
@@ -161,10 +161,10 @@ CacheStateHandler::operator()(
)html";
if (cache_.get().isFull())
return web::ng::Response{boost::beast::http::status::ok, kCACHE_CHECK_LOADED_HTML, request};
return web::ng::Response{boost::beast::http::status::ok, kCacheCheckLoadedHtml, request};
return web::ng::Response{
boost::beast::http::status::service_unavailable, kCACHE_CHECK_NOT_LOADED_HTML, request
boost::beast::http::status::service_unavailable, kCacheCheckNotLoadedHtml, request
};
}

View File

@@ -22,12 +22,11 @@ namespace cluster {
namespace {
struct JsonFields {
static constexpr std::string_view const kUPDATE_TIME = "update_time";
static constexpr std::string_view const kDB_ROLE = "db_role";
static constexpr std::string_view const kETL_STARTED = "etl_started";
static constexpr std::string_view const kCACHE_IS_FULL = "cache_is_full";
static constexpr std::string_view const kCACHE_IS_CURRENTLY_LOADING =
"cache_is_currently_loading";
static constexpr std::string_view const kUpdateTime = "update_time";
static constexpr std::string_view const kDbRole = "db_role";
static constexpr std::string_view const kEtlStarted = "etl_started";
static constexpr std::string_view const kCacheIsFull = "cache_is_full";
static constexpr std::string_view const kCacheIsCurrentlyLoading = "cache_is_currently_loading";
};
} // namespace
@@ -67,11 +66,11 @@ void
tag_invoke(boost::json::value_from_tag, boost::json::value& jv, ClioNode const& node)
{
jv = {
{JsonFields::kUPDATE_TIME, util::systemTpToUtcStr(node.updateTime, ClioNode::kTIME_FORMAT)},
{JsonFields::kDB_ROLE, static_cast<int64_t>(node.dbRole)},
{JsonFields::kETL_STARTED, node.etlStarted},
{JsonFields::kCACHE_IS_FULL, node.cacheIsFull},
{JsonFields::kCACHE_IS_CURRENTLY_LOADING, node.cacheIsCurrentlyLoading}
{JsonFields::kUpdateTime, util::systemTpToUtcStr(node.updateTime, ClioNode::kTimeFormat)},
{JsonFields::kDbRole, static_cast<int64_t>(node.dbRole)},
{JsonFields::kEtlStarted, node.etlStarted},
{JsonFields::kCacheIsFull, node.cacheIsFull},
{JsonFields::kCacheIsCurrentlyLoading, node.cacheIsCurrentlyLoading}
};
}
@@ -79,16 +78,16 @@ ClioNode
tag_invoke(boost::json::value_to_tag<ClioNode>, boost::json::value const& jv)
{
auto const& obj = jv.as_object();
auto const& updateTimeStr = obj.at(JsonFields::kUPDATE_TIME).as_string();
auto const& updateTimeStr = obj.at(JsonFields::kUpdateTime).as_string();
auto const updateTime =
util::systemTpFromUtcStr(std::string(updateTimeStr), ClioNode::kTIME_FORMAT);
util::systemTpFromUtcStr(std::string(updateTimeStr), ClioNode::kTimeFormat);
if (!updateTime.has_value()) {
throw std::runtime_error("Failed to parse update time");
}
// Each field has a default value for backward compatibility
auto dbRole = ClioNode::DbRole::Fallback;
if (auto const* v = obj.if_contains(JsonFields::kDB_ROLE)) {
if (auto const* v = obj.if_contains(JsonFields::kDbRole)) {
auto const dbRoleValue = v->as_int64();
if (dbRoleValue > static_cast<int64_t>(ClioNode::DbRole::Max))
throw std::runtime_error("Invalid db_role value");
@@ -96,12 +95,11 @@ tag_invoke(boost::json::value_to_tag<ClioNode>, boost::json::value const& jv)
}
auto const etlStarted =
obj.contains(JsonFields::kETL_STARTED) ? obj.at(JsonFields::kETL_STARTED).as_bool() : true;
auto const cacheIsFull = obj.contains(JsonFields::kCACHE_IS_FULL)
? obj.at(JsonFields::kCACHE_IS_FULL).as_bool()
: true;
auto const cacheIsCurrentlyLoading = obj.contains(JsonFields::kCACHE_IS_CURRENTLY_LOADING)
? obj.at(JsonFields::kCACHE_IS_CURRENTLY_LOADING).as_bool()
obj.contains(JsonFields::kEtlStarted) ? obj.at(JsonFields::kEtlStarted).as_bool() : true;
auto const cacheIsFull =
obj.contains(JsonFields::kCacheIsFull) ? obj.at(JsonFields::kCacheIsFull).as_bool() : true;
auto const cacheIsCurrentlyLoading = obj.contains(JsonFields::kCacheIsCurrentlyLoading)
? obj.at(JsonFields::kCacheIsCurrentlyLoading).as_bool()
: false;
return ClioNode{

View File

@@ -19,7 +19,7 @@ struct ClioNode {
/**
* @brief The format of the time to store in the database.
*/
static constexpr char const* kTIME_FORMAT = "%Y-%m-%dT%H:%M:%SZ";
static constexpr char const* kTimeFormat = "%Y-%m-%dT%H:%M:%SZ";
/**
* @brief Database role of a node in the cluster.

View File

@@ -36,8 +36,8 @@ class ClusterCommunicationService : public ClusterCommunicationServiceTag {
CacheLoaderDecider cacheLoaderDecider_;
public:
static constexpr std::chrono::milliseconds kDEFAULT_READ_INTERVAL{1000};
static constexpr std::chrono::milliseconds kDEFAULT_WRITE_INTERVAL{1000};
static constexpr std::chrono::milliseconds kDefaultReadInterval{1000};
static constexpr std::chrono::milliseconds kDefaultWriteInterval{1000};
/**
* @brief Construct a new Cluster Communication Service object.
@@ -52,8 +52,8 @@ public:
std::shared_ptr<data::BackendInterface> backend,
std::unique_ptr<etl::WriterStateInterface> writerState,
std::unique_ptr<data::LedgerCacheLoadingStateInterface> cacheLoadingState,
std::chrono::steady_clock::duration readInterval = kDEFAULT_READ_INTERVAL,
std::chrono::steady_clock::duration writeInterval = kDEFAULT_WRITE_INTERVAL
std::chrono::steady_clock::duration readInterval = kDefaultReadInterval,
std::chrono::steady_clock::duration writeInterval = kDefaultWriteInterval
);
~ClusterCommunicationService() override;

View File

@@ -63,7 +63,7 @@ namespace cluster {
*/
class WriterDecider {
public:
static constexpr std::chrono::steady_clock::duration kRECOVERY_TIME = std::chrono::hours{1};
static constexpr std::chrono::steady_clock::duration kRecoveryTime = std::chrono::hours{1};
private:
/** @brief Thread pool for spawning asynchronous tasks */
@@ -90,12 +90,12 @@ public:
* @param ctx Thread pool for executing asynchronous operations
* @param writerState Writer state interface for controlling write operations
* @param recoveryTime How long to wait in Fallback before attempting recovery
* (defaults to `kRECOVERY_TIME`; pass a short duration in tests)
* (defaults to `kRecoveryTime`; pass a short duration in tests)
*/
WriterDecider(
boost::asio::thread_pool& ctx,
std::unique_ptr<etl::WriterStateInterface> writerState,
std::chrono::steady_clock::duration recoveryTime = kRECOVERY_TIME
std::chrono::steady_clock::duration recoveryTime = kRecoveryTime
);
/**

View File

@@ -33,8 +33,8 @@ namespace {
std::unordered_set<std::string>&
supportedAmendments()
{
static std::unordered_set<std::string> kAMENDMENTS = {};
return kAMENDMENTS;
static std::unordered_set<std::string> kAmendments = {};
return kAmendments;
}
bool

View File

@@ -17,7 +17,7 @@ namespace data {
namespace {
std::vector<std::int64_t> const kHISTOGRAM_BUCKETS{1, 2, 5, 10, 20, 50, 100, 200, 500, 700, 1000};
std::vector<std::int64_t> const kHistogramBuckets{1, 2, 5, 10, 20, 50, 100, 200, 500, 700, 1000};
std::int64_t
durationInMillisecondsSince(std::chrono::steady_clock::time_point const startTime)
@@ -60,7 +60,7 @@ BackendCounters::BackendCounters()
PrometheusService::histogramInt(
"backend_duration_milliseconds_histogram",
Labels({Label{"operation", "read"}}),
kHISTOGRAM_BUCKETS,
kHistogramBuckets,
"The duration of backend read operations including retries"
)
)
@@ -68,7 +68,7 @@ BackendCounters::BackendCounters()
PrometheusService::histogramInt(
"backend_duration_milliseconds_histogram",
Labels({Label{"operation", "write"}}),
kHISTOGRAM_BUCKETS,
kHistogramBuckets,
"The duration of backend write operations including retries"
)
)

View File

@@ -311,7 +311,7 @@ BackendInterface::fetchLedgerPage(
ripple::uint256 const& curCursor = [&]() {
if (!keys.empty())
return keys.back();
return (cursor ? *cursor : kFIRST_KEY);
return (cursor ? *cursor : kFirstKey);
}();
// NOLINTNEXTLINE(bugprone-unchecked-optional-access)

View File

@@ -49,7 +49,7 @@ public:
}
};
static constexpr std::size_t kDEFAULT_WAIT_BETWEEN_RETRY = 500;
static constexpr std::size_t kDefaultWaitBetweenRetry = 500;
/**
* @brief A helper function that catches DatabaseTimeout exceptions and retries indefinitely.
*
@@ -60,7 +60,7 @@ static constexpr std::size_t kDEFAULT_WAIT_BETWEEN_RETRY = 500;
*/
template <typename FnType>
auto
retryOnTimeout(FnType func, size_t waitMs = kDEFAULT_WAIT_BETWEEN_RETRY)
retryOnTimeout(FnType func, size_t waitMs = kDefaultWaitBetweenRetry)
{
static util::Logger const log{"Backend"}; // NOLINT(readability-identifier-naming)

View File

@@ -209,13 +209,13 @@ template <typename T>
inline bool
isDirNode(T const& object)
{
static constexpr auto kMIN_SIZE_REQUIRED = 3;
if (std::size(object) < kMIN_SIZE_REQUIRED)
static constexpr auto kMinSizeRequired = 3;
if (std::size(object) < kMinSizeRequired)
return false;
static constexpr short kDIR_NODE_SPACE_KEY = 0x0064;
static constexpr short kDirNodeSpaceKey = 0x0064;
short const spaceKey = (object.data()[1] << 8) | object.data()[2];
return spaceKey == kDIR_NODE_SPACE_KEY;
return spaceKey == kDirNodeSpaceKey;
}
/**
@@ -246,12 +246,12 @@ template <typename T>
inline ripple::uint256
getBookBase(T const& key)
{
static constexpr size_t kEY_SIZE = 24;
static constexpr size_t kEySize = 24;
ASSERT(key.size() == ripple::uint256::size(), "Invalid key size {}", key.size());
ripple::uint256 ret;
for (size_t i = 0; i < kEY_SIZE; ++i)
for (size_t i = 0; i < kEySize; ++i)
ret.data()[i] = key.data()[i];
return ret;
@@ -270,4 +270,4 @@ uint256ToString(ripple::uint256 const& input)
}
/** @brief The ripple epoch start timestamp. Midnight on 1st January 2000. */
static constexpr std::uint32_t kRIPPLE_EPOCH_START = 946684800;
static constexpr std::uint32_t kRippleEpochStart = 946684800;

View File

@@ -312,13 +312,13 @@ struct AmendmentKey {
operator<=>(AmendmentKey const& other) const = default;
};
constexpr ripple::uint256 kFIRST_KEY{
constexpr ripple::uint256 kFirstKey{
"0000000000000000000000000000000000000000000000000000000000000000"
};
constexpr ripple::uint256 kLAST_KEY{
constexpr ripple::uint256 kLastKey{
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
};
constexpr ripple::uint256 kHI192{
constexpr ripple::uint256 kHi192{
"0000000000000000000000000000000000000000000000001111111111111111"
};

View File

@@ -603,7 +603,7 @@ public:
if (auto const res = executor_.read(yield, schema_->selectSuccessor, key, ledgerSequence);
res) {
if (auto const result = res->template get<ripple::uint256>(); result) {
if (*result == kLAST_KEY)
if (*result == kLastKey)
return std::nullopt;
return result;
}

View File

@@ -90,13 +90,13 @@ SettingsProvider::parseSettings() const
if (config_.getValueView("connect_timeout").hasValue()) {
auto const connectTimeoutSecond = config_.get<uint32_t>("connect_timeout");
settings.connectionTimeout =
std::chrono::milliseconds{connectTimeoutSecond * util::kMILLISECONDS_PER_SECOND};
std::chrono::milliseconds{connectTimeoutSecond * util::kMillisecondsPerSecond};
}
if (config_.getValueView("request_timeout").hasValue()) {
auto const requestTimeoutSecond = config_.get<uint32_t>("request_timeout");
settings.requestTimeout =
std::chrono::milliseconds{requestTimeoutSecond * util::kMILLISECONDS_PER_SECOND};
std::chrono::milliseconds{requestTimeoutSecond * util::kMillisecondsPerSecond};
}
settings.certificate = parseOptionalCertificate();

View File

@@ -12,7 +12,7 @@
#include <vector>
namespace {
constexpr auto kBATCH_DELETER = [](CassBatch* ptr) { cass_batch_free(ptr); };
constexpr auto kBatchDeleter = [](CassBatch* ptr) { cass_batch_free(ptr); };
} // namespace
namespace data::cassandra::impl {
@@ -29,7 +29,7 @@ namespace data::cassandra::impl {
* https://docs.datastax.com/en/developer/cpp-driver-dse/1.10/features/basics/batches/index.html
*/
Batch::Batch(std::vector<Statement> const& statements)
: ManagedObject{cass_batch_new(CASS_BATCH_TYPE_UNLOGGED), kBATCH_DELETER}
: ManagedObject{cass_batch_new(CASS_BATCH_TYPE_UNLOGGED), kBatchDeleter}
{
cass_batch_set_is_idempotent(*this, cass_true);

View File

@@ -14,13 +14,13 @@
namespace {
constexpr auto kCLUSTER_DELETER = [](CassCluster* ptr) { cass_cluster_free(ptr); };
constexpr auto kClusterDeleter = [](CassCluster* ptr) { cass_cluster_free(ptr); };
}; // namespace
namespace data::cassandra::impl {
Cluster::Cluster(Settings const& settings) : ManagedObject{cass_cluster_new(), kCLUSTER_DELETER}
Cluster::Cluster(Settings const& settings) : ManagedObject{cass_cluster_new(), kClusterDeleter}
{
using std::to_string;

View File

@@ -35,11 +35,11 @@ providerFromString(std::string const& provider)
* @brief Bundles all cassandra settings in one place.
*/
struct Settings {
static constexpr std::size_t kDEFAULT_CONNECTION_TIMEOUT = 10000;
static constexpr uint32_t kDEFAULT_MAX_WRITE_REQUESTS_OUTSTANDING = 10'000;
static constexpr uint32_t kDEFAULT_MAX_READ_REQUESTS_OUTSTANDING = 100'000;
static constexpr std::size_t kDEFAULT_BATCH_SIZE = 20;
static constexpr Provider kDEFAULT_PROVIDER = Provider::Cassandra;
static constexpr std::size_t kDefaultConnectionTimeout = 10000;
static constexpr uint32_t kDefaultMaxWriteRequestsOutstanding = 10'000;
static constexpr uint32_t kDefaultMaxReadRequestsOutstanding = 100'000;
static constexpr std::size_t kDefaultBatchSize = 20;
static constexpr Provider kDefaultProvider = Provider::Cassandra;
/**
* @brief Represents the configuration of contact points for cassandra.
@@ -61,7 +61,7 @@ struct Settings {
/** @brief Connect timeout specified in milliseconds */
std::chrono::milliseconds connectionTimeout =
std::chrono::milliseconds{kDEFAULT_CONNECTION_TIMEOUT};
std::chrono::milliseconds{kDefaultConnectionTimeout};
/** @brief Request timeout specified in milliseconds */
std::chrono::milliseconds requestTimeout = std::chrono::milliseconds{0}; // no timeout at all
@@ -73,19 +73,19 @@ struct Settings {
uint32_t threads = std::thread::hardware_concurrency();
/** @brief The maximum number of outstanding write requests at any given moment */
uint32_t maxWriteRequestsOutstanding = kDEFAULT_MAX_WRITE_REQUESTS_OUTSTANDING;
uint32_t maxWriteRequestsOutstanding = kDefaultMaxWriteRequestsOutstanding;
/** @brief The maximum number of outstanding read requests at any given moment */
uint32_t maxReadRequestsOutstanding = kDEFAULT_MAX_READ_REQUESTS_OUTSTANDING;
uint32_t maxReadRequestsOutstanding = kDefaultMaxReadRequestsOutstanding;
/** @brief The number of connection per host to always have active */
uint32_t coreConnectionsPerHost = 3u;
/** @brief Size of batches when writing */
std::size_t writeBatchSize = kDEFAULT_BATCH_SIZE;
std::size_t writeBatchSize = kDefaultBatchSize;
/** @brief Provider to know if we are using scylladb or keyspace */
Provider provider = kDEFAULT_PROVIDER;
Provider provider = kDefaultProvider;
/** @brief Size of the IO queue */
std::optional<uint32_t> queueSizeIO =

View File

@@ -14,7 +14,7 @@
namespace data::cassandra::impl {
class Collection : public ManagedObject<CassCollection> {
static constexpr auto kDELETER = [](CassCollection* ptr) { cass_collection_free(ptr); };
static constexpr auto kDeleter = [](CassCollection* ptr) { cass_collection_free(ptr); };
static void
throwErrorIfNeeded(CassError const rc, std::string_view const label)
@@ -30,7 +30,7 @@ public:
template <typename Type>
explicit Collection(std::vector<Type> const& value)
: ManagedObject{cass_collection_new(CASS_COLLECTION_TYPE_LIST, value.size()), kDELETER}
: ManagedObject{cass_collection_new(CASS_COLLECTION_TYPE_LIST, value.size()), kDeleter}
{
bind(value);
}

View File

@@ -13,12 +13,12 @@
#include <utility>
namespace {
constexpr auto kFUTURE_DELETER = [](CassFuture* ptr) { cass_future_free(ptr); };
constexpr auto kFutureDeleter = [](CassFuture* ptr) { cass_future_free(ptr); };
} // namespace
namespace data::cassandra::impl {
/* implicit */ Future::Future(CassFuture* ptr) : ManagedObject{ptr, kFUTURE_DELETER}
/* implicit */ Future::Future(CassFuture* ptr) : ManagedObject{ptr, kFutureDeleter}
{
}

View File

@@ -7,13 +7,13 @@
#include <cstddef>
namespace {
constexpr auto kRESULT_DELETER = [](CassResult const* ptr) { cass_result_free(ptr); };
constexpr auto kRESULT_ITERATOR_DELETER = [](CassIterator* ptr) { cass_iterator_free(ptr); };
constexpr auto kResultDeleter = [](CassResult const* ptr) { cass_result_free(ptr); };
constexpr auto kResultIteratorDeleter = [](CassIterator* ptr) { cass_iterator_free(ptr); };
} // namespace
namespace data::cassandra::impl {
/* implicit */ Result::Result(CassResult const* ptr) : ManagedObject{ptr, kRESULT_DELETER}
/* implicit */ Result::Result(CassResult const* ptr) : ManagedObject{ptr, kResultDeleter}
{
}
@@ -30,7 +30,7 @@ Result::hasRows() const
}
/* implicit */ ResultIterator::ResultIterator(CassIterator* ptr)
: ManagedObject{ptr, kRESULT_ITERATOR_DELETER}, hasMore_{cass_iterator_next(ptr) != 0u}
: ManagedObject{ptr, kResultIteratorDeleter}, hasMore_{cass_iterator_next(ptr) != 0u}
{
}

View File

@@ -7,10 +7,10 @@
namespace data::cassandra::impl {
class Session : public ManagedObject<CassSession> {
static constexpr auto kDELETER = [](CassSession* ptr) { cass_session_free(ptr); };
static constexpr auto kDeleter = [](CassSession* ptr) { cass_session_free(ptr); };
public:
Session() : ManagedObject{cass_session_new(), kDELETER}
Session() : ManagedObject{cass_session_new(), kDeleter}
{
}
};

View File

@@ -8,13 +8,13 @@
#include <string>
namespace {
constexpr auto kCONTEXT_DELETER = [](CassSsl* ptr) { cass_ssl_free(ptr); };
constexpr auto kContextDeleter = [](CassSsl* ptr) { cass_ssl_free(ptr); };
} // namespace
namespace data::cassandra::impl {
SslContext::SslContext(std::string const& certificate)
: ManagedObject{cass_ssl_new(), kCONTEXT_DELETER}
: ManagedObject{cass_ssl_new(), kContextDeleter}
{
cass_ssl_set_verify_flags(*this, CASS_SSL_VERIFY_NONE);
if (auto const rc = cass_ssl_add_trusted_cert(*this, certificate.c_str()); rc != CASS_OK) {

View File

@@ -26,7 +26,7 @@
namespace data::cassandra::impl {
class Statement : public ManagedObject<CassStatement> {
static constexpr auto kDELETER = [](CassStatement* ptr) { cass_statement_free(ptr); };
static constexpr auto kDeleter = [](CassStatement* ptr) { cass_statement_free(ptr); };
public:
/**
@@ -37,7 +37,7 @@ public:
*/
template <typename... Args>
explicit Statement(std::string_view query, Args&&... args)
: ManagedObject{cass_statement_new_n(query.data(), query.size(), sizeof...(args)), kDELETER}
: ManagedObject{cass_statement_new_n(query.data(), query.size(), sizeof...(args)), kDeleter}
{
// TODO: figure out how to set consistency level in config
// NOTE: Keyspace doesn't support QUORUM at write level
@@ -46,7 +46,7 @@ public:
bind<Args...>(std::forward<Args>(args)...);
}
/* implicit */ Statement(CassStatement* ptr) : ManagedObject{ptr, kDELETER}
/* implicit */ Statement(CassStatement* ptr) : ManagedObject{ptr, kDeleter}
{
// cass_statement_set_consistency(*this, CASS_CONSISTENCY_LOCAL_QUORUM);
cass_statement_set_is_idempotent(*this, cass_true);
@@ -157,10 +157,10 @@ public:
* This is used to produce Statement objects that can be executed.
*/
class PreparedStatement : public ManagedObject<CassPrepared const> {
static constexpr auto kDELETER = [](CassPrepared const* ptr) { cass_prepared_free(ptr); };
static constexpr auto kDeleter = [](CassPrepared const* ptr) { cass_prepared_free(ptr); };
public:
/* implicit */ PreparedStatement(CassPrepared const* ptr) : ManagedObject{ptr, kDELETER}
/* implicit */ PreparedStatement(CassPrepared const* ptr) : ManagedObject{ptr, kDeleter}
{
}

View File

@@ -5,18 +5,18 @@
#include <cassandra.h>
namespace {
constexpr auto kTUPLE_DELETER = [](CassTuple* ptr) { cass_tuple_free(ptr); };
constexpr auto kTUPLE_ITERATOR_DELETER = [](CassIterator* ptr) { cass_iterator_free(ptr); };
constexpr auto kTupleDeleter = [](CassTuple* ptr) { cass_tuple_free(ptr); };
constexpr auto kTupleIteratorDeleter = [](CassIterator* ptr) { cass_iterator_free(ptr); };
} // namespace
namespace data::cassandra::impl {
/* implicit */ Tuple::Tuple(CassTuple* ptr) : ManagedObject{ptr, kTUPLE_DELETER}
/* implicit */ Tuple::Tuple(CassTuple* ptr) : ManagedObject{ptr, kTupleDeleter}
{
}
/* implicit */ TupleIterator::TupleIterator(CassIterator* ptr)
: ManagedObject{ptr, kTUPLE_ITERATOR_DELETER}
: ManagedObject{ptr, kTupleIteratorDeleter}
{
}

View File

@@ -18,14 +18,14 @@
namespace data::cassandra::impl {
class Tuple : public ManagedObject<CassTuple> {
static constexpr auto kDELETER = [](CassTuple* ptr) { cass_tuple_free(ptr); };
static constexpr auto kDeleter = [](CassTuple* ptr) { cass_tuple_free(ptr); };
public:
/* implicit */ Tuple(CassTuple* ptr);
template <typename... Types>
explicit Tuple(std::tuple<Types...>&& value)
: ManagedObject{cass_tuple_new(std::tuple_size<std::tuple<Types...>>{}), kDELETER}
: ManagedObject{cass_tuple_new(std::tuple_size<std::tuple<Types...>>{}), kDeleter}
{
std::apply(std::bind_front(&Tuple::bind<Types...>, this), std::move(value));
}

View File

@@ -19,7 +19,7 @@ namespace data::impl {
using Hash = ripple::uint256;
using Separator = std::array<char, 16>;
static constexpr Separator kSEPARATOR = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
static constexpr Separator kSeparator = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
namespace {
@@ -78,7 +78,7 @@ LedgerCacheFile::write(DataView dataView)
.deletedSize = dataView.deleted.size()
};
file.write(header);
file.write(kSEPARATOR);
file.write(kSeparator);
for (auto const& [k, v] : dataView.map) {
file.write(k.data(), decltype(k)::bytes);
@@ -86,7 +86,7 @@ LedgerCacheFile::write(DataView dataView)
file.write(v.blob.size());
file.writeRaw(reinterpret_cast<char const*>(v.blob.data()), v.blob.size());
}
file.write(kSEPARATOR);
file.write(kSeparator);
for (auto const& [k, v] : dataView.deleted) {
file.write(k.data(), decltype(k)::bytes);
@@ -94,7 +94,7 @@ LedgerCacheFile::write(DataView dataView)
file.write(v.blob.size());
file.writeRaw(reinterpret_cast<char const*>(v.blob.data()), v.blob.size());
}
file.write(kSEPARATOR);
file.write(kSeparator);
auto const hash = file.hash();
file.write(hash.data(), decltype(hash)::bytes);
@@ -129,9 +129,9 @@ LedgerCacheFile::read(uint32_t minLatestSequence)
if (not file.read(header)) {
return std::unexpected{"Error reading cache header"};
}
if (header.version != kVERSION) {
if (header.version != kVersion) {
return std::unexpected{fmt::format(
"Cache has wrong version: expected {} found {}", kVERSION, header.version
"Cache has wrong version: expected {} found {}", kVersion, header.version
)};
}
if (header.latestSeq < minLatestSequence) {

View File

@@ -17,14 +17,14 @@ namespace data::impl {
class LedgerCacheFile {
public:
struct Header {
uint32_t version = kVERSION;
uint32_t version = kVersion;
uint32_t latestSeq{};
uint64_t mapSize{};
uint64_t deletedSize{};
};
private:
static constexpr uint32_t kVERSION = 1;
static constexpr uint32_t kVersion = 1;
std::string path_;

View File

@@ -289,7 +289,7 @@ LoadBalancer::forwardToRippled(
auto numAttempts = 0u;
auto xUserValue = isAdmin ? kADMIN_FORWARDING_X_USER_VALUE : kUSER_FORWARDING_X_USER_VALUE;
auto xUserValue = isAdmin ? kAdminForwardingXUserValue : kUserForwardingXUserValue;
std::optional<boost::json::object> response;
rpc::ClioError error = rpc::ClioError::EtlConnectionError;

View File

@@ -63,7 +63,7 @@ public:
using OptionalGetLedgerResponseType = std::optional<GetLedgerResponseType>;
private:
static constexpr std::uint32_t kDEFAULT_DOWNLOAD_RANGES = 16;
static constexpr std::uint32_t kDefaultDownloadRanges = 16;
util::Logger log_{"ETL"};
// Forwarding cache must be destroyed after sources because sources have a callback to
@@ -75,7 +75,7 @@ private:
std::vector<SourcePtr> sources_;
std::optional<ETLState> etlState_;
std::uint32_t downloadRanges_ = kDEFAULT_DOWNLOAD_RANGES; /*< The number of markers to use when
std::uint32_t downloadRanges_ = kDefaultDownloadRanges; /*< The number of markers to use when
downloading initial ledger */
struct ForwardingCounters {
@@ -95,12 +95,12 @@ public:
/**
* @brief Value for the X-User header when forwarding admin requests
*/
static constexpr std::string_view kADMIN_FORWARDING_X_USER_VALUE = "clio_admin";
static constexpr std::string_view kAdminForwardingXUserValue = "clio_admin";
/**
* @brief Value for the X-User header when forwarding user requests
*/
static constexpr std::string_view kUSER_FORWARDING_X_USER_VALUE = "clio_user";
static constexpr std::string_view kUserForwardingXUserValue = "clio_user";
/**
* @brief Create an instance of the load balancer.

View File

@@ -31,7 +31,7 @@ namespace etl::model {
template <ripple::TxType... Types>
requires(util::hasNoDuplicates(Types...))
struct Spec {
static constexpr bool kSPEC_TAG = true;
static constexpr bool kSpecTag = true;
/**
* @brief Checks if the transaction type was requested.

View File

@@ -16,7 +16,7 @@ namespace etl {
*/
class MonitorInterface {
public:
static constexpr auto kDEFAULT_REPEAT_INTERVAL = std::chrono::seconds{1};
static constexpr auto kDefaultRepeatInterval = std::chrono::seconds{1};
using NewSequenceSignalType = boost::signals2::signal<void(uint32_t)>;
using DbStalledSignalType = boost::signals2::signal<void()>;
@@ -61,7 +61,7 @@ public:
* @param repeatInterval The interval between attempts to check the database for new ledgers
*/
virtual void
run(std::chrono::steady_clock::duration repeatInterval = kDEFAULT_REPEAT_INTERVAL) = 0;
run(std::chrono::steady_clock::duration repeatInterval = kDefaultRepeatInterval) = 0;
/**
* @brief Stops the monitor service

View File

@@ -18,7 +18,7 @@ struct MonitorProviderInterface {
/**
* @brief The time Monitor should wait before reporting absence of updates to the database
*/
static constexpr auto kDEFAULT_DB_STALLED_REPORT_DELAY = std::chrono::seconds{10};
static constexpr auto kDefaultDbStalledReportDelay = std::chrono::seconds{10};
virtual ~MonitorProviderInterface() = default;
@@ -38,7 +38,7 @@ struct MonitorProviderInterface {
std::shared_ptr<BackendInterface> backend,
std::shared_ptr<NetworkValidatedLedgersInterface> validatedLedgers,
uint32_t startSequence,
std::chrono::steady_clock::duration dbStalledReportDelay = kDEFAULT_DB_STALLED_REPORT_DELAY
std::chrono::steady_clock::duration dbStalledReportDelay = kDefaultDbStalledReportDelay
) = 0;
};

View File

@@ -11,15 +11,14 @@
namespace etl::impl {
AmendmentBlockHandler::ActionType const AmendmentBlockHandler::kDEFAULT_AMENDMENT_BLOCK_ACTION =
[]() {
static util::Logger const log{"ETL"}; // NOLINT(readability-identifier-naming)
LOG(
log.fatal()
) << "Can't process new ledgers: The current ETL source is not compatible with the version "
"of "
<< "the libxrpl Clio is currently using. Please upgrade Clio to a newer version.";
};
AmendmentBlockHandler::ActionType const AmendmentBlockHandler::kDefaultAmendmentBlockAction = []() {
static util::Logger const log{"ETL"}; // NOLINT(readability-identifier-naming)
LOG(
log.fatal()
) << "Can't process new ledgers: The current ETL source is not compatible with the version "
"of "
<< "the libxrpl Clio is currently using. Please upgrade Clio to a newer version.";
};
AmendmentBlockHandler::AmendmentBlockHandler(
util::async::AnyExecutionContext ctx,

View File

@@ -28,13 +28,13 @@ private:
ActionType action_;
public:
static ActionType const kDEFAULT_AMENDMENT_BLOCK_ACTION;
static ActionType const kDefaultAmendmentBlockAction;
AmendmentBlockHandler(
util::async::AnyExecutionContext ctx,
SystemState& state,
std::chrono::steady_clock::duration interval = std::chrono::seconds{1},
ActionType action = kDEFAULT_AMENDMENT_BLOCK_ACTION
ActionType action = kDefaultAmendmentBlockAction
);
~AmendmentBlockHandler() override;

View File

@@ -43,10 +43,10 @@ public:
}();
rg::sort(accountRoots);
std::vector<ripple::uint256> cursors{data::kFIRST_KEY};
std::vector<ripple::uint256> cursors{data::kFirstKey};
rg::copy(accountRoots.begin(), accountRoots.end(), std::back_inserter(cursors));
rg::sort(cursors);
cursors.push_back(data::kLAST_KEY);
cursors.push_back(data::kLastKey);
std::vector<CursorPair> pairs;
pairs.reserve(cursors.size());

View File

@@ -67,13 +67,13 @@ public:
);
}
std::vector<ripple::uint256> cursors{data::kFIRST_KEY};
std::vector<ripple::uint256> cursors{data::kFirstKey};
rg::copy(
liveCursors | vs::take(std::min(liveCursors.size(), numCursors_)),
std::back_inserter(cursors)
);
rg::sort(cursors);
cursors.push_back(data::kLAST_KEY);
cursors.push_back(data::kLastKey);
std::vector<CursorPair> pairs;
pairs.reserve(cursors.size());

View File

@@ -57,14 +57,14 @@ public:
rg::unique(diffs, [](auto const& a, auto const& b) { return a.key == b.key; });
diffs.erase(removalCursor, last);
std::vector<ripple::uint256> cursors{data::kFIRST_KEY};
std::vector<ripple::uint256> cursors{data::kFirstKey};
rg::copy(
diffs //
| vs::filter([](auto const& obj) { return not obj.blob.empty(); }) //
| vs::transform([](auto const& obj) { return obj.key; }),
std::back_inserter(cursors)
);
cursors.push_back(data::kLAST_KEY); // last pair should cover the remaining range
cursors.push_back(data::kLastKey); // last pair should cover the remaining range
std::vector<CursorPair> pairs;
pairs.reserve(cursors.size());

View File

@@ -108,8 +108,8 @@ extractObj(PBObjType obj)
.keyRaw = std::move(*obj.mutable_key()),
.data = {obj.mutable_data()->begin(), obj.mutable_data()->end()},
.dataRaw = std::move(*obj.mutable_data()),
.successor = valueOr(obj.successor(), uint256ToString(data::kFIRST_KEY)),
.predecessor = valueOr(obj.predecessor(), uint256ToString(data::kLAST_KEY)),
.successor = valueOr(obj.successor(), uint256ToString(data::kFirstKey)),
.predecessor = valueOr(obj.predecessor(), uint256ToString(data::kLastKey)),
.type = extractModType(obj.mod_type()),
};
}

View File

@@ -20,14 +20,14 @@ class ForwardingSource {
util::requests::WsConnectionBuilder connectionBuilder_;
std::chrono::steady_clock::duration forwardingTimeout_;
static constexpr std::chrono::seconds kCONNECTION_TIMEOUT{3};
static constexpr std::chrono::seconds kConnectionTimeout{3};
public:
ForwardingSource(
std::string ip,
std::string wsPort,
std::chrono::steady_clock::duration forwardingTimeout,
std::chrono::steady_clock::duration connTimeout = ForwardingSource::kCONNECTION_TIMEOUT
std::chrono::steady_clock::duration connTimeout = ForwardingSource::kConnectionTimeout
);
/**

View File

@@ -58,13 +58,12 @@ GrpcSource::GrpcSource(
try {
grpc::ChannelArguments chArgs;
chArgs.SetMaxReceiveMessageSize(-1);
chArgs.SetInt(GRPC_ARG_KEEPALIVE_TIME_MS, kKEEPALIVE_PING_INTERVAL_MS);
chArgs.SetInt(GRPC_ARG_KEEPALIVE_TIMEOUT_MS, kKEEPALIVE_TIMEOUT_MS);
chArgs.SetInt(GRPC_ARG_KEEPALIVE_TIME_MS, kKeepalivePingIntervalMs);
chArgs.SetInt(GRPC_ARG_KEEPALIVE_TIMEOUT_MS, kKeepaliveTimeoutMs);
chArgs.SetInt(
GRPC_ARG_KEEPALIVE_PERMIT_WITHOUT_CALLS,
static_cast<int>(kKEEPALIVE_PERMIT_WITHOUT_CALLS)
GRPC_ARG_KEEPALIVE_PERMIT_WITHOUT_CALLS, static_cast<int>(kKeepalivePermitWithoutCalls)
);
chArgs.SetInt(GRPC_ARG_HTTP2_MAX_PINGS_WITHOUT_DATA, kMAX_PINGS_WITHOUT_DATA);
chArgs.SetInt(GRPC_ARG_HTTP2_MAX_PINGS_WITHOUT_DATA, kMaxPingsWithoutData);
stub_ = org::xrpl::rpc::v1::XRPLedgerAPIService::NewStub(
grpc::CreateCustomChannel(

View File

@@ -24,18 +24,18 @@ class GrpcSource {
std::unique_ptr<std::atomic_bool> initialLoadShouldStop_;
std::chrono::system_clock::duration deadline_;
static constexpr auto kKEEPALIVE_PING_INTERVAL_MS = 10000;
static constexpr auto kKEEPALIVE_TIMEOUT_MS = 5000;
static constexpr auto kKEEPALIVE_PERMIT_WITHOUT_CALLS =
true; // Allow keepalive pings when no calls
static constexpr auto kMAX_PINGS_WITHOUT_DATA = 0; // No limit
static constexpr auto kDEADLINE = std::chrono::seconds(30);
static constexpr auto kKeepalivePingIntervalMs = 10000;
static constexpr auto kKeepaliveTimeoutMs = 5000;
static constexpr auto kKeepalivePermitWithoutCalls =
true; // Allow keepalive pings when no calls
static constexpr auto kMaxPingsWithoutData = 0; // No limit
static constexpr auto kDeadline = std::chrono::seconds(30);
public:
GrpcSource(
std::string const& ip,
std::string const& grpcPort,
std::chrono::system_clock::duration deadline = kDEADLINE
std::chrono::system_clock::duration deadline = kDeadline
);
/**

View File

@@ -167,8 +167,8 @@ public:
// if the ledger closed over MAX_LEDGER_AGE_SECONDS ago, assume we are still catching up
// and don't publish
static constexpr std::uint32_t kMAX_LEDGER_AGE_SECONDS = 600;
if (age < kMAX_LEDGER_AGE_SECONDS) {
static constexpr std::uint32_t kMaxLedgerAgeSeconds = 600;
if (age < kMaxLedgerAgeSeconds) {
std::optional<ripple::Fees> fees =
data::synchronousAndRetryOnTimeout([&](auto yield) {
return backend_->fetchFees(lgrInfo.seq, yield);
@@ -246,9 +246,9 @@ public:
std::chrono::system_clock::now().time_since_epoch()
)
.count();
if (now < (kRIPPLE_EPOCH_START + closeTime))
if (now < (kRippleEpochStart + closeTime))
return 0;
return now - (kRIPPLE_EPOCH_START + closeTime);
return now - (kRippleEpochStart + closeTime);
}
/**

View File

@@ -83,8 +83,8 @@ Loader::onInitialLoadGotMoreObjects(
std::optional<std::string> lastKey
)
{
static constexpr std::size_t kLOG_STRIDE = 1000u;
static auto kINITIAL_LOAD_START_TIME = std::chrono::steady_clock::now();
static constexpr std::size_t kLogStride = 1000u;
static auto kInitialLoadStartTime = std::chrono::steady_clock::now();
try {
LOG(log_.trace()) << "On initial load: got more objects for seq " << seq
@@ -99,12 +99,12 @@ Loader::onInitialLoadGotMoreObjects(
initialLoadWrittenObjects_ += data.size();
++initialLoadWrites_;
if (initialLoadWrites_ % kLOG_STRIDE == 0u && initialLoadWrites_ != 0u) {
if (initialLoadWrites_ % kLogStride == 0u && initialLoadWrites_ != 0u) {
auto elapsedSinceStart = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - kINITIAL_LOAD_START_TIME
std::chrono::steady_clock::now() - kInitialLoadStartTime
);
auto elapsedSeconds =
elapsedSinceStart.count() / static_cast<double>(util::kMILLISECONDS_PER_SECOND);
elapsedSinceStart.count() / static_cast<double>(util::kMillisecondsPerSecond);
auto objectsPerSecond = elapsedSeconds > 0.0
? static_cast<double>(initialLoadWrittenObjects_) / elapsedSeconds
: 0.0;

View File

@@ -57,7 +57,7 @@ concept HasInitialObjectHook = requires(T p) {
};
template <typename T>
concept ContainsSpec = std::decay_t<T>::spec::kSPEC_TAG;
concept ContainsSpec = std::decay_t<T>::spec::kSpecTag;
template <typename T>
concept ContainsValidHook =

View File

@@ -49,11 +49,11 @@ public:
[[nodiscard]] std::optional<model::Task>
next() override
{
static constexpr auto kMAX = std::numeric_limits<uint32_t>::max();
static constexpr auto kMax = std::numeric_limits<uint32_t>::max();
uint32_t currentSeq = seq_;
if (ledgers_.get().getMostRecent() >= currentSeq) {
while (currentSeq < maxSeq_.value_or(kMAX)) {
while (currentSeq < maxSeq_.value_or(kMax)) {
if (seq_.compare_exchange_weak(
currentSeq, currentSeq + 1u, std::memory_order_acq_rel
)) {

View File

@@ -58,7 +58,7 @@ SubscriptionSource::SubscriptionSource(
, subscriptions_(std::move(subscriptions))
, strand_(boost::asio::make_strand(ioContext))
, wsTimeout_(wsTimeout)
, retry_(util::makeRetryExponentialBackoff(retryDelay, kRETRY_MAX_DELAY, strand_))
, retry_(util::makeRetryExponentialBackoff(retryDelay, kRetryMaxDelay, strand_))
, onConnect_(std::move(onConnect))
, onDisconnect_(std::move(onDisconnect))
, onLedgerClosed_(std::move(onLedgerClosed))
@@ -198,9 +198,9 @@ SubscriptionSource::handleMessage(std::string const& message)
auto const object = raw.as_object();
uint32_t ledgerIndex = 0;
static constexpr auto kJS_LEDGER_CLOSED = "ledgerClosed";
static constexpr auto kJS_VALIDATION_RECEIVED = "validationReceived";
static constexpr auto kJS_MANIFEST_RECEIVED = "manifestReceived";
static constexpr auto kJsLedgerClosed = "ledgerClosed";
static constexpr auto kJsValidationReceived = "validationReceived";
static constexpr auto kJsManifestReceived = "manifestReceived";
if (object.contains(JS(result))) {
auto const& result = object.at(JS(result)).as_object();
@@ -215,7 +215,7 @@ SubscriptionSource::handleMessage(std::string const& message)
LOG(log_.debug()) << "Received a message on ledger subscription stream. Message: "
<< object;
} else if (object.contains(JS(type)) && object.at(JS(type)) == kJS_LEDGER_CLOSED) {
} else if (object.contains(JS(type)) && object.at(JS(type)) == kJsLedgerClosed) {
LOG(log_.debug()) << "Received a message of type 'ledgerClosed' on ledger subscription "
"stream. Message: "
<< object;
@@ -239,12 +239,12 @@ SubscriptionSource::handleMessage(std::string const& message)
LOG(log_.debug()) << "Forwarding proposed transaction: " << object;
subscriptions_->forwardProposedTransaction(object);
} else if (
object.contains(JS(type)) && object.at(JS(type)) == kJS_VALIDATION_RECEIVED
object.contains(JS(type)) && object.at(JS(type)) == kJsValidationReceived
) {
LOG(log_.debug()) << "Forwarding validation: " << object;
subscriptions_->forwardValidation(object);
} else if (
object.contains(JS(type)) && object.at(JS(type)) == kJS_MANIFEST_RECEIVED
object.contains(JS(type)) && object.at(JS(type)) == kJsManifestReceived
) {
LOG(log_.debug()) << "Forwarding manifest: " << object;
subscriptions_->forwardManifest(object);
@@ -358,12 +358,12 @@ SubscriptionSource::setValidatedRange(std::string range)
std::string const&
SubscriptionSource::getSubscribeCommandJson()
{
static boost::json::object const kJSON_VALUE{
static boost::json::object const kJsonValue{
{"command", "subscribe"},
{"streams", {"ledger", "manifests", "validations", "transactions_proposed"}},
};
static std::string const kJSON_STRING = boost::json::serialize(kJSON_VALUE);
return kJSON_STRING;
static std::string const kJsonString = boost::json::serialize(kJsonValue);
return kJsonString;
}
} // namespace etl::impl

View File

@@ -74,9 +74,9 @@ private:
util::StopHelper stopHelper_;
static constexpr std::chrono::seconds kWS_TIMEOUT{30};
static constexpr std::chrono::seconds kRETRY_MAX_DELAY{30};
static constexpr std::chrono::seconds kRETRY_DELAY{1};
static constexpr std::chrono::seconds kWsTimeout{30};
static constexpr std::chrono::seconds kRetryMaxDelay{30};
static constexpr std::chrono::seconds kRetryDelay{1};
public:
/**
@@ -104,8 +104,8 @@ public:
OnConnectHook onConnect,
OnDisconnectHook onDisconnect,
OnLedgerClosedHook onLedgerClosed,
std::chrono::steady_clock::duration const wsTimeout = SubscriptionSource::kWS_TIMEOUT,
std::chrono::steady_clock::duration const retryDelay = SubscriptionSource::kRETRY_DELAY
std::chrono::steady_clock::duration const wsTimeout = SubscriptionSource::kWsTimeout,
std::chrono::steady_clock::duration const retryDelay = SubscriptionSource::kRetryDelay
);
/**

View File

@@ -40,7 +40,7 @@ TaskManager::TaskManager(
, extractor_(extractor)
, loader_(loader)
, monitor_(monitor)
, queue_({.startSeq = startSeq, .increment = 1u, .limit = kQUEUE_SIZE_LIMIT})
, queue_({.startSeq = startSeq, .increment = 1u, .limit = kQueueSizeLimit})
{
}
@@ -70,8 +70,8 @@ TaskManager::spawnExtractor(TaskQueue& queue)
{
// TODO https://github.com/XRPLF/clio/issues/2838: the approach should be changed to a reactive
// one instead
static constexpr auto kDELAY_BETWEEN_ATTEMPTS = std::chrono::milliseconds{10u};
static constexpr auto kDELAY_BETWEEN_ENQUEUE_ATTEMPTS = std::chrono::milliseconds{1u};
static constexpr auto kDelayBetweenAttempts = std::chrono::milliseconds{10u};
static constexpr auto kDelayBetweenEnqueueAttempts = std::chrono::milliseconds{1u};
return ctx_.execute([this, &queue](auto stopRequested) {
while (not stopRequested) {
@@ -81,7 +81,7 @@ TaskManager::spawnExtractor(TaskQueue& queue)
LOG(log_.debug()) << "Adding data after extracting diff";
while (not queue.enqueue(*maybeBatch)) {
// TODO (https://github.com/XRPLF/clio/issues/1852)
std::this_thread::sleep_for(kDELAY_BETWEEN_ENQUEUE_ATTEMPTS);
std::this_thread::sleep_for(kDelayBetweenEnqueueAttempts);
if (stopRequested)
break;
@@ -89,7 +89,7 @@ TaskManager::spawnExtractor(TaskQueue& queue)
}
} else {
// TODO (https://github.com/XRPLF/clio/issues/1852)
std::this_thread::sleep_for(kDELAY_BETWEEN_ATTEMPTS);
std::this_thread::sleep_for(kDelayBetweenAttempts);
}
}
@@ -130,7 +130,7 @@ TaskManager::spawnLoader(TaskQueue& queue)
if (shouldExitOnError)
break;
auto const seconds = nanos / util::kNANO_PER_SECOND;
auto const seconds = nanos / util::kNanoPerSecond;
auto const txnCount = data->transactions.size();
auto const objCount = data->objects.size();

View File

@@ -23,7 +23,7 @@
namespace etl::impl {
class TaskManager : public TaskManagerInterface {
static constexpr auto kQUEUE_SIZE_LIMIT = 2048uz;
static constexpr auto kQueueSizeLimit = 2048uz;
util::async::AnyExecutionContext ctx_;
std::shared_ptr<SchedulerInterface> schedulers_;

View File

@@ -86,7 +86,7 @@ SuccessorExt::writeIncludedSuccessor(uint32_t seq, model::BookSuccessor const& s
{
auto firstBook = succ.firstBook;
if (firstBook.empty())
firstBook = uint256ToString(data::kLAST_KEY);
firstBook = uint256ToString(data::kLastKey);
backend_->writeSuccessor(auto{succ.bookBase}, seq, std::move(firstBook));
}
@@ -116,10 +116,10 @@ SuccessorExt::updateSuccessorFromCache(uint32_t seq, model::Object const& obj) c
{
auto const lb = cache_.get()
.getPredecessor(obj.key, seq)
.value_or(data::LedgerObject{.key = data::kFIRST_KEY, .blob = {}});
.value_or(data::LedgerObject{.key = data::kFirstKey, .blob = {}});
auto const ub = cache_.get()
.getSuccessor(obj.key, seq)
.value_or(data::LedgerObject{.key = data::kLAST_KEY, .blob = {}});
.value_or(data::LedgerObject{.key = data::kLastKey, .blob = {}});
auto checkBookBase = false;
auto const isDeleted = obj.data.empty();
@@ -169,16 +169,16 @@ SuccessorExt::updateBookSuccessor(
uint256ToString(bookBase), seq, uint256ToString(maybeSuccessor->key)
);
} else {
backend_->writeSuccessor(uint256ToString(bookBase), seq, uint256ToString(data::kLAST_KEY));
backend_->writeSuccessor(uint256ToString(bookBase), seq, uint256ToString(data::kLastKey));
}
}
void
SuccessorExt::writeSuccessors(uint32_t seq) const
{
ripple::uint256 prev = data::kFIRST_KEY;
ripple::uint256 prev = data::kFirstKey;
while (auto cur = cache_.get().getSuccessor(prev, seq)) {
if (prev == data::kFIRST_KEY)
if (prev == data::kFirstKey)
backend_->writeSuccessor(uint256ToString(prev), seq, uint256ToString(cur->key));
if (isBookDir(cur->key, cur->blob)) {
@@ -199,7 +199,7 @@ SuccessorExt::writeSuccessors(uint32_t seq) const
prev = cur->key;
}
backend_->writeSuccessor(uint256ToString(prev), seq, uint256ToString(data::kLAST_KEY));
backend_->writeSuccessor(uint256ToString(prev), seq, uint256ToString(data::kLastKey));
}
void

View File

@@ -62,7 +62,7 @@ public:
private:
static constexpr std::array<char const*, static_cast<size_t>(Status::NumStatuses)>
kSTATUS_STR_MAP = {"Migrated", "NotMigrated", "NotKnown"};
kStatusStrMap = {"Migrated", "NotMigrated", "NotKnown"};
Status status_;
};

View File

@@ -20,14 +20,14 @@ MigratorStatus::operator==(Status const& other) const
std::string
MigratorStatus::toString() const
{
return kSTATUS_STR_MAP[static_cast<size_t>(status_)];
return kStatusStrMap[static_cast<size_t>(status_)];
}
MigratorStatus
MigratorStatus::fromString(std::string const& statusStr)
{
for (std::size_t i = 0; i < kSTATUS_STR_MAP.size(); ++i) {
if (statusStr == kSTATUS_STR_MAP[i]) {
for (std::size_t i = 0; i < kStatusStrMap.size(); ++i) {
if (statusStr == kStatusStrMap[i]) {
return MigratorStatus(static_cast<Status>(i));
}
}

View File

@@ -34,11 +34,11 @@ A migrator satisfies the `MigratorSpec`(impl/Spec.hpp) concept.
It contains:
- A `kNAME` which will be used to identify the migrator. User will refer this migrator in command-line tool by this name. The name needs to be different with other migrators, otherwise a compilation error will be raised.
- A `kName` which will be used to identify the migrator. User will refer this migrator in command-line tool by this name. The name needs to be different with other migrators, otherwise a compilation error will be raised.
- A `kDESCRIPTION` which is the detail information of the migrator.
- A `kDescription` which is the detail information of the migrator.
- An optional `kCAN_BLOCK_CLIO` which indicates whether the migrator can block the Clio server. If it's absent, the migrator can't block server. If there is a blocking migrator not completed, the Clio server will fail to start.
- An optional `kCanBlockClio` which indicates whether the migrator can block the Clio server. If it's absent, the migrator can't block server. If there is a blocking migrator not completed, the Clio server will fail to start.
- A static function `runMigration`, it will be called when user run `--migrate name`. It accepts two parameters: backend, which provides the DB operations interface, and cfg, which provides migration-related configuration. Each migrator can have its own configuration under `.migration` session.
@@ -63,8 +63,8 @@ If you need to do full scan against other table, you can follow below steps:
- Describe the table which needs full scan in a struct. It has to satisfy the `TableSpec`(cassandra/Spec.hpp) concept, containing static member:
- Tuple type `Row`, it's the type of each field in a row. The order of types should match what database will return in a row. Key types should come first, followed by other field types sorted in alphabetical order.
- `kPARTITION_KEY`, it's the name of the partition key of the table.
- `kTABLE_NAME`
- `kPartitionKey`, it's the name of the partition key of the table.
- `kTableName`
- Inherent from `FullTableScannerAdapterBase`.
- Implement `onRowRead`, its parameter is the `Row` we defined. It's the callback function when a row is read.

View File

@@ -60,24 +60,24 @@ public:
)
{
LOG(log_.debug()) << "Travsering token range: " << start << " - " << end
<< " ; table: " << TableDesc::kTABLE_NAME;
<< " ; table: " << TableDesc::kTableName;
// for each table we only have one prepared statement
static auto kSTATEMENT_PREPARED = migrationSchema_.getPreparedFullScanStatement(
handle_, TableDesc::kTABLE_NAME, TableDesc::kPARTITION_KEY
static auto kStatementPrepared = migrationSchema_.getPreparedFullScanStatement(
handle_, TableDesc::kTableName, TableDesc::kPartitionKey
);
auto const statement = kSTATEMENT_PREPARED.bind(start, end);
auto const statement = kStatementPrepared.bind(start, end);
auto const res = this->executor_.read(yield, statement);
if (not res) {
LOG(log_.error()) << "Could not fetch data from table: " << TableDesc::kTABLE_NAME
LOG(log_.error()) << "Could not fetch data from table: " << TableDesc::kTableName
<< " range: " << start << " - " << end << ";" << res.error();
return;
}
auto const& results = res.value();
if (not results.hasRows()) {
LOG(log_.debug()) << "No rows returned - table: " << TableDesc::kTABLE_NAME
LOG(log_.debug()) << "No rows returned - table: " << TableDesc::kTableName
<< " range: " << start << " - " << end;
return;
}

View File

@@ -71,7 +71,7 @@ public:
data::cassandra::PreparedStatement const&
getPreparedInsertMigratedMigrator(data::cassandra::Handle const& handler)
{
static auto kPREPARED = handler.prepare(
static auto kPrepared = handler.prepare(
fmt::format(
R"(
INSERT INTO {}
@@ -83,7 +83,7 @@ public:
)
)
);
return kPREPARED;
return kPrepared;
}
};
} // namespace migration::cassandra::impl

View File

@@ -23,8 +23,8 @@ namespace migration::cassandra::impl {
*/
struct TableObjectsDesc {
using Row = std::tuple<ripple::uint256, std::uint32_t, data::Blob>;
static constexpr char const* kPARTITION_KEY = "key";
static constexpr char const* kTABLE_NAME = "objects";
static constexpr char const* kPartitionKey = "key";
static constexpr char const* kTableName = "objects";
};
/**

View File

@@ -16,7 +16,7 @@ concept TableSpec = requires {
requires std::tuple_size_v<typename T::Row> >= 0; // Ensures 'row' is a tuple
// Check that static constexpr members 'partitionKey' and 'tableName' exist
{ T::kPARTITION_KEY } -> std::convertible_to<char const*>;
{ T::kTABLE_NAME } -> std::convertible_to<char const*>;
{ T::kPartitionKey } -> std::convertible_to<char const*>;
{ T::kTableName } -> std::convertible_to<char const*>;
};
} // namespace migration::cassandra::impl

View File

@@ -24,8 +24,8 @@ struct TableTransactionsDesc {
// hash, date, ledger_seq, metadata, transaction
using Row =
std::tuple<ripple::uint256, std::uint64_t, std::uint32_t, ripple::Blob, ripple::Blob>;
static constexpr char const* kPARTITION_KEY = "hash";
static constexpr char const* kTABLE_NAME = "transactions";
static constexpr char const* kPartitionKey = "hash";
static constexpr char const* kTableName = "transactions";
};
/**

View File

@@ -34,7 +34,7 @@ concept BackendMatchAllMigrators = (MigrationBackend<Backend, MigratorType> && .
template <typename T>
concept HasCanBlockClio = requires(T t) {
{ t.kCAN_BLOCK_CLIO };
{ t.kCanBlockClio };
};
/**
@@ -57,7 +57,7 @@ class MigratorsRegister {
void
callMigration(std::string const& name, util::config::ObjectView const& config)
{
if (name == Migrator::kNAME) {
if (name == Migrator::kName) {
LOG(log_.info()) << "Running migration: " << name;
Migrator::runMigration(backend_, config);
backend_->writeMigratorStatus(
@@ -71,16 +71,16 @@ class MigratorsRegister {
static constexpr std::string_view
getDescriptionIfMatch(std::string_view targetName)
{
return (T::kNAME == targetName) ? T::kDESCRIPTION : "";
return (T::kName == targetName) ? T::kDescription : "";
}
template <typename First, typename... Rest>
static constexpr bool
canBlockClioHelper(std::string_view targetName)
{
if (targetName == First::kNAME) {
if (targetName == First::kName) {
if constexpr (HasCanBlockClio<First>) {
return First::kCAN_BLOCK_CLIO;
return First::kCanBlockClio;
}
return false;
}
@@ -168,7 +168,7 @@ public:
[[nodiscard]] constexpr auto
getMigratorNames() const
{
return std::array<std::string_view, sizeof...(MigratorType)>{MigratorType::kNAME...};
return std::array<std::string_view, sizeof...(MigratorType)>{MigratorType::kName...};
}
/**

View File

@@ -15,11 +15,11 @@ namespace migration::impl {
template <typename T, typename Backend>
concept MigratorSpec =
requires(std::shared_ptr<Backend> const& backend, util::config::ObjectView const& cfg) {
// Check that 'kNAME' exists and is a string
{ T::kNAME } -> std::convertible_to<std::string>;
// Check that 'kName' exists and is a string
{ T::kName } -> std::convertible_to<std::string>;
// Check that 'kDESCRIPTION' exists and is a string
{ T::kDESCRIPTION } -> std::convertible_to<std::string>;
// Check that 'kDescription' exists and is a string
{ T::kDescription } -> std::convertible_to<std::string>;
// Check that the migrator specifies the backend type it supports
typename T::Backend;

View File

@@ -60,7 +60,7 @@ operator<<(std::ostream& stream, Status const& status)
WarningInfo const&
getWarningInfo(WarningCode code)
{
static constexpr WarningInfo kINFOS[]{
static constexpr WarningInfo kInfos[]{
{WarningCode::WarnUnknown, "Unknown warning"},
{WarningCode::WarnRpcClio,
"This is a clio server. clio only serves validated data. If you want to talk to rippled, "
@@ -74,7 +74,7 @@ getWarningInfo(WarningCode code)
};
auto matchByCode = [code](auto const& info) { return info.code == code; };
if (auto it = ranges::find_if(kINFOS, matchByCode); it != end(kINFOS))
if (auto it = ranges::find_if(kInfos, matchByCode); it != end(kInfos))
return *it;
throw(out_of_range("Invalid WarningCode"));
@@ -93,7 +93,7 @@ makeWarning(WarningCode code)
ClioErrorInfo const&
getErrorInfo(ClioError code)
{
static constexpr ClioErrorInfo kINFOS[]{
static constexpr ClioErrorInfo kInfos[]{
{.code = ClioError::RpcMalformedCurrency,
.error = "malformedCurrency",
.message = "Malformed currency."},
@@ -150,7 +150,7 @@ getErrorInfo(ClioError code)
};
auto matchByCode = [code](auto const& info) { return info.code == code; };
if (auto it = ranges::find_if(kINFOS, matchByCode); it != end(kINFOS))
if (auto it = ranges::find_if(kInfos, matchByCode); it != end(kInfos))
return *it;
throw(out_of_range("Invalid error code"));

View File

@@ -10,7 +10,7 @@ namespace {
std::unordered_set<std::string_view> const&
handledRpcs()
{
static std::unordered_set<std::string_view> const kHANDLED_RPCS = {
static std::unordered_set<std::string_view> const kHandledRpcs = {
// clang-format off
"account_channels",
"account_currencies",
@@ -52,13 +52,13 @@ handledRpcs()
"version",
// clang-format on
};
return kHANDLED_RPCS;
return kHandledRpcs;
}
std::unordered_set<std::string_view> const&
forwardedRpcs()
{
static std::unordered_set<std::string_view> const kFORWARDED_RPCS = {
static std::unordered_set<std::string_view> const kForwardedRpcs = {
"server_definitions",
"server_state",
"submit",
@@ -73,7 +73,7 @@ forwardedRpcs()
"simulate",
"batch"
};
return kFORWARDED_RPCS;
return kForwardedRpcs;
}
} // namespace

View File

@@ -135,10 +135,9 @@ getDeliveredAmount(
// then its absence indicates that the amount delivered is listed in the
// Amount field. DeliveredAmount went live January 24, 2014.
// 446000000 is in Feb 2014, well after DeliveredAmount went live
static constexpr std::uint32_t kFIRST_LEDGER_WITH_DELIVERED_AMOUNT = 4594095;
static constexpr std::uint32_t kDELIVERED_AMOUNT_LIVE_DATE = 446000000;
if (ledgerSequence >= kFIRST_LEDGER_WITH_DELIVERED_AMOUNT ||
date > kDELIVERED_AMOUNT_LIVE_DATE) {
static constexpr std::uint32_t kFirstLedgerWithDeliveredAmount = 4594095;
static constexpr std::uint32_t kDeliveredAmountLiveDate = 446000000;
if (ledgerSequence >= kFirstLedgerWithDeliveredAmount || date > kDeliveredAmountLiveDate) {
return txn->getFieldAmount(ripple::sfAmount);
}
}
@@ -270,15 +269,15 @@ toExpandedJson(
std::optional<std::string>
encodeCTID(uint32_t ledgerSeq, uint16_t txnIndex, uint16_t networkId) noexcept
{
static constexpr uint32_t kMAX_LEDGER_SEQ = 0x0FFF'FFFF;
static constexpr uint32_t kMAX_TXN_INDEX = 0xFFFF;
static constexpr uint32_t kMAX_NETWORK_ID = 0xFFFF;
static constexpr uint32_t kMaxLedgerSeq = 0x0FFF'FFFF;
static constexpr uint32_t kMaxTxnIndex = 0xFFFF;
static constexpr uint32_t kMaxNetworkId = 0xFFFF;
if (ledgerSeq > kMAX_LEDGER_SEQ || txnIndex > kMAX_TXN_INDEX || networkId > kMAX_NETWORK_ID)
if (ledgerSeq > kMaxLedgerSeq || txnIndex > kMaxTxnIndex || networkId > kMaxNetworkId)
return {};
static constexpr uint64_t kCTID_PREFIX = 0xC000'0000;
uint64_t const ctidValue = ((kCTID_PREFIX + static_cast<uint64_t>(ledgerSeq)) << 32) +
static constexpr uint64_t kCtidPrefix = 0xC000'0000;
uint64_t const ctidValue = ((kCtidPrefix + static_cast<uint64_t>(ledgerSeq)) << 32) +
(static_cast<uint64_t>(txnIndex) << 16) + networkId;
return {fmt::format("{:016X}", ctidValue)};
@@ -731,8 +730,8 @@ traverseOwnedNodes(
// Only reserve 2048 nodes when fetching all owned ledger objects. If there
// are more, then keys will allocate more memory, which is suboptimal, but
// should only occur occasionally.
static constexpr std::uint32_t kMIN_NODES = 2048;
keys.reserve(std::min(kMIN_NODES, limit));
static constexpr std::uint32_t kMinNodes = 2048;
keys.reserve(std::min(kMinNodes, limit));
auto start = std::chrono::system_clock::now();
@@ -879,10 +878,10 @@ parseRippleLibSeed(boost::json::value const& value)
boost::json::value_to<std::string>(value), ripple::TokenType::None
);
static constexpr std::size_t kSEED_SIZE = 18;
static constexpr std::array<std::uint8_t, 2> kSEED_PREFIX = {0xE1, 0x4B};
if (result.size() == kSEED_SIZE && static_cast<std::uint8_t>(result[0]) == kSEED_PREFIX[0] &&
static_cast<std::uint8_t>(result[1]) == kSEED_PREFIX[1])
static constexpr std::size_t kSeedSize = 18;
static constexpr std::array<std::uint8_t, 2> kSeedPrefix = {0xE1, 0x4B};
if (result.size() == kSeedSize && static_cast<std::uint8_t>(result[0]) == kSeedPrefix[0] &&
static_cast<std::uint8_t>(result[1]) == kSeedPrefix[1])
return ripple::Seed(ripple::makeSlice(result.substr(2)));
return {};

View File

@@ -713,8 +713,8 @@ decodeCTID(T const ctid) noexcept
auto const getCTID64 = [](T const ctid) noexcept -> std::optional<uint64_t> {
if constexpr (std::is_convertible_v<T, std::string>) {
std::string const ctidString(ctid);
static constexpr std::size_t kCTID_STRING_LENGTH = 16;
if (ctidString.length() != kCTID_STRING_LENGTH)
static constexpr std::size_t kCtidStringLength = 16;
if (ctidString.length() != kCtidStringLength)
return {};
if (!boost::regex_match(ctidString, boost::regex("^[0-9A-F]+$")))
@@ -731,10 +731,10 @@ decodeCTID(T const ctid) noexcept
auto const ctidValue = getCTID64(ctid).value_or(0);
static constexpr uint64_t kCTID_PREFIX = 0xC000'0000'0000'0000ULL;
static constexpr uint64_t kCTID_PREFIX_MASK = 0xF000'0000'0000'0000ULL;
static constexpr uint64_t kCtidPrefix = 0xC000'0000'0000'0000ULL;
static constexpr uint64_t kCtidPrefixMask = 0xF000'0000'0000'0000ULL;
if ((ctidValue & kCTID_PREFIX_MASK) != kCTID_PREFIX)
if ((ctidValue & kCtidPrefixMask) != kCtidPrefix)
return {};
uint32_t const ledgerSeq = (ctidValue >> 32) & 0xFFFF'FFFUL;
@@ -762,7 +762,7 @@ logDuration(
using boost::json::serialize;
static util::Logger const log{"RPC"}; // NOLINT(readability-identifier-naming)
static constexpr std::int64_t kDURATION_ERROR_THRESHOLD_SECONDS = 10;
static constexpr std::int64_t kDurationErrorThresholdSeconds = 10;
auto const millis = std::chrono::duration_cast<std::chrono::milliseconds>(dur).count();
auto const seconds = std::chrono::duration_cast<std::chrono::seconds>(dur).count();
@@ -772,7 +772,7 @@ logDuration(
serialize(util::removeSecret(request))
);
if (seconds > kDURATION_ERROR_THRESHOLD_SECONDS) {
if (seconds > kDurationErrorThresholdSeconds) {
LOG(log.error()) << tag << msg;
} else if (seconds > 1) {
LOG(log.warn()) << tag << msg;

View File

@@ -62,7 +62,7 @@ WorkQueue::WorkQueue(DontStartProcessingTag, std::uint32_t numWorkers, uint32_t
}
WorkQueue::WorkQueue(std::uint32_t numWorkers, uint32_t maxSize)
: WorkQueue(kDONT_START_PROCESSING_TAG, numWorkers, maxSize)
: WorkQueue(kDontStartProcessingTag, numWorkers, maxSize)
{
startProcessing();
}

View File

@@ -90,7 +90,7 @@ private:
[[nodiscard]] std::optional<TaskWithTimestamp>
popNext()
{
if (not high.empty() and (highPriorityCounter < kTAKE_HIGH_PRIO or normal.empty())) {
if (not high.empty() and (highPriorityCounter < kTakeHighPrio or normal.empty())) {
auto taskWithTimestamp = std::move(high.front());
high.pop();
++highPriorityCounter;
@@ -109,7 +109,7 @@ private:
};
private:
static constexpr auto kTAKE_HIGH_PRIO = 4uz;
static constexpr auto kTakeHighPrio = 4uz;
// these are cumulative for the lifetime of the process
std::reference_wrapper<util::prometheus::CounterInt> queued_;
@@ -143,7 +143,7 @@ private:
public:
struct DontStartProcessingTag {};
static constexpr DontStartProcessingTag kDONT_START_PROCESSING_TAG = {};
static constexpr DontStartProcessingTag kDontStartProcessingTag = {};
/**
* @brief Create an instance of the work queue.

View File

@@ -11,17 +11,17 @@ namespace rpc {
/**
* @brief Default API version to use if no version is specified by clients
*/
static constexpr uint32_t kAPI_VERSION_DEFAULT = 1u;
static constexpr uint32_t kApiVersionDefault = 1u;
/**
* @brief Minimum API version supported by this build
*/
static constexpr uint32_t kAPI_VERSION_MIN = 1u;
static constexpr uint32_t kApiVersionMin = 1u;
/**
* @brief Maximum API version supported by this build
*/
static constexpr uint32_t kAPI_VERSION_MAX = 3u;
static constexpr uint32_t kApiVersionMax = 3u;
/**
* @brief A baseclass for API version helper

View File

@@ -32,7 +32,7 @@ struct FieldSpec final {
: processor_{
impl::makeFieldProcessor<Processors...>(key, std::forward<Processors>(processors)...)
}
, checker_{impl::kEMPTY_FIELD_CHECKER}
, checker_{impl::kEmptyFieldChecker}
{
}
@@ -45,7 +45,7 @@ struct FieldSpec final {
*/
template <SomeCheck... Checks>
FieldSpec(std::string const& key, Checks&&... checks)
: processor_{impl::kEMPTY_FIELD_PROCESSOR}
: processor_{impl::kEmptyFieldProcessor}
, checker_{impl::makeFieldChecker<Checks...>(key, std::forward<Checks>(checks)...)}
{
}

View File

@@ -232,7 +232,7 @@ CustomValidator CustomValidators::subscribeStreamValidator =
if (!value.is_array())
return Error{Status{RippledError::rpcINVALID_PARAMS, std::string(key) + "NotArray"}};
static std::unordered_set<std::string> const kVALID_STREAMS = {
static std::unordered_set<std::string> const kValidStreams = {
"ledger",
"transactions",
"transactions_proposed",
@@ -241,17 +241,17 @@ CustomValidator CustomValidators::subscribeStreamValidator =
"validations"
};
static std::unordered_set<std::string> const kNOT_SUPPORT_STREAMS = {
static std::unordered_set<std::string> const kNotSupportStreams = {
"peer_status", "consensus", "server"
};
for (auto const& v : value.as_array()) {
if (!v.is_string())
return Error{Status{RippledError::rpcINVALID_PARAMS, "streamNotString"}};
if (kNOT_SUPPORT_STREAMS.contains(boost::json::value_to<std::string>(v)))
if (kNotSupportStreams.contains(boost::json::value_to<std::string>(v)))
return Error{Status{RippledError::rpcNOT_SUPPORTED}};
if (not kVALID_STREAMS.contains(boost::json::value_to<std::string>(v)))
if (not kValidStreams.contains(boost::json::value_to<std::string>(v)))
return Error{Status{RippledError::rpcSTREAM_MALFORMED}};
}

View File

@@ -21,9 +21,9 @@ class ProductionAPIVersionParser : public APIVersionParser {
public:
ProductionAPIVersionParser(
uint32_t defaultVersion = kAPI_VERSION_DEFAULT,
uint32_t minVersion = kAPI_VERSION_MIN,
uint32_t maxVersion = kAPI_VERSION_MAX
uint32_t defaultVersion = kApiVersionDefault,
uint32_t minVersion = kApiVersionMin,
uint32_t maxVersion = kApiVersionMax
);
ProductionAPIVersionParser(util::config::ObjectView const& config);

View File

@@ -20,7 +20,7 @@ namespace rpc::impl {
using FieldSpecProcessor = std::function<MaybeError(boost::json::value&)>;
static FieldSpecProcessor const kEMPTY_FIELD_PROCESSOR = [](boost::json::value&) -> MaybeError {
static FieldSpecProcessor const kEmptyFieldProcessor = [](boost::json::value&) -> MaybeError {
return {};
};
@@ -60,7 +60,7 @@ makeFieldProcessor(std::string const& key, Processors&&... procs)
using FieldChecker = std::function<check::Warnings(boost::json::value const&)>;
static FieldChecker const kEMPTY_FIELD_CHECKER = [](boost::json::value const&) -> check::Warnings {
static FieldChecker const kEmptyFieldChecker = [](boost::json::value const&) -> check::Warnings {
return {};
};

View File

@@ -115,9 +115,9 @@ private:
[[nodiscard]] bool
isForcedForward(web::Context const& ctx) const
{
static constexpr auto kFORCE_FORWARD = "force_forward";
return ctx.isAdmin and ctx.params.contains(kFORCE_FORWARD) and
ctx.params.at(kFORCE_FORWARD).is_bool() and ctx.params.at(kFORCE_FORWARD).as_bool();
static constexpr auto kForceForward = "force_forward";
return ctx.isAdmin and ctx.params.contains(kForceForward) and
ctx.params.at(kForceForward).is_bool() and ctx.params.at(kForceForward).as_bool();
}
};

View File

@@ -46,12 +46,12 @@ std::string
toIso8601(ripple::NetClock::time_point tp)
{
using namespace std::chrono;
static constexpr auto kRIPPLE_EPOCH_OFFSET = seconds{kRIPPLE_EPOCH_START};
static constexpr auto kRippleEpochOffset = seconds{kRippleEpochStart};
return date::format(
"%Y-%Om-%dT%H:%M:%OS%z",
date::sys_time<system_clock::duration>(
system_clock::time_point{tp.time_since_epoch() + kRIPPLE_EPOCH_OFFSET}
system_clock::time_point{tp.time_since_epoch() + kRippleEpochOffset}
)
);
};
@@ -230,7 +230,7 @@ AMMInfoHandler::process(AMMInfoHandler::Input const& input, Context const& ctx)
RpcSpecConstRef
AMMInfoHandler::spec([[maybe_unused]] uint32_t apiVersion)
{
static auto const kSTRING_ISSUE_VALIDATOR = validation::CustomValidator{
static auto const kStringIssueValidator = validation::CustomValidator{
[](boost::json::value const& value, std::string_view key) -> MaybeError {
if (not value.is_string()) {
return Error{
@@ -248,7 +248,7 @@ AMMInfoHandler::spec([[maybe_unused]] uint32_t apiVersion)
}
};
static auto const kRPC_SPEC = RpcSpec{
static auto const kRpcSpec = RpcSpec{
{JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator},
{JS(ledger_index), validation::CustomValidators::ledgerIndexValidator},
{JS(asset),
@@ -256,7 +256,7 @@ AMMInfoHandler::spec([[maybe_unused]] uint32_t apiVersion)
validation::Type<std::string, boost::json::object>{},
Status(RippledError::rpcISSUE_MALFORMED)
},
meta::IfType<std::string>{kSTRING_ISSUE_VALIDATOR},
meta::IfType<std::string>{kStringIssueValidator},
meta::IfType<boost::json::object>{
meta::WithCustomError{
validation::CustomValidators::currencyIssueValidator,
@@ -268,7 +268,7 @@ AMMInfoHandler::spec([[maybe_unused]] uint32_t apiVersion)
validation::Type<std::string, boost::json::object>{},
Status(RippledError::rpcISSUE_MALFORMED)
},
meta::IfType<std::string>{kSTRING_ISSUE_VALIDATOR},
meta::IfType<std::string>{kStringIssueValidator},
meta::IfType<boost::json::object>{
meta::WithCustomError{
validation::CustomValidators::currencyIssueValidator,
@@ -285,7 +285,7 @@ AMMInfoHandler::spec([[maybe_unused]] uint32_t apiVersion)
}},
};
return kRPC_SPEC;
return kRpcSpec;
}
void

View File

@@ -32,9 +32,9 @@ class AccountChannelsHandler {
std::shared_ptr<BackendInterface> const sharedPtrBackend_;
public:
static constexpr auto kLIMIT_MIN = 10;
static constexpr auto kLIMIT_MAX = 400;
static constexpr auto kLIMIT_DEFAULT = 200;
static constexpr auto kLimitMin = 10;
static constexpr auto kLimitMax = 400;
static constexpr auto kLimitDefault = 200;
/**
* @brief A struct to hold data for one channel response
@@ -78,7 +78,7 @@ public:
std::optional<std::string> destinationAccount;
std::optional<std::string> ledgerHash;
std::optional<uint32_t> ledgerIndex;
uint32_t limit = kLIMIT_DEFAULT;
uint32_t limit = kLimitDefault;
std::optional<std::string> marker;
};
@@ -103,7 +103,7 @@ public:
static RpcSpecConstRef
spec([[maybe_unused]] uint32_t apiVersion)
{
static auto const kRPC_SPEC = RpcSpec{
static auto const kRpcSpec = RpcSpec{
{JS(account), validation::Required{}, validation::CustomValidators::accountValidator},
{JS(destination_account),
validation::Type<std::string>{},
@@ -112,12 +112,12 @@ public:
{JS(limit),
validation::Type<uint32_t>{},
validation::Min(1u),
modifiers::Clamp<int32_t>{kLIMIT_MIN, kLIMIT_MAX}},
modifiers::Clamp<int32_t>{kLimitMin, kLimitMax}},
{JS(ledger_index), validation::CustomValidators::ledgerIndexValidator},
{JS(marker), validation::CustomValidators::accountMarkerValidator},
};
return kRPC_SPEC;
return kRpcSpec;
}
/**

View File

@@ -72,7 +72,7 @@ public:
static RpcSpecConstRef
spec([[maybe_unused]] uint32_t apiVersion)
{
static auto const kRPC_SPEC = RpcSpec{
static auto const kRpcSpec = RpcSpec{
{JS(account), validation::Required{}, validation::CustomValidators::accountValidator},
{JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator},
{JS(ledger_index), validation::CustomValidators::ledgerIndexValidator},
@@ -80,7 +80,7 @@ public:
{JS(strict), check::Deprecated{}}
};
return kRPC_SPEC;
return kRpcSpec;
}
/**

View File

@@ -88,7 +88,7 @@ public:
static RpcSpecConstRef
spec([[maybe_unused]] uint32_t apiVersion)
{
static auto const kRPC_SPEC_V1 = RpcSpec{
static auto const kRpcSpecV1 = RpcSpec{
{JS(account), validation::CustomValidators::accountValidator},
{JS(ident), validation::CustomValidators::accountValidator},
{JS(ident), check::Deprecated{}},
@@ -98,10 +98,10 @@ public:
{JS(strict), check::Deprecated{}}
};
static auto const kRPC_SPEC =
RpcSpec{kRPC_SPEC_V1, {{JS(signer_lists), validation::Type<bool>{}}}};
static auto const kRpcSpec =
RpcSpec{kRpcSpecV1, {{JS(signer_lists), validation::Type<bool>{}}}};
return apiVersion == 1 ? kRPC_SPEC_V1 : kRPC_SPEC;
return apiVersion == 1 ? kRpcSpecV1 : kRpcSpec;
}
/**

View File

@@ -36,9 +36,9 @@ class AccountLinesHandler {
std::shared_ptr<BackendInterface> const sharedPtrBackend_;
public:
static constexpr auto kLIMIT_MIN = 10;
static constexpr auto kLIMIT_MAX = 400;
static constexpr auto kLIMIT_DEFAULT = 200;
static constexpr auto kLimitMin = 10;
static constexpr auto kLimitMax = 400;
static constexpr auto kLimitDefault = 200;
/**
* @brief A struct to hold data for one line response
@@ -84,7 +84,7 @@ public:
std::optional<std::string> peer;
bool ignoreDefault = false; // TODO: document
// https://github.com/XRPLF/xrpl-dev-portal/issues/1839
uint32_t limit = kLIMIT_DEFAULT;
uint32_t limit = kLimitDefault;
std::optional<std::string> marker;
};
@@ -109,7 +109,7 @@ public:
static RpcSpecConstRef
spec([[maybe_unused]] uint32_t apiVersion)
{
static auto const kRPC_SPEC = RpcSpec{
static auto const kRpcSpec = RpcSpec{
{JS(account),
validation::Required{},
meta::WithCustomError{
@@ -126,14 +126,14 @@ public:
{JS(limit),
validation::Type<uint32_t>{},
validation::Min(1u),
modifiers::Clamp<int32_t>{kLIMIT_MIN, kLIMIT_MAX}},
modifiers::Clamp<int32_t>{kLimitMin, kLimitMax}},
{JS(ledger_index), validation::CustomValidators::ledgerIndexValidator},
{JS(marker), validation::CustomValidators::accountMarkerValidator},
{JS(ledger), check::Deprecated{}},
{"peer_index", check::Deprecated{}},
};
return kRPC_SPEC;
return kRpcSpec;
}
/**

View File

@@ -34,9 +34,9 @@ class AccountMPTokenIssuancesHandler {
std::shared_ptr<BackendInterface> sharedPtrBackend_;
public:
static constexpr auto kLIMIT_MIN = 10;
static constexpr auto kLIMIT_MAX = 400;
static constexpr auto kLIMIT_DEFAULT = 200;
static constexpr auto kLimitMin = 10;
static constexpr auto kLimitMax = 400;
static constexpr auto kLimitDefault = 200;
/**
* @brief A struct to hold data for one MPTokenIssuance response.
@@ -93,7 +93,7 @@ public:
std::string account;
std::optional<std::string> ledgerHash;
std::optional<uint32_t> ledgerIndex;
uint32_t limit = kLIMIT_DEFAULT;
uint32_t limit = kLimitDefault;
std::optional<std::string> marker;
};
@@ -118,7 +118,7 @@ public:
static RpcSpecConstRef
spec([[maybe_unused]] uint32_t apiVersion)
{
static auto const kRPC_SPEC = RpcSpec{
static auto const kRpcSpec = RpcSpec{
{JS(account),
validation::Required{},
meta::WithCustomError{
@@ -129,13 +129,13 @@ public:
{JS(limit),
validation::Type<uint32_t>{},
validation::Min(1u),
modifiers::Clamp<int32_t>{kLIMIT_MIN, kLIMIT_MAX}},
modifiers::Clamp<int32_t>{kLimitMin, kLimitMax}},
{JS(ledger_index), validation::CustomValidators::ledgerIndexValidator},
{JS(marker), validation::CustomValidators::accountMarkerValidator},
{JS(ledger), check::Deprecated{}},
};
return kRPC_SPEC;
return kRpcSpec;
}
/**

View File

@@ -33,9 +33,9 @@ class AccountMPTokensHandler {
std::shared_ptr<BackendInterface> sharedPtrBackend_;
public:
static constexpr auto kLIMIT_MIN = 10;
static constexpr auto kLIMIT_MAX = 400;
static constexpr auto kLIMIT_DEFAULT = 200;
static constexpr auto kLimitMin = 10;
static constexpr auto kLimitMax = 400;
static constexpr auto kLimitDefault = 200;
/**
* @brief A struct to hold data for one MPToken response.
@@ -71,7 +71,7 @@ public:
std::string account;
std::optional<std::string> ledgerHash;
std::optional<uint32_t> ledgerIndex;
uint32_t limit = kLIMIT_DEFAULT;
uint32_t limit = kLimitDefault;
std::optional<std::string> marker;
};
@@ -96,7 +96,7 @@ public:
static RpcSpecConstRef
spec([[maybe_unused]] uint32_t apiVersion)
{
static auto const kRPC_SPEC = RpcSpec{
static auto const kRpcSpec = RpcSpec{
{JS(account),
validation::Required{},
meta::WithCustomError{
@@ -107,13 +107,13 @@ public:
{JS(limit),
validation::Type<uint32_t>{},
validation::Min(1u),
modifiers::Clamp<int32_t>{kLIMIT_MIN, kLIMIT_MAX}},
modifiers::Clamp<int32_t>{kLimitMin, kLimitMax}},
{JS(ledger_index), validation::CustomValidators::ledgerIndexValidator},
{JS(marker), validation::CustomValidators::accountMarkerValidator},
{JS(ledger), check::Deprecated{}},
};
return kRPC_SPEC;
return kRpcSpec;
}
/**

View File

@@ -28,9 +28,9 @@ class AccountNFTsHandler {
std::shared_ptr<BackendInterface> sharedPtrBackend_;
public:
static constexpr auto kLIMIT_MIN = 20;
static constexpr auto kLIMIT_MAX = 400;
static constexpr auto kLIMIT_DEFAULT = 100;
static constexpr auto kLimitMin = 20;
static constexpr auto kLimitMax = 400;
static constexpr auto kLimitDefault = 100;
/**
* @brief A struct to hold the output data of the command
@@ -53,7 +53,7 @@ public:
std::string account;
std::optional<std::string> ledgerHash;
std::optional<uint32_t> ledgerIndex;
uint32_t limit = kLIMIT_DEFAULT; // Limit the number of token pages to retrieve. [20,400]
uint32_t limit = kLimitDefault; // Limit the number of token pages to retrieve. [20,400]
std::optional<std::string> marker;
};
@@ -78,7 +78,7 @@ public:
static RpcSpecConstRef
spec([[maybe_unused]] uint32_t apiVersion)
{
static auto const kRPC_SPEC = RpcSpec{
static auto const kRpcSpec = RpcSpec{
{JS(account), validation::Required{}, validation::CustomValidators::accountValidator},
{JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator},
{JS(ledger_index), validation::CustomValidators::ledgerIndexValidator},
@@ -86,10 +86,10 @@ public:
{JS(limit),
validation::Type<uint32_t>{},
validation::Min(1u),
modifiers::Clamp<int32_t>{kLIMIT_MIN, kLIMIT_MAX}},
modifiers::Clamp<int32_t>{kLimitMin, kLimitMax}},
};
return kRPC_SPEC;
return kRpcSpec;
}
/**

View File

@@ -34,9 +34,9 @@ class AccountObjectsHandler {
std::shared_ptr<BackendInterface> sharedPtrBackend_;
public:
static constexpr auto kLIMIT_MIN = 10;
static constexpr auto kLIMIT_MAX = 400;
static constexpr auto kLIMIT_DEFAULT = 200;
static constexpr auto kLimitMin = 10;
static constexpr auto kLimitMax = 400;
static constexpr auto kLimitDefault = 200;
/**
* @brief A struct to hold the output data of the command
@@ -58,7 +58,7 @@ public:
std::string account;
std::optional<std::string> ledgerHash;
std::optional<uint32_t> ledgerIndex;
uint32_t limit = kLIMIT_DEFAULT; // [10,400]
uint32_t limit = kLimitDefault; // [10,400]
std::optional<std::string> marker;
std::optional<ripple::LedgerEntryType> type;
bool deletionBlockersOnly = false;
@@ -85,20 +85,20 @@ public:
static RpcSpecConstRef
spec([[maybe_unused]] uint32_t apiVersion)
{
static auto const kRPC_SPEC = RpcSpec{
static auto const kRpcSpec = RpcSpec{
{JS(account), validation::Required{}, validation::CustomValidators::accountValidator},
{JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator},
{JS(ledger_index), validation::CustomValidators::ledgerIndexValidator},
{JS(limit),
validation::Type<uint32_t>{},
validation::Min(1u),
modifiers::Clamp<int32_t>(kLIMIT_MIN, kLIMIT_MAX)},
modifiers::Clamp<int32_t>(kLimitMin, kLimitMax)},
{JS(type), validation::CustomValidators::accountTypeValidator},
{JS(marker), validation::CustomValidators::accountMarkerValidator},
{JS(deletion_blockers_only), validation::Type<bool>{}},
};
return kRPC_SPEC;
return kRpcSpec;
}
/**

View File

@@ -31,9 +31,9 @@ class AccountOffersHandler {
std::shared_ptr<BackendInterface> sharedPtrBackend_;
public:
static constexpr auto kLIMIT_MIN = 10;
static constexpr auto kLIMIT_MAX = 400;
static constexpr auto kLIMIT_DEFAULT = 200;
static constexpr auto kLimitMin = 10;
static constexpr auto kLimitMax = 400;
static constexpr auto kLimitDefault = 200;
/**
* @brief A struct to hold data for one offer response
@@ -67,7 +67,7 @@ public:
std::string account;
std::optional<std::string> ledgerHash;
std::optional<uint32_t> ledgerIndex;
uint32_t limit = kLIMIT_DEFAULT;
uint32_t limit = kLimitDefault;
std::optional<std::string> marker;
};
@@ -92,7 +92,7 @@ public:
static RpcSpecConstRef
spec([[maybe_unused]] uint32_t apiVersion)
{
static auto const kRPC_SPEC = RpcSpec{
static auto const kRpcSpec = RpcSpec{
{JS(account), validation::Required{}, validation::CustomValidators::accountValidator},
{JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator},
{JS(ledger_index), validation::CustomValidators::ledgerIndexValidator},
@@ -100,12 +100,12 @@ public:
{JS(limit),
validation::Type<uint32_t>{},
validation::Min(1u),
modifiers::Clamp<int32_t>{kLIMIT_MIN, kLIMIT_MAX}},
modifiers::Clamp<int32_t>{kLimitMin, kLimitMax}},
{JS(ledger), check::Deprecated{}},
{JS(strict), check::Deprecated{}},
};
return kRPC_SPEC;
return kRpcSpec;
}
/**

View File

@@ -113,7 +113,7 @@ AccountTxHandler::process(AccountTxHandler::Input const& input, Context const& c
}
}
auto const limit = input.limit.value_or(kLIMIT_DEFAULT);
auto const limit = input.limit.value_or(kLimitDefault);
auto const accountID = accountFromStringStrict(input.account);
auto const [txnsAndCursor, timeDiff] = util::timed([&]() {
return sharedPtrBackend_->fetchAccountTransactions(

View File

@@ -41,9 +41,9 @@ class AccountTxHandler {
std::shared_ptr<etl::ETLServiceInterface const> etl_;
public:
static constexpr auto kLIMIT_MIN = 1;
static constexpr auto kLIMIT_MAX = 1000;
static constexpr auto kLIMIT_DEFAULT = 200;
static constexpr auto kLimitMin = 1;
static constexpr auto kLimitMax = 1000;
static constexpr auto kLimitDefault = 200;
/**
* @brief A struct to hold the marker data
@@ -113,7 +113,7 @@ public:
spec([[maybe_unused]] uint32_t apiVersion)
{
auto const& typesKeysInLowercase = util::getTxTypesInLowercase();
static auto const kRPC_SPEC_FOR_V1 = RpcSpec{
static auto const kRpcSpecForV1 = RpcSpec{
{JS(account), validation::Required{}, validation::CustomValidators::accountValidator},
{JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator},
{JS(ledger_index), validation::CustomValidators::ledgerIndexValidator},
@@ -123,7 +123,7 @@ public:
{JS(limit),
validation::Type<uint32_t>{},
validation::Min(1u),
modifiers::Clamp<int32_t>{kLIMIT_MIN, kLIMIT_MAX}},
modifiers::Clamp<int32_t>{kLimitMin, kLimitMax}},
{JS(marker),
meta::WithCustomError{
validation::Type<boost::json::object>{},
@@ -143,15 +143,15 @@ public:
},
};
static auto const kRPC_SPEC = RpcSpec{
kRPC_SPEC_FOR_V1,
static auto const kRpcSpec = RpcSpec{
kRpcSpecForV1,
{
{JS(binary), validation::Type<bool>{}},
{JS(forward), validation::Type<bool>{}},
}
};
return apiVersion == 1 ? kRPC_SPEC_FOR_V1 : kRPC_SPEC;
return apiVersion == 1 ? kRpcSpecForV1 : kRpcSpec;
}
/**

View File

@@ -70,12 +70,12 @@ public:
static RpcSpecConstRef
spec([[maybe_unused]] uint32_t apiVersion)
{
static auto const kRPC_SPEC = RpcSpec{
static auto const kRpcSpec = RpcSpec{
{JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator},
{JS(ledger_index), validation::CustomValidators::ledgerIndexValidator},
};
return kRPC_SPEC;
return kRpcSpec;
}
/**

View File

@@ -37,9 +37,9 @@ class BookOffersHandler {
std::shared_ptr<data::AmendmentCenterInterface const> amendmentCenter_;
public:
static constexpr auto kLIMIT_MIN = 1;
static constexpr auto kLIMIT_MAX = 100;
static constexpr auto kLIMIT_DEFAULT = 60;
static constexpr auto kLimitMin = 1;
static constexpr auto kLimitMax = 100;
static constexpr auto kLimitDefault = 60;
/**
* @brief A struct to hold the output data of the command
@@ -60,7 +60,7 @@ public:
struct Input {
std::optional<std::string> ledgerHash;
std::optional<uint32_t> ledgerIndex;
uint32_t limit = kLIMIT_DEFAULT;
uint32_t limit = kLimitDefault;
std::optional<ripple::AccountID> taker;
ripple::Currency paysCurrency;
ripple::Currency getsCurrency;
@@ -95,7 +95,7 @@ public:
static RpcSpecConstRef
spec([[maybe_unused]] uint32_t apiVersion)
{
static auto const kRPC_SPEC = RpcSpec{
static auto const kRpcSpec = RpcSpec{
{JS(taker_gets),
validation::Required{},
validation::Type<boost::json::object>{},
@@ -146,12 +146,12 @@ public:
{JS(limit),
validation::Type<uint32_t>{},
validation::Min(1u),
modifiers::Clamp<int32_t>{kLIMIT_MIN, kLIMIT_MAX}},
modifiers::Clamp<int32_t>{kLimitMin, kLimitMax}},
{JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator},
{JS(ledger_index), validation::CustomValidators::ledgerIndexValidator},
};
return kRPC_SPEC;
return kRpcSpec;
}
/**

View File

@@ -81,7 +81,7 @@ public:
static RpcSpecConstRef
spec([[maybe_unused]] uint32_t apiVersion)
{
static auto const kRPC_SPEC = RpcSpec{
static auto const kRpcSpec = RpcSpec{
{JS(source_account),
validation::Required{},
validation::CustomValidators::accountValidator},
@@ -93,7 +93,7 @@ public:
{JS(credentials), validation::Type<boost::json::array>{}, validation::Hex256ItemType()}
};
return kRPC_SPEC;
return kRpcSpec;
}
/**

View File

@@ -102,7 +102,7 @@ FeatureHandler::process(FeatureHandler::Input const& input, Context const& ctx)
RpcSpecConstRef
FeatureHandler::spec([[maybe_unused]] uint32_t apiVersion)
{
static RpcSpec const kRPC_SPEC = {
static RpcSpec const kRpcSpec = {
{JS(feature), validation::Type<std::string>{}},
{JS(vetoed),
meta::WithCustomError{
@@ -115,7 +115,7 @@ FeatureHandler::spec([[maybe_unused]] uint32_t apiVersion)
{JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator},
{JS(ledger_index), validation::CustomValidators::ledgerIndexValidator},
};
return kRPC_SPEC;
return kRpcSpec;
}
void

View File

@@ -128,20 +128,20 @@ public:
};
};
static auto const kSPEC_COMMON = RpcSpec{
static auto const kSpecCommon = RpcSpec{
{JS(account), validation::Required{}, validation::CustomValidators::accountValidator},
{JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator},
{JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}
};
static auto const kSPEC_V1 = RpcSpec{
kSPEC_COMMON, {{JS(hotwallet), getHotWalletValidator(ripple::rpcINVALID_HOTWALLET)}}
static auto const kSpecV1 = RpcSpec{
kSpecCommon, {{JS(hotwallet), getHotWalletValidator(ripple::rpcINVALID_HOTWALLET)}}
};
static auto const kSPEC_V2 = RpcSpec{
kSPEC_COMMON, {{JS(hotwallet), getHotWalletValidator(ripple::rpcINVALID_PARAMS)}}
static auto const kSpecV2 = RpcSpec{
kSpecCommon, {{JS(hotwallet), getHotWalletValidator(ripple::rpcINVALID_PARAMS)}}
};
return apiVersion == 1 ? kSPEC_V1 : kSPEC_V2;
return apiVersion == 1 ? kSpecV1 : kSpecV2;
}
/**

View File

@@ -178,11 +178,11 @@ GetAggregatePriceHandler::process(
auto const median = [&, size = out.extireStats.size]() {
auto const middle = size / 2;
if ((size % 2) == 0) {
static ripple::STAmount const kTWO{ripple::noIssue(), 2, 0};
static ripple::STAmount const kTwo{ripple::noIssue(), 2, 0};
auto it = itAdvance(timestampPricesBiMap.right.begin(), middle - 1);
auto const& a1 = it->first;
auto const& a2 = (++it)->first;
return divide(a1 + a2, kTWO, ripple::noIssue());
return divide(a1 + a2, kTwo, ripple::noIssue());
}
return itAdvance(timestampPricesBiMap.right.begin(), middle)->first;
}();
@@ -198,7 +198,7 @@ GetAggregatePriceHandler::tracebackOracleObject(
std::function<bool(ripple::STObject const&)> const& callback
) const
{
static constexpr auto kHISTORY_MAX = 3;
static constexpr auto kHistoryMax = 3;
std::optional<ripple::STObject> optOracleObject = oracleObject;
std::optional<ripple::STObject> optCurrentObject = optOracleObject;
@@ -216,7 +216,7 @@ GetAggregatePriceHandler::tracebackOracleObject(
if (callback(*optOracleObject) or isNew)
return;
if (++history > kHISTORY_MAX)
if (++history > kHistoryMax)
return;
auto const prevTxIndex = optCurrentObject->getFieldH256(ripple::sfPreviousTxnID);

View File

@@ -100,12 +100,12 @@ public:
static RpcSpecConstRef
spec([[maybe_unused]] uint32_t apiVersion)
{
static constexpr auto kORACLES_MAX = 200;
static constexpr auto kOraclesMax = 200;
static auto const kORACLES_VALIDATOR = modifiers::CustomModifier{
static auto const kOraclesValidator = modifiers::CustomModifier{
[](boost::json::value& value, std::string_view) -> MaybeError {
if (!value.is_array() or value.as_array().empty() or
value.as_array().size() > kORACLES_MAX)
value.as_array().size() > kOraclesMax)
return Error{Status{RippledError::rpcORACLE_MALFORMED}};
for (auto& oracle : value.as_array()) {
@@ -135,7 +135,7 @@ public:
}
};
static auto const kRPC_SPEC = RpcSpec{
static auto const kRpcSpec = RpcSpec{
{JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator},
{JS(ledger_index), validation::CustomValidators::ledgerIndexValidator},
// validate quoteAsset and base_asset in accordance to the currency code found in XRPL
@@ -155,7 +155,7 @@ public:
validation::CustomValidators::currencyValidator,
Status(RippledError::rpcINVALID_PARAMS)
}},
{JS(oracles), validation::Required{}, kORACLES_VALIDATOR},
{JS(oracles), validation::Required{}, kOraclesValidator},
// note: Unlike `rippled`, Clio only supports UInt as input, no string, no `null`, etc.
{JS(time_threshold), validation::Type<std::uint32_t>{}},
{
@@ -165,7 +165,7 @@ public:
}
};
return kRPC_SPEC;
return kRpcSpec;
}
/**

View File

@@ -93,7 +93,7 @@ public:
static RpcSpecConstRef
spec([[maybe_unused]] uint32_t apiVersion)
{
static auto const kRPC_SPEC = RpcSpec{
static auto const kRpcSpec = RpcSpec{
{JS(full), validation::Type<bool>{}, validation::NotSupported{true}},
{JS(full), check::Deprecated{}},
{JS(accounts), validation::Type<bool>{}, validation::NotSupported{true}},
@@ -110,7 +110,7 @@ public:
{JS(type), check::Deprecated{}},
};
return kRPC_SPEC;
return kRpcSpec;
}
/**

View File

@@ -101,7 +101,7 @@ LedgerDataHandler::process(Input const& input, Context const& ctx) const
// framework can not handler the check right now, adjust the value here
auto const limit = std::min(
input.limit,
input.binary ? LedgerDataHandler::kLIMIT_BINARY : LedgerDataHandler::kLIMIT_JSON
input.binary ? LedgerDataHandler::kLimitBinary : LedgerDataHandler::kLimitJson
);
auto page = sharedPtrBackend_->fetchLedgerPage(
input.marker, lgrInfo.seq, limit, input.outOfOrder, ctx.yield
@@ -187,7 +187,7 @@ tag_invoke(boost::json::value_to_tag<LedgerDataHandler::Input>, boost::json::val
if (jsonObject.contains(JS(binary))) {
input.binary = jsonObject.at(JS(binary)).as_bool();
input.limit =
input.binary ? LedgerDataHandler::kLIMIT_BINARY : LedgerDataHandler::kLIMIT_JSON;
input.binary ? LedgerDataHandler::kLimitBinary : LedgerDataHandler::kLimitJson;
}
if (jsonObject.contains(JS(limit)))

View File

@@ -37,8 +37,8 @@ class LedgerDataHandler {
public:
// constants
static constexpr uint32_t kLIMIT_BINARY = 2048;
static constexpr uint32_t kLIMIT_JSON = 256;
static constexpr uint32_t kLimitBinary = 2048;
static constexpr uint32_t kLimitJson = 256;
/**
* @brief A struct to hold the output data of the command
@@ -64,7 +64,7 @@ public:
std::optional<std::string> ledgerHash;
std::optional<uint32_t> ledgerIndex;
bool binary = false;
uint32_t limit = LedgerDataHandler::kLIMIT_JSON; // max 256 for json ; 2048 for binary
uint32_t limit = LedgerDataHandler::kLimitJson; // max 256 for json ; 2048 for binary
std::optional<ripple::uint256> marker;
std::optional<uint32_t> diffMarker;
bool outOfOrder = false;
@@ -92,7 +92,7 @@ public:
static RpcSpecConstRef
spec([[maybe_unused]] uint32_t apiVersion)
{
static auto const kRPC_SPEC = RpcSpec{
static auto const kRpcSpec = RpcSpec{
{JS(binary), validation::Type<bool>{}},
{"out_of_order", validation::Type<bool>{}},
{JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator},
@@ -104,7 +104,7 @@ public:
{JS(type), validation::CustomValidators::ledgerTypeValidator},
{JS(ledger), check::Deprecated{}},
};
return kRPC_SPEC;
return kRpcSpec;
}
/**

View File

@@ -368,36 +368,34 @@ tag_invoke(boost::json::value_to_tag<LedgerEntryHandler::Input>, boost::json::va
input.binary = jv.at(JS(binary)).as_bool();
// check all the potential index
static auto const kINDEX_FIELD_TYPE_MAP =
std::unordered_map<std::string, ripple::LedgerEntryType>{
{JS(index), ripple::ltANY},
{JS(directory), ripple::ltDIR_NODE},
{JS(offer), ripple::ltOFFER},
{JS(check), ripple::ltCHECK},
{JS(escrow), ripple::ltESCROW},
{JS(payment_channel), ripple::ltPAYCHAN},
{JS(deposit_preauth), ripple::ltDEPOSIT_PREAUTH},
{JS(ticket), ripple::ltTICKET},
{JS(nft_page), ripple::ltNFTOKEN_PAGE},
{JS(amm), ripple::ltAMM},
{JS(xchain_owned_create_account_claim_id),
ripple::ltXCHAIN_OWNED_CREATE_ACCOUNT_CLAIM_ID},
{JS(xchain_owned_claim_id), ripple::ltXCHAIN_OWNED_CLAIM_ID},
{JS(oracle), ripple::ltORACLE},
{JS(credential), ripple::ltCREDENTIAL},
{JS(mptoken), ripple::ltMPTOKEN},
{JS(permissioned_domain), ripple::ltPERMISSIONED_DOMAIN},
{JS(vault), ripple::ltVAULT},
{JS(loan_broker), ripple::ltLOAN_BROKER},
{JS(loan), ripple::ltLOAN},
{JS(delegate), ripple::ltDELEGATE},
{JS(amendments), ripple::ltAMENDMENTS},
{JS(fee), ripple::ltFEE_SETTINGS},
{JS(hashes), ripple::ltLEDGER_HASHES},
{JS(nft_offer), ripple::ltNFTOKEN_OFFER},
{JS(nunl), ripple::ltNEGATIVE_UNL},
{JS(signer_list), ripple::ltSIGNER_LIST},
};
static auto const kIndexFieldTypeMap = std::unordered_map<std::string, ripple::LedgerEntryType>{
{JS(index), ripple::ltANY},
{JS(directory), ripple::ltDIR_NODE},
{JS(offer), ripple::ltOFFER},
{JS(check), ripple::ltCHECK},
{JS(escrow), ripple::ltESCROW},
{JS(payment_channel), ripple::ltPAYCHAN},
{JS(deposit_preauth), ripple::ltDEPOSIT_PREAUTH},
{JS(ticket), ripple::ltTICKET},
{JS(nft_page), ripple::ltNFTOKEN_PAGE},
{JS(amm), ripple::ltAMM},
{JS(xchain_owned_create_account_claim_id), ripple::ltXCHAIN_OWNED_CREATE_ACCOUNT_CLAIM_ID},
{JS(xchain_owned_claim_id), ripple::ltXCHAIN_OWNED_CLAIM_ID},
{JS(oracle), ripple::ltORACLE},
{JS(credential), ripple::ltCREDENTIAL},
{JS(mptoken), ripple::ltMPTOKEN},
{JS(permissioned_domain), ripple::ltPERMISSIONED_DOMAIN},
{JS(vault), ripple::ltVAULT},
{JS(loan_broker), ripple::ltLOAN_BROKER},
{JS(loan), ripple::ltLOAN},
{JS(delegate), ripple::ltDELEGATE},
{JS(amendments), ripple::ltAMENDMENTS},
{JS(fee), ripple::ltFEE_SETTINGS},
{JS(hashes), ripple::ltLEDGER_HASHES},
{JS(nft_offer), ripple::ltNFTOKEN_OFFER},
{JS(nunl), ripple::ltNEGATIVE_UNL},
{JS(signer_list), ripple::ltSIGNER_LIST},
};
auto const parseBridgeFromJson = [](boost::json::value const& bridgeJson) {
auto const lockingDoor =
@@ -444,12 +442,12 @@ tag_invoke(boost::json::value_to_tag<LedgerEntryHandler::Input>, boost::json::va
};
auto const indexFieldType =
std::ranges::find_if(kINDEX_FIELD_TYPE_MAP, [&jsonObject](auto const& pair) {
std::ranges::find_if(kIndexFieldTypeMap, [&jsonObject](auto const& pair) {
auto const& [field, _] = pair;
return jsonObject.contains(field) && jsonObject.at(field).is_string();
});
if (indexFieldType != kINDEX_FIELD_TYPE_MAP.end()) {
if (indexFieldType != kIndexFieldTypeMap.end()) {
input.index = boost::json::value_to<std::string>(jv.at(indexFieldType->first));
input.expectedType = indexFieldType->second;
}

Some files were not shown because too many files have changed in this diff Show More