diff --git a/.clang-tidy b/.clang-tidy index d5e890db..3bd74115 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -130,6 +130,7 @@ Checks: '-*, readability-enum-initial-value, readability-implicit-bool-conversion, readability-inconsistent-declaration-parameter-name, + readability-identifier-naming, readability-make-member-function-const, readability-math-missing-parentheses, readability-misleading-indentation, @@ -149,6 +150,39 @@ Checks: '-*, CheckOptions: readability-braces-around-statements.ShortStatementLines: 2 + readability-identifier-naming.MacroDefinitionCase: UPPER_CASE + readability-identifier-naming.ClassCase: CamelCase + readability-identifier-naming.StructCase: CamelCase + readability-identifier-naming.UnionCase: CamelCase + readability-identifier-naming.EnumCase: CamelCase + readability-identifier-naming.EnumConstantCase: CamelCase + readability-identifier-naming.ScopedEnumConstantCase: CamelCase + readability-identifier-naming.GlobalConstantCase: UPPER_CASE + readability-identifier-naming.GlobalConstantPrefix: 'k' + readability-identifier-naming.GlobalVariableCase: CamelCase + readability-identifier-naming.GlobalVariablePrefix: 'g' + readability-identifier-naming.ConstexprFunctionCase: camelBack + readability-identifier-naming.ConstexprMethodCase: camelBack + readability-identifier-naming.ClassMethodCase: camelBack + readability-identifier-naming.ClassMemberCase: camelBack + readability-identifier-naming.ClassConstantCase: UPPER_CASE + readability-identifier-naming.ClassConstantPrefix: 'k' + readability-identifier-naming.StaticConstantCase: UPPER_CASE + 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.LocalConstantCase: camelBack + readability-identifier-naming.LocalVariableCase: camelBack + readability-identifier-naming.TemplateParameterCase: CamelCase + readability-identifier-naming.ParameterCase: camelBack + readability-identifier-naming.FunctionCase: camelBack + readability-identifier-naming.MemberCase: camelBack + readability-identifier-naming.PrivateMemberSuffix: _ + readability-identifier-naming.ProtectedMemberSuffix: _ + readability-identifier-naming.PublicMemberSuffix: '' + readability-identifier-naming.FunctionIgnoredRegexp: '.*tag_invoke.*' bugprone-unsafe-functions.ReportMoreUnsafeFunctions: true bugprone-unused-return-value.CheckedReturnTypes: ::std::error_code;::std::error_condition;::std::errc misc-include-cleaner.IgnoreHeaders: '.*/(detail|impl)/.*;.*(expected|unexpected).*;.*ranges_lower_bound\.h;time.h;stdlib.h' diff --git a/benchmarks/util/async/ExecutionContextBenchmarks.cpp b/benchmarks/util/async/ExecutionContextBenchmarks.cpp index 47158a09..fead0946 100644 --- a/benchmarks/util/async/ExecutionContextBenchmarks.cpp +++ b/benchmarks/util/async/ExecutionContextBenchmarks.cpp @@ -188,10 +188,10 @@ public: static auto generateData() { - constexpr auto TOTAL = 10'000; + constexpr auto kTOTAL = 10'000; std::vector data; - data.reserve(TOTAL); - for (auto i = 0; i < TOTAL; ++i) + data.reserve(kTOTAL); + for (auto i = 0; i < kTOTAL; ++i) data.push_back(util::Random::uniform(1, 100'000'000)); return data; diff --git a/cmake/Build.cpp.in b/cmake/Build.cpp.in index 49579916..4ae43918 100644 --- a/cmake/Build.cpp.in +++ b/cmake/Build.cpp.in @@ -23,19 +23,19 @@ namespace util::build { -static constexpr char versionString[] = "@CLIO_VERSION@"; +static constexpr char versionString[] = "@CLIO_VERSION@"; // NOLINT(readability-identifier-naming) std::string const& getClioVersionString() { - static std::string const value = versionString; + static std::string const value = versionString; // NOLINT(readability-identifier-naming) return value; } std::string const& getClioFullVersionString() { - static std::string const value = "clio-" + getClioVersionString(); + static std::string const value = "clio-" + getClioVersionString(); // NOLINT(readability-identifier-naming) return value; } diff --git a/src/app/CliArgs.cpp b/src/app/CliArgs.cpp index 919bb589..0c973dee 100644 --- a/src/app/CliArgs.cpp +++ b/src/app/CliArgs.cpp @@ -44,7 +44,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()->default_value(defaultConfigPath), "configuration file") + ("conf,c", po::value()->default_value(kDEFAULT_CONFIG_PATH), "configuration file") ("ng-web-server,w", "Use ng-web-server") ("migrate", po::value(), "start migration helper") ; diff --git a/src/app/CliArgs.hpp b/src/app/CliArgs.hpp index e7572019..2142ad3f 100644 --- a/src/app/CliArgs.hpp +++ b/src/app/CliArgs.hpp @@ -35,7 +35,7 @@ public: /** * @brief Default configuration path. */ - static constexpr char defaultConfigPath[] = "/etc/opt/clio/config.json"; + static constexpr char kDEFAULT_CONFIG_PATH[] = "/etc/opt/clio/config.json"; /** * @brief An action parsed from the command line. diff --git a/src/app/ClioApplication.cpp b/src/app/ClioApplication.cpp index 2a05235a..6a64206f 100644 --- a/src/app/ClioApplication.cpp +++ b/src/app/ClioApplication.cpp @@ -101,25 +101,25 @@ ClioApplication::run(bool const useNgWebServer) auto sweepHandler = web::dosguard::IntervalSweepHandler{config_, ioc, dosGuard}; // Interface to the database - auto backend = data::make_Backend(config_); + auto backend = data::makeBackend(config_); // Manages clients subscribed to streams - auto subscriptions = feed::SubscriptionManager::make_SubscriptionManager(config_, backend); + auto subscriptions = feed::SubscriptionManager::makeSubscriptionManager(config_, backend); // Tracks which ledgers have been validated by the network - auto ledgers = etl::NetworkValidatedLedgers::make_ValidatedLedgers(); + auto ledgers = etl::NetworkValidatedLedgers::makeValidatedLedgers(); // Handles the connection to one or more rippled nodes. // ETL uses the balancer to extract data. // The server uses the balancer to forward RPCs to a rippled node. // The balancer itself publishes to streams (transactions_proposed and accounts_proposed) - auto balancer = etl::LoadBalancer::make_LoadBalancer(config_, ioc, backend, subscriptions, ledgers); + auto balancer = etl::LoadBalancer::makeLoadBalancer(config_, ioc, backend, subscriptions, ledgers); // ETL is responsible for writing and publishing to streams. In read-only mode, ETL only publishes - auto etl = etl::ETLService::make_ETLService(config_, ioc, backend, subscriptions, balancer, ledgers); + auto etl = etl::ETLService::makeETLService(config_, ioc, backend, subscriptions, balancer, ledgers); - auto workQueue = rpc::WorkQueue::make_WorkQueue(config_); - auto counters = rpc::Counters::make_Counters(workQueue); + auto workQueue = rpc::WorkQueue::makeWorkQueue(config_); + auto counters = rpc::Counters::makeCounters(workQueue); auto const amendmentCenter = std::make_shared(backend); auto const handlerProvider = std::make_shared( config_, backend, subscriptions, balancer, etl, amendmentCenter, counters @@ -127,19 +127,19 @@ ClioApplication::run(bool const useNgWebServer) using RPCEngineType = rpc::RPCEngine; auto const rpcEngine = - RPCEngineType::make_RPCEngine(config_, backend, balancer, dosGuard, workQueue, counters, handlerProvider); + RPCEngineType::makeRPCEngine(config_, backend, balancer, dosGuard, workQueue, counters, handlerProvider); if (useNgWebServer or config_.get("server.__ng_web_server")) { web::ng::RPCServerHandler handler{config_, backend, rpcEngine, etl}; - auto expectedAdminVerifier = web::make_AdminVerificationStrategy(config_); + auto expectedAdminVerifier = web::makeAdminVerificationStrategy(config_); if (not expectedAdminVerifier.has_value()) { LOG(util::LogService::error()) << "Error creating admin verifier: " << expectedAdminVerifier.error(); return EXIT_FAILURE; } auto const adminVerifier = std::move(expectedAdminVerifier).value(); - auto httpServer = web::ng::make_Server(config_, OnConnectCheck{dosGuard}, DisconnectHook{dosGuard}, ioc); + auto httpServer = web::ng::makeServer(config_, OnConnectCheck{dosGuard}, DisconnectHook{dosGuard}, ioc); if (not httpServer.has_value()) { LOG(util::LogService::error()) << "Error creating web server: " << httpServer.error(); @@ -170,7 +170,7 @@ ClioApplication::run(bool const useNgWebServer) auto handler = std::make_shared>(config_, backend, rpcEngine, etl); - auto const httpServer = web::make_HttpServer(config_, ioc, dosGuard, handler); + auto const httpServer = web::makeHttpServer(config_, ioc, dosGuard, handler); // Blocks until stopped. // When stopped, shared_ptrs fall out of scope diff --git a/src/app/WebHandlers.cpp b/src/app/WebHandlers.cpp index 7a1a1a41..97cddb7a 100644 --- a/src/app/WebHandlers.cpp +++ b/src/app/WebHandlers.cpp @@ -97,7 +97,7 @@ HealthCheckHandler::operator()( boost::asio::yield_context ) { - static auto constexpr HealthCheckHTML = R"html( + static auto constexpr kHEALTH_CHECK_HTML = R"html( Test page for Clio @@ -105,7 +105,7 @@ HealthCheckHandler::operator()( )html"; - return web::ng::Response{boost::beast::http::status::ok, HealthCheckHTML, request}; + return web::ng::Response{boost::beast::http::status::ok, kHEALTH_CHECK_HTML, request}; } } // namespace app diff --git a/src/app/WebHandlers.hpp b/src/app/WebHandlers.hpp index d66f7c78..ac7958ac 100644 --- a/src/app/WebHandlers.hpp +++ b/src/app/WebHandlers.hpp @@ -213,9 +213,9 @@ public: auto jsonResponse = boost::json::parse(response.message()).as_object(); jsonResponse["warning"] = "load"; if (jsonResponse.contains("warnings") && jsonResponse["warnings"].is_array()) { - jsonResponse["warnings"].as_array().push_back(rpc::makeWarning(rpc::warnRPC_RATE_LIMIT)); + jsonResponse["warnings"].as_array().push_back(rpc::makeWarning(rpc::WarnRpcRateLimit)); } else { - jsonResponse["warnings"] = boost::json::array{rpc::makeWarning(rpc::warnRPC_RATE_LIMIT)}; + jsonResponse["warnings"] = boost::json::array{rpc::makeWarning(rpc::WarnRpcRateLimit)}; } response.setMessage(jsonResponse); } diff --git a/src/data/AmendmentCenter.cpp b/src/data/AmendmentCenter.cpp index 863ffc38..f2caeeca 100644 --- a/src/data/AmendmentCenter.cpp +++ b/src/data/AmendmentCenter.cpp @@ -50,10 +50,10 @@ namespace { std::unordered_set& -SUPPORTED_AMENDMENTS() +supportedAmendments() { - static std::unordered_set amendments = {}; - return amendments; + static std::unordered_set kAMENDMENTS = {}; + return kAMENDMENTS; } bool @@ -72,8 +72,8 @@ namespace impl { WritingAmendmentKey::WritingAmendmentKey(std::string amendmentName) : AmendmentKey{std::move(amendmentName)} { - ASSERT(not SUPPORTED_AMENDMENTS().contains(name), "Attempt to register the same amendment twice"); - SUPPORTED_AMENDMENTS().insert(name); + ASSERT(not supportedAmendments().contains(name), "Attempt to register the same amendment twice"); + supportedAmendments().insert(name); } } // namespace impl @@ -90,7 +90,7 @@ AmendmentKey::operator std::string_view() const AmendmentKey::operator ripple::uint256() const { - return Amendment::GetAmendmentId(name); + return Amendment::getAmendmentId(name); } AmendmentCenter::AmendmentCenter(std::shared_ptr const& backend) : backend_{backend} @@ -103,9 +103,9 @@ AmendmentCenter::AmendmentCenter(std::shared_ptr const& auto const& [name, support] = p; return Amendment{ .name = name, - .feature = Amendment::GetAmendmentId(name), + .feature = Amendment::getAmendmentId(name), .isSupportedByXRPL = support != ripple::AmendmentSupport::Unsupported, - .isSupportedByClio = rg::find(SUPPORTED_AMENDMENTS(), name) != rg::end(SUPPORTED_AMENDMENTS()), + .isSupportedByClio = rg::find(supportedAmendments(), name) != rg::end(supportedAmendments()), .isRetired = support == ripple::AmendmentSupport::Retired }; }), @@ -180,7 +180,7 @@ AmendmentCenter::operator[](AmendmentKey const& key) const } ripple::uint256 -Amendment::GetAmendmentId(std::string_view name) +Amendment::getAmendmentId(std::string_view name) { return ripple::sha512Half(ripple::Slice(name.data(), name.size())); } diff --git a/src/data/AmendmentCenter.hpp b/src/data/AmendmentCenter.hpp index f6b8d8fd..0413f009 100644 --- a/src/data/AmendmentCenter.hpp +++ b/src/data/AmendmentCenter.hpp @@ -67,6 +67,7 @@ struct Amendments { // Most of the time it's going to be no changes at all. /** @cond */ + // NOLINTBEGIN(readability-identifier-naming) REGISTER(OwnerPaysFee); REGISTER(Flow); REGISTER(FlowCross); @@ -154,6 +155,7 @@ struct Amendments { REGISTER(fix1512); REGISTER(fix1523); REGISTER(fix1528); + // NOLINTEND(readability-identifier-naming) /** @endcond */ }; diff --git a/src/data/BackendCounters.cpp b/src/data/BackendCounters.cpp index e868941b..5fcc2d03 100644 --- a/src/data/BackendCounters.cpp +++ b/src/data/BackendCounters.cpp @@ -36,7 +36,7 @@ namespace data { namespace { -std::vector const histogramBuckets{1, 2, 5, 10, 20, 50, 100, 200, 500, 700, 1000}; +std::vector const kHISTOGRAM_BUCKETS{1, 2, 5, 10, 20, 50, 100, 200, 500, 700, 1000}; std::int64_t durationInMillisecondsSince(std::chrono::steady_clock::time_point const startTime) @@ -69,13 +69,13 @@ BackendCounters::BackendCounters() , readDurationHistogram_(PrometheusService::histogramInt( "backend_duration_milliseconds_histogram", Labels({Label{"operation", "read"}}), - histogramBuckets, + kHISTOGRAM_BUCKETS, "The duration of backend read operations including retries" )) , writeDurationHistogram_(PrometheusService::histogramInt( "backend_duration_milliseconds_histogram", Labels({Label{"operation", "write"}}), - histogramBuckets, + kHISTOGRAM_BUCKETS, "The duration of backend write operations including retries" )) { diff --git a/src/data/BackendFactory.hpp b/src/data/BackendFactory.hpp index d3990faf..fcb64161 100644 --- a/src/data/BackendFactory.hpp +++ b/src/data/BackendFactory.hpp @@ -41,9 +41,9 @@ namespace data { * @return A shared_ptr with the selected implementation */ inline std::shared_ptr -make_Backend(util::config::ClioConfigDefinition const& config) +makeBackend(util::config::ClioConfigDefinition const& config) { - static util::Logger const log{"Backend"}; + static util::Logger const log{"Backend"}; // NOLINT(readability-identifier-naming) LOG(log.info()) << "Constructing BackendInterface"; auto const readOnly = config.get("read_only"); diff --git a/src/data/BackendInterface.cpp b/src/data/BackendInterface.cpp index 3c43f2bd..1eafa9cb 100644 --- a/src/data/BackendInterface.cpp +++ b/src/data/BackendInterface.cpp @@ -267,7 +267,7 @@ std::optional BackendInterface::fetchLedgerRange() const { std::shared_lock const lck(rngMtx_); - return range; + return range_; } void @@ -276,16 +276,16 @@ BackendInterface::updateRange(uint32_t newMax) std::scoped_lock const lck(rngMtx_); ASSERT( - !range || newMax >= range->maxSequence, + !range_ || newMax >= range_->maxSequence, "Range shouldn't exist yet or newMax should be greater. newMax = {}, range->maxSequence = {}", newMax, - range->maxSequence + range_->maxSequence ); - if (!range) { - range = {.minSequence = newMax, .maxSequence = newMax}; + if (!range_) { + range_ = {.minSequence = newMax, .maxSequence = newMax}; } else { - range->maxSequence = newMax; + range_->maxSequence = newMax; } } @@ -296,10 +296,10 @@ BackendInterface::setRange(uint32_t min, uint32_t max, bool force) if (!force) { ASSERT(min <= max, "Range min must be less than or equal to max"); - ASSERT(not range.has_value(), "Range was already set"); + ASSERT(not range_.has_value(), "Range was already set"); } - range = {.minSequence = min, .maxSequence = max}; + range_ = {.minSequence = min, .maxSequence = max}; } LedgerPage @@ -320,10 +320,10 @@ BackendInterface::fetchLedgerPage( ripple::uint256 const& curCursor = [&]() { if (!keys.empty()) return keys.back(); - return (cursor ? *cursor : firstKey); + return (cursor ? *cursor : kFIRST_KEY); }(); - std::uint32_t const seq = outOfOrder ? range->maxSequence : ledgerSequence; + std::uint32_t const seq = outOfOrder ? range_->maxSequence : ledgerSequence; auto succ = fetchSuccessorKey(curCursor, seq, yield); if (!succ) { diff --git a/src/data/BackendInterface.hpp b/src/data/BackendInterface.hpp index a8a447b7..2d7e3ef6 100644 --- a/src/data/BackendInterface.hpp +++ b/src/data/BackendInterface.hpp @@ -65,7 +65,7 @@ public: } }; -static constexpr std::size_t DEFAULT_WAIT_BETWEEN_RETRY = 500; +static constexpr std::size_t kDEFAULT_WAIT_BETWEEN_RETRY = 500; /** * @brief A helper function that catches DatabaseTimout exceptions and retries indefinitely. * @@ -76,9 +76,9 @@ static constexpr std::size_t DEFAULT_WAIT_BETWEEN_RETRY = 500; */ template auto -retryOnTimeout(FnType func, size_t waitMs = DEFAULT_WAIT_BETWEEN_RETRY) +retryOnTimeout(FnType func, size_t waitMs = kDEFAULT_WAIT_BETWEEN_RETRY) { - static util::Logger const log{"Backend"}; + static util::Logger const log{"Backend"}; // NOLINT(readability-identifier-naming) while (true) { try { @@ -138,7 +138,7 @@ synchronousAndRetryOnTimeout(FnType&& func) class BackendInterface { protected: mutable std::shared_mutex rngMtx_; - std::optional range; + std::optional range_; LedgerCache cache_; std::optional> corruptionDetector_; diff --git a/src/data/CassandraBackend.hpp b/src/data/CassandraBackend.hpp index 2ab20cbe..ba8aacd7 100644 --- a/src/data/CassandraBackend.hpp +++ b/src/data/CassandraBackend.hpp @@ -22,6 +22,7 @@ #include "data/BackendInterface.hpp" #include "data/DBHelpers.hpp" #include "data/Types.hpp" +#include "data/cassandra/Concepts.hpp" #include "data/cassandra/Handle.hpp" #include "data/cassandra/Schema.hpp" #include "data/cassandra/SettingsProvider.hpp" @@ -193,7 +194,7 @@ public: // wait for other threads to finish their writes executor_.sync(); - if (!range) { + if (!range_) { executor_.writeSync(schema_->updateLedgerRange, ledgerSequence_, false, ledgerSequence_); } @@ -649,7 +650,7 @@ public: { if (auto const res = executor_.read(yield, schema_->selectSuccessor, key, ledgerSequence); res) { if (auto const result = res->template get(); result) { - if (*result == lastKey) + if (*result == kLAST_KEY) return std::nullopt; return result; } @@ -862,7 +863,7 @@ public: { LOG(log_.trace()) << " Writing ledger object " << key.size() << ":" << seq << " [" << blob.size() << " bytes]"; - if (range) + if (range_) executor_.write(schema_->insertDiff, seq, key); executor_.write(schema_->insertObject, std::move(key), seq, std::move(blob)); diff --git a/src/data/DBHelpers.hpp b/src/data/DBHelpers.hpp index 6f27de82..520228e3 100644 --- a/src/data/DBHelpers.hpp +++ b/src/data/DBHelpers.hpp @@ -190,11 +190,11 @@ template inline bool isOffer(T const& object) { - static constexpr short OFFER_OFFSET = 0x006f; - static constexpr short SHIFT = 8; + static constexpr short kOFFER_OFFSET = 0x006f; + static constexpr short kSHIFT = 8; - short offer_bytes = (object[1] << SHIFT) | object[2]; - return offer_bytes == OFFER_OFFSET; + short offerBytes = (object[1] << kSHIFT) | object[2]; + return offerBytes == kOFFER_OFFSET; } /** @@ -223,9 +223,9 @@ template inline bool isDirNode(T const& object) { - static constexpr short DIR_NODE_SPACE_KEY = 0x0064; + static constexpr short kDIR_NODE_SPACE_KEY = 0x0064; short const spaceKey = (object.data()[1] << 8) | object.data()[2]; - return spaceKey == DIR_NODE_SPACE_KEY; + return spaceKey == kDIR_NODE_SPACE_KEY; } /** @@ -273,12 +273,12 @@ template inline ripple::uint256 getBookBase(T const& key) { - static constexpr size_t KEY_SIZE = 24; + static constexpr size_t kEY_SIZE = 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 < kEY_SIZE; ++i) ret.data()[i] = key.data()[i]; return ret; @@ -297,4 +297,4 @@ uint256ToString(ripple::uint256 const& input) } /** @brief The ripple epoch start timestamp. Midnight on 1st January 2000. */ -static constexpr std::uint32_t rippleEpochStart = 946684800; +static constexpr std::uint32_t kRIPPLE_EPOCH_START = 946684800; diff --git a/src/data/Types.hpp b/src/data/Types.hpp index cb1eaa23..80d64a45 100644 --- a/src/data/Types.hpp +++ b/src/data/Types.hpp @@ -266,7 +266,7 @@ struct Amendment { * @return The amendment Id as uint256 */ static ripple::uint256 - GetAmendmentId(std::string_view const name); + getAmendmentId(std::string_view const name); /** * @brief Equality comparison operator @@ -312,8 +312,8 @@ struct AmendmentKey { operator<=>(AmendmentKey const& other) const = default; }; -constexpr ripple::uint256 firstKey{"0000000000000000000000000000000000000000000000000000000000000000"}; -constexpr ripple::uint256 lastKey{"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"}; -constexpr ripple::uint256 hi192{"0000000000000000000000000000000000000000000000001111111111111111"}; +constexpr ripple::uint256 kFIRST_KEY{"0000000000000000000000000000000000000000000000000000000000000000"}; +constexpr ripple::uint256 kLAST_KEY{"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"}; +constexpr ripple::uint256 kHI192{"0000000000000000000000000000000000000000000000001111111111111111"}; } // namespace data diff --git a/src/data/cassandra/SettingsProvider.cpp b/src/data/cassandra/SettingsProvider.cpp index 5a05da68..478a2348 100644 --- a/src/data/cassandra/SettingsProvider.cpp +++ b/src/data/cassandra/SettingsProvider.cpp @@ -100,12 +100,12 @@ SettingsProvider::parseSettings() const if (config_.getValueView("connect_timeout").hasValue()) { auto const connectTimeoutSecond = config_.get("connect_timeout"); - settings.connectionTimeout = std::chrono::milliseconds{connectTimeoutSecond * util::MILLISECONDS_PER_SECOND}; + settings.connectionTimeout = std::chrono::milliseconds{connectTimeoutSecond * util::kMILLISECONDS_PER_SECOND}; } if (config_.getValueView("request_timeout").hasValue()) { auto const requestTimeoutSecond = config_.get("request_timeout"); - settings.requestTimeout = std::chrono::milliseconds{requestTimeoutSecond * util::MILLISECONDS_PER_SECOND}; + settings.requestTimeout = std::chrono::milliseconds{requestTimeoutSecond * util::kMILLISECONDS_PER_SECOND}; } settings.certificate = parseOptionalCertificate(); diff --git a/src/data/cassandra/impl/Batch.cpp b/src/data/cassandra/impl/Batch.cpp index bcaf4f45..b26e889c 100644 --- a/src/data/cassandra/impl/Batch.cpp +++ b/src/data/cassandra/impl/Batch.cpp @@ -31,14 +31,14 @@ #include namespace { -constexpr auto batchDeleter = [](CassBatch* ptr) { cass_batch_free(ptr); }; +constexpr auto kBATCH_DELETER = [](CassBatch* ptr) { cass_batch_free(ptr); }; } // namespace namespace data::cassandra::impl { // TODO: Use an appropriate value instead of CASS_BATCH_TYPE_LOGGED for different use cases Batch::Batch(std::vector const& statements) - : ManagedObject{cass_batch_new(CASS_BATCH_TYPE_LOGGED), batchDeleter} + : ManagedObject{cass_batch_new(CASS_BATCH_TYPE_LOGGED), kBATCH_DELETER} { cass_batch_set_is_idempotent(*this, cass_true); diff --git a/src/data/cassandra/impl/Cluster.cpp b/src/data/cassandra/impl/Cluster.cpp index 80c6b4e7..ea49cf46 100644 --- a/src/data/cassandra/impl/Cluster.cpp +++ b/src/data/cassandra/impl/Cluster.cpp @@ -33,13 +33,13 @@ namespace { -constexpr auto clusterDeleter = [](CassCluster* ptr) { cass_cluster_free(ptr); }; +constexpr auto kCLUSTER_DELETER = [](CassCluster* ptr) { cass_cluster_free(ptr); }; }; // namespace namespace data::cassandra::impl { -Cluster::Cluster(Settings const& settings) : ManagedObject{cass_cluster_new(), clusterDeleter} +Cluster::Cluster(Settings const& settings) : ManagedObject{cass_cluster_new(), kCLUSTER_DELETER} { using std::to_string; diff --git a/src/data/cassandra/impl/Cluster.hpp b/src/data/cassandra/impl/Cluster.hpp index bd82ceeb..61bdbfd5 100644 --- a/src/data/cassandra/impl/Cluster.hpp +++ b/src/data/cassandra/impl/Cluster.hpp @@ -25,6 +25,8 @@ #include #include +#include +#include #include #include #include @@ -39,10 +41,10 @@ namespace data::cassandra::impl { * @brief Bundles all cassandra settings in one place. */ struct Settings { - static constexpr std::size_t DEFAULT_CONNECTION_TIMEOUT = 10000; - static constexpr uint32_t DEFAULT_MAX_WRITE_REQUESTS_OUTSTANDING = 10'000; - static constexpr uint32_t DEFAULT_MAX_READ_REQUESTS_OUTSTANDING = 100'000; - static constexpr std::size_t DEFAULT_BATCH_SIZE = 20; + 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; /** * @brief Represents the configuration of contact points for cassandra. @@ -63,7 +65,7 @@ struct Settings { bool enableLog = false; /** @brief Connect timeout specified in milliseconds */ - std::chrono::milliseconds connectionTimeout = std::chrono::milliseconds{DEFAULT_CONNECTION_TIMEOUT}; + std::chrono::milliseconds connectionTimeout = std::chrono::milliseconds{kDEFAULT_CONNECTION_TIMEOUT}; /** @brief Request timeout specified in milliseconds */ std::chrono::milliseconds requestTimeout = std::chrono::milliseconds{0}; // no timeout at all @@ -75,16 +77,16 @@ struct Settings { uint32_t threads = std::thread::hardware_concurrency(); /** @brief The maximum number of outstanding write requests at any given moment */ - uint32_t maxWriteRequestsOutstanding = DEFAULT_MAX_WRITE_REQUESTS_OUTSTANDING; + uint32_t maxWriteRequestsOutstanding = kDEFAULT_MAX_WRITE_REQUESTS_OUTSTANDING; /** @brief The maximum number of outstanding read requests at any given moment */ - uint32_t maxReadRequestsOutstanding = DEFAULT_MAX_READ_REQUESTS_OUTSTANDING; + uint32_t maxReadRequestsOutstanding = kDEFAULT_MAX_READ_REQUESTS_OUTSTANDING; /** @brief The number of connection per host to always have active */ uint32_t coreConnectionsPerHost = 1u; /** @brief Size of batches when writing */ - std::size_t writeBatchSize = DEFAULT_BATCH_SIZE; + std::size_t writeBatchSize = kDEFAULT_BATCH_SIZE; /** @brief Size of the IO queue */ std::optional queueSizeIO = std::nullopt; // NOLINT(readability-redundant-member-init) diff --git a/src/data/cassandra/impl/Collection.hpp b/src/data/cassandra/impl/Collection.hpp index b4a92751..8caa11fd 100644 --- a/src/data/cassandra/impl/Collection.hpp +++ b/src/data/cassandra/impl/Collection.hpp @@ -33,7 +33,7 @@ namespace data::cassandra::impl { class Collection : public ManagedObject { - static constexpr auto deleter = [](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) @@ -49,7 +49,7 @@ public: template explicit Collection(std::vector const& value) - : ManagedObject{cass_collection_new(CASS_COLLECTION_TYPE_LIST, value.size()), deleter} + : ManagedObject{cass_collection_new(CASS_COLLECTION_TYPE_LIST, value.size()), kDELETER} { bind(value); } diff --git a/src/data/cassandra/impl/Future.cpp b/src/data/cassandra/impl/Future.cpp index 2e87b52b..8389e32f 100644 --- a/src/data/cassandra/impl/Future.cpp +++ b/src/data/cassandra/impl/Future.cpp @@ -32,12 +32,12 @@ #include namespace { -constexpr auto futureDeleter = [](CassFuture* ptr) { cass_future_free(ptr); }; +constexpr auto kFUTURE_DELETER = [](CassFuture* ptr) { cass_future_free(ptr); }; } // namespace namespace data::cassandra::impl { -/* implicit */ Future::Future(CassFuture* ptr) : ManagedObject{ptr, futureDeleter} +/* implicit */ Future::Future(CassFuture* ptr) : ManagedObject{ptr, kFUTURE_DELETER} { } diff --git a/src/data/cassandra/impl/ManagedObject.hpp b/src/data/cassandra/impl/ManagedObject.hpp index 212b1e47..e5fe95c1 100644 --- a/src/data/cassandra/impl/ManagedObject.hpp +++ b/src/data/cassandra/impl/ManagedObject.hpp @@ -30,8 +30,8 @@ protected: std::unique_ptr ptr_; public: - template - ManagedObject(Managed* rawPtr, deleterCallable deleter) : ptr_{rawPtr, deleter} + template + ManagedObject(Managed* rawPtr, DeleterCallable deleter) : ptr_{rawPtr, deleter} { if (rawPtr == nullptr) throw std::runtime_error("Could not create DB object - got nullptr"); diff --git a/src/data/cassandra/impl/Result.cpp b/src/data/cassandra/impl/Result.cpp index 9168bfb7..f6eee14e 100644 --- a/src/data/cassandra/impl/Result.cpp +++ b/src/data/cassandra/impl/Result.cpp @@ -26,13 +26,13 @@ #include namespace { -constexpr auto resultDeleter = [](CassResult const* ptr) { cass_result_free(ptr); }; -constexpr auto resultIteratorDeleter = [](CassIterator* ptr) { cass_iterator_free(ptr); }; +constexpr auto kRESULT_DELETER = [](CassResult const* ptr) { cass_result_free(ptr); }; +constexpr auto kRESULT_ITERATOR_DELETER = [](CassIterator* ptr) { cass_iterator_free(ptr); }; } // namespace namespace data::cassandra::impl { -/* implicit */ Result::Result(CassResult const* ptr) : ManagedObject{ptr, resultDeleter} +/* implicit */ Result::Result(CassResult const* ptr) : ManagedObject{ptr, kRESULT_DELETER} { } @@ -49,7 +49,7 @@ Result::hasRows() const } /* implicit */ ResultIterator::ResultIterator(CassIterator* ptr) - : ManagedObject{ptr, resultIteratorDeleter}, hasMore_{cass_iterator_next(ptr) != 0u} + : ManagedObject{ptr, kRESULT_ITERATOR_DELETER}, hasMore_{cass_iterator_next(ptr) != 0u} { } diff --git a/src/data/cassandra/impl/Session.hpp b/src/data/cassandra/impl/Session.hpp index af9ec837..2b6d2b6e 100644 --- a/src/data/cassandra/impl/Session.hpp +++ b/src/data/cassandra/impl/Session.hpp @@ -26,10 +26,10 @@ namespace data::cassandra::impl { class Session : public ManagedObject { - static constexpr auto deleter = [](CassSession* ptr) { cass_session_free(ptr); }; + static constexpr auto kDELETER = [](CassSession* ptr) { cass_session_free(ptr); }; public: - Session() : ManagedObject{cass_session_new(), deleter} + Session() : ManagedObject{cass_session_new(), kDELETER} { } }; diff --git a/src/data/cassandra/impl/SslContext.cpp b/src/data/cassandra/impl/SslContext.cpp index c2524e2c..cf6b1ac2 100644 --- a/src/data/cassandra/impl/SslContext.cpp +++ b/src/data/cassandra/impl/SslContext.cpp @@ -27,12 +27,12 @@ #include namespace { -constexpr auto contextDeleter = [](CassSsl* ptr) { cass_ssl_free(ptr); }; +constexpr auto kCONTEXT_DELETER = [](CassSsl* ptr) { cass_ssl_free(ptr); }; } // namespace namespace data::cassandra::impl { -SslContext::SslContext(std::string const& certificate) : ManagedObject{cass_ssl_new(), contextDeleter} +SslContext::SslContext(std::string const& certificate) : ManagedObject{cass_ssl_new(), kCONTEXT_DELETER} { 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) { diff --git a/src/data/cassandra/impl/Statement.hpp b/src/data/cassandra/impl/Statement.hpp index 50b579f2..c7692aa6 100644 --- a/src/data/cassandra/impl/Statement.hpp +++ b/src/data/cassandra/impl/Statement.hpp @@ -43,7 +43,7 @@ namespace data::cassandra::impl { class Statement : public ManagedObject { - static constexpr auto deleter = [](CassStatement* ptr) { cass_statement_free(ptr); }; + static constexpr auto kDELETER = [](CassStatement* ptr) { cass_statement_free(ptr); }; public: /** @@ -54,14 +54,14 @@ public: */ template explicit Statement(std::string_view query, Args&&... args) - : ManagedObject{cass_statement_new_n(query.data(), query.size(), sizeof...(args)), deleter} + : ManagedObject{cass_statement_new_n(query.data(), query.size(), sizeof...(args)), kDELETER} { cass_statement_set_consistency(*this, CASS_CONSISTENCY_QUORUM); cass_statement_set_is_idempotent(*this, cass_true); bind(std::forward(args)...); } - /* implicit */ Statement(CassStatement* ptr) : ManagedObject{ptr, deleter} + /* implicit */ Statement(CassStatement* ptr) : ManagedObject{ptr, kDELETER} { cass_statement_set_consistency(*this, CASS_CONSISTENCY_QUORUM); cass_statement_set_is_idempotent(*this, cass_true); @@ -153,10 +153,10 @@ public: * This is used to produce Statement objects that can be executed. */ class PreparedStatement : public ManagedObject { - static constexpr auto deleter = [](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, deleter} + /* implicit */ PreparedStatement(CassPrepared const* ptr) : ManagedObject{ptr, kDELETER} { } diff --git a/src/data/cassandra/impl/Tuple.cpp b/src/data/cassandra/impl/Tuple.cpp index 1103b83f..b11308ed 100644 --- a/src/data/cassandra/impl/Tuple.cpp +++ b/src/data/cassandra/impl/Tuple.cpp @@ -24,17 +24,17 @@ #include namespace { -constexpr auto tupleDeleter = [](CassTuple* ptr) { cass_tuple_free(ptr); }; -constexpr auto tupleIteratorDeleter = [](CassIterator* ptr) { cass_iterator_free(ptr); }; +constexpr auto kTUPLE_DELETER = [](CassTuple* ptr) { cass_tuple_free(ptr); }; +constexpr auto kTUPLE_ITERATOR_DELETER = [](CassIterator* ptr) { cass_iterator_free(ptr); }; } // namespace namespace data::cassandra::impl { -/* implicit */ Tuple::Tuple(CassTuple* ptr) : ManagedObject{ptr, tupleDeleter} +/* implicit */ Tuple::Tuple(CassTuple* ptr) : ManagedObject{ptr, kTUPLE_DELETER} { } -/* implicit */ TupleIterator::TupleIterator(CassIterator* ptr) : ManagedObject{ptr, tupleIteratorDeleter} +/* implicit */ TupleIterator::TupleIterator(CassIterator* ptr) : ManagedObject{ptr, kTUPLE_ITERATOR_DELETER} { } diff --git a/src/data/cassandra/impl/Tuple.hpp b/src/data/cassandra/impl/Tuple.hpp index 72224d13..d498b924 100644 --- a/src/data/cassandra/impl/Tuple.hpp +++ b/src/data/cassandra/impl/Tuple.hpp @@ -37,14 +37,14 @@ namespace data::cassandra::impl { class Tuple : public ManagedObject { - static constexpr auto deleter = [](CassTuple* ptr) { cass_tuple_free(ptr); }; + static constexpr auto kDELETER = [](CassTuple* ptr) { cass_tuple_free(ptr); }; public: /* implicit */ Tuple(CassTuple* ptr); template explicit Tuple(std::tuple&& value) - : ManagedObject{cass_tuple_new(std::tuple_size>{}), deleter} + : ManagedObject{cass_tuple_new(std::tuple_size>{}), kDELETER} { std::apply(std::bind_front(&Tuple::bind, this), std::move(value)); } diff --git a/src/etl/CacheLoader.hpp b/src/etl/CacheLoader.hpp index 739d94e8..0d53688d 100644 --- a/src/etl/CacheLoader.hpp +++ b/src/etl/CacheLoader.hpp @@ -69,7 +69,7 @@ public: std::shared_ptr const& backend, CacheType& cache ) - : backend_{backend}, cache_{cache}, settings_{make_CacheLoaderSettings(config)}, ctx_{settings_.numThreads} + : backend_{backend}, cache_{cache}, settings_{makeCacheLoaderSettings(config)}, ctx_{settings_.numThreads} { } diff --git a/src/etl/CacheLoaderSettings.cpp b/src/etl/CacheLoaderSettings.cpp index 08f43ed8..9f6a1623 100644 --- a/src/etl/CacheLoaderSettings.cpp +++ b/src/etl/CacheLoaderSettings.cpp @@ -48,7 +48,7 @@ CacheLoaderSettings::isDisabled() const } [[nodiscard]] CacheLoaderSettings -make_CacheLoaderSettings(util::config::ClioConfigDefinition const& config) +makeCacheLoaderSettings(util::config::ClioConfigDefinition const& config) { CacheLoaderSettings settings; settings.numThreads = config.get("io_threads"); diff --git a/src/etl/CacheLoaderSettings.hpp b/src/etl/CacheLoaderSettings.hpp index 367d915b..d1439058 100644 --- a/src/etl/CacheLoaderSettings.hpp +++ b/src/etl/CacheLoaderSettings.hpp @@ -64,6 +64,6 @@ struct CacheLoaderSettings { * @returns The CacheLoaderSettings object */ [[nodiscard]] CacheLoaderSettings -make_CacheLoaderSettings(util::config::ClioConfigDefinition const& config); +makeCacheLoaderSettings(util::config::ClioConfigDefinition const& config); } // namespace etl diff --git a/src/etl/ETLService.cpp b/src/etl/ETLService.cpp index 6065cd0a..3807efed 100644 --- a/src/etl/ETLService.cpp +++ b/src/etl/ETLService.cpp @@ -88,9 +88,9 @@ ETLService::runETLPipeline(uint32_t startSequence, uint32_t numExtractors) auto const end = std::chrono::system_clock::now(); auto const lastPublishedSeq = ledgerPublisher_.getLastPublishedSequence(); - static constexpr auto NANOSECONDS_PER_SECOND = 1'000'000'000.0; + static constexpr auto kNANOSECONDS_PER_SECOND = 1'000'000'000.0; LOG(log_.debug()) << "Extracted and wrote " << lastPublishedSeq.value_or(startSequence) - startSequence << " in " - << ((end - begin).count()) / NANOSECONDS_PER_SECOND; + << ((end - begin).count()) / kNANOSECONDS_PER_SECOND; state_.isWriting = false; @@ -168,7 +168,7 @@ ETLService::publishNextSequence(uint32_t nextSequence) if (auto rng = backend_->hardFetchLedgerRangeNoThrow(); rng && rng->maxSequence >= nextSequence) { ledgerPublisher_.publish(nextSequence, {}); ++nextSequence; - } else if (networkValidatedLedgers_->waitUntilValidatedByNetwork(nextSequence, util::MILLISECONDS_PER_SECOND)) { + } else if (networkValidatedLedgers_->waitUntilValidatedByNetwork(nextSequence, util::kMILLISECONDS_PER_SECOND)) { LOG(log_.info()) << "Ledger with sequence = " << nextSequence << " has been validated by the network. " << "Attempting to find in database and publish"; @@ -178,8 +178,8 @@ ETLService::publishNextSequence(uint32_t nextSequence) // database after the specified number of attempts. publishLedger() // waits one second between each attempt to read the ledger from the // database - constexpr size_t timeoutSeconds = 10; - bool const success = ledgerPublisher_.publish(nextSequence, timeoutSeconds); + constexpr size_t kTIMEOUT_SECONDS = 10; + bool const success = ledgerPublisher_.publish(nextSequence, kTIMEOUT_SECONDS); if (!success) { LOG(log_.warn()) << "Failed to publish ledger with sequence = " << nextSequence << " . Beginning ETL"; @@ -233,7 +233,7 @@ ETLService::monitorReadOnly() // if we can't, wait until it's validated by the network, or 1 second passes, whichever occurs // first. Even if we don't hear from rippled, if ledgers are being written to the db, we publish // them. - networkValidatedLedgers_->waitUntilValidatedByNetwork(latestSequence, util::MILLISECONDS_PER_SECOND); + networkValidatedLedgers_->waitUntilValidatedByNetwork(latestSequence, util::kMILLISECONDS_PER_SECOND); } } } diff --git a/src/etl/ETLService.hpp b/src/etl/ETLService.hpp index 3583bb89..1dbbd94c 100644 --- a/src/etl/ETLService.hpp +++ b/src/etl/ETLService.hpp @@ -141,7 +141,7 @@ public: * @return A shared pointer to a new instance of ETLService */ static std::shared_ptr - make_ETLService( + makeETLService( util::config::ClioConfigDefinition const& config, boost::asio::io_context& ioc, std::shared_ptr backend, diff --git a/src/etl/LoadBalancer.cpp b/src/etl/LoadBalancer.cpp index f10a7bc2..6e961933 100644 --- a/src/etl/LoadBalancer.cpp +++ b/src/etl/LoadBalancer.cpp @@ -59,7 +59,7 @@ using namespace util::config; namespace etl { std::shared_ptr -LoadBalancer::make_LoadBalancer( +LoadBalancer::makeLoadBalancer( ClioConfigDefinition const& config, boost::asio::io_context& ioc, std::shared_ptr backend, @@ -235,7 +235,7 @@ LoadBalancer::forwardToRippled( ) { if (not request.contains("command")) - return std::unexpected{rpc::ClioError::rpcCOMMAND_IS_MISSING}; + return std::unexpected{rpc::ClioError::RpcCommandIsMissing}; auto const cmd = boost::json::value_to(request.at("command")); if (forwardingCache_) { @@ -249,10 +249,10 @@ LoadBalancer::forwardToRippled( auto numAttempts = 0u; - auto xUserValue = isAdmin ? ADMIN_FORWARDING_X_USER_VALUE : USER_FORWARDING_X_USER_VALUE; + auto xUserValue = isAdmin ? kADMIN_FORWARDING_X_USER_VALUE : kUSER_FORWARDING_X_USER_VALUE; std::optional response; - rpc::ClioError error = rpc::ClioError::etlCONNECTION_ERROR; + rpc::ClioError error = rpc::ClioError::EtlConnectionError; while (numAttempts < sources_.size()) { auto res = sources_[sourceIdx]->forwardToRippled(request, clientIp, xUserValue, yield); if (res) { diff --git a/src/etl/LoadBalancer.hpp b/src/etl/LoadBalancer.hpp index 9d19aeed..60f56a48 100644 --- a/src/etl/LoadBalancer.hpp +++ b/src/etl/LoadBalancer.hpp @@ -65,7 +65,7 @@ public: using OptionalGetLedgerResponseType = std::optional; private: - static constexpr std::uint32_t DEFAULT_DOWNLOAD_RANGES = 16; + static constexpr std::uint32_t kDEFAULT_DOWNLOAD_RANGES = 16; util::Logger log_{"ETL"}; // Forwarding cache must be destroyed after sources because sources have a callback to invalidate cache @@ -75,7 +75,7 @@ private: std::vector sources_; std::optional etlState_; std::uint32_t downloadRanges_ = - DEFAULT_DOWNLOAD_RANGES; /*< The number of markers to use when downloading initial ledger */ + kDEFAULT_DOWNLOAD_RANGES; /*< The number of markers to use when downloading initial ledger */ // Using mutext instead of atomic_bool because choosing a new source to // forward messages should be done with a mutual exclusion otherwise there will be a race condition @@ -85,12 +85,12 @@ public: /** * @brief Value for the X-User header when forwarding admin requests */ - static constexpr std::string_view ADMIN_FORWARDING_X_USER_VALUE = "clio_admin"; + static constexpr std::string_view kADMIN_FORWARDING_X_USER_VALUE = "clio_admin"; /** * @brief Value for the X-User header when forwarding user requests */ - static constexpr std::string_view USER_FORWARDING_X_USER_VALUE = "clio_user"; + static constexpr std::string_view kUSER_FORWARDING_X_USER_VALUE = "clio_user"; /** * @brief Create an instance of the load balancer. @@ -108,7 +108,7 @@ public: std::shared_ptr backend, std::shared_ptr subscriptions, std::shared_ptr validatedLedgers, - SourceFactory sourceFactory = make_Source + SourceFactory sourceFactory = makeSource ); /** @@ -123,13 +123,13 @@ public: * @return A shared pointer to a new instance of LoadBalancer */ static std::shared_ptr - make_LoadBalancer( + makeLoadBalancer( util::config::ClioConfigDefinition const& config, boost::asio::io_context& ioc, std::shared_ptr backend, std::shared_ptr subscriptions, std::shared_ptr validatedLedgers, - SourceFactory sourceFactory = make_Source + SourceFactory sourceFactory = makeSource ); ~LoadBalancer(); diff --git a/src/etl/NetworkValidatedLedgers.cpp b/src/etl/NetworkValidatedLedgers.cpp index 2074efe8..9a317c06 100644 --- a/src/etl/NetworkValidatedLedgers.cpp +++ b/src/etl/NetworkValidatedLedgers.cpp @@ -27,7 +27,7 @@ namespace etl { std::shared_ptr -NetworkValidatedLedgers::make_ValidatedLedgers() +NetworkValidatedLedgers::makeValidatedLedgers() { return std::make_shared(); } diff --git a/src/etl/NetworkValidatedLedgers.hpp b/src/etl/NetworkValidatedLedgers.hpp index 339be1d7..c694c3b8 100644 --- a/src/etl/NetworkValidatedLedgers.hpp +++ b/src/etl/NetworkValidatedLedgers.hpp @@ -51,7 +51,7 @@ public: * @return A shared pointer to a new instance of NetworkValidatedLedgers */ static std::shared_ptr - make_ValidatedLedgers(); + makeValidatedLedgers(); /** * @brief Notify the datastructure that idx has been validated by the network. diff --git a/src/etl/Source.cpp b/src/etl/Source.cpp index abe574af..5de0586c 100644 --- a/src/etl/Source.cpp +++ b/src/etl/Source.cpp @@ -38,7 +38,7 @@ namespace etl { SourcePtr -make_Source( +makeSource( util::config::ObjectView const& config, boost::asio::io_context& ioc, std::shared_ptr backend, diff --git a/src/etl/Source.hpp b/src/etl/Source.hpp index 6adda85d..e5084972 100644 --- a/src/etl/Source.hpp +++ b/src/etl/Source.hpp @@ -175,7 +175,7 @@ using SourceFactory = std::function backend, diff --git a/src/etl/impl/AmendmentBlockHandler.cpp b/src/etl/impl/AmendmentBlockHandler.cpp index f8ea09b3..9b732bf6 100644 --- a/src/etl/impl/AmendmentBlockHandler.cpp +++ b/src/etl/impl/AmendmentBlockHandler.cpp @@ -30,8 +30,8 @@ namespace etl::impl { -AmendmentBlockHandler::ActionType const AmendmentBlockHandler::defaultAmendmentBlockAction = []() { - static util::Logger const log{"ETL"}; +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."; }; diff --git a/src/etl/impl/AmendmentBlockHandler.hpp b/src/etl/impl/AmendmentBlockHandler.hpp index 423e7647..b50d909b 100644 --- a/src/etl/impl/AmendmentBlockHandler.hpp +++ b/src/etl/impl/AmendmentBlockHandler.hpp @@ -43,13 +43,13 @@ private: ActionType action_; public: - static ActionType const defaultAmendmentBlockAction; + static ActionType const kDEFAULT_AMENDMENT_BLOCK_ACTION; AmendmentBlockHandler( boost::asio::io_context& ioc, SystemState& state, std::chrono::steady_clock::duration interval = std::chrono::seconds{1}, - ActionType action = defaultAmendmentBlockAction + ActionType action = kDEFAULT_AMENDMENT_BLOCK_ACTION ); void diff --git a/src/etl/impl/CursorFromAccountProvider.hpp b/src/etl/impl/CursorFromAccountProvider.hpp index 3a762547..0ae6d8a7 100644 --- a/src/etl/impl/CursorFromAccountProvider.hpp +++ b/src/etl/impl/CursorFromAccountProvider.hpp @@ -58,10 +58,10 @@ public: }(); rg::sort(accountRoots); - std::vector cursors{data::firstKey}; + std::vector cursors{data::kFIRST_KEY}; rg::copy(accountRoots.begin(), accountRoots.end(), std::back_inserter(cursors)); rg::sort(cursors); - cursors.push_back(data::lastKey); + cursors.push_back(data::kLAST_KEY); std::vector pairs; pairs.reserve(cursors.size()); diff --git a/src/etl/impl/CursorFromDiffProvider.hpp b/src/etl/impl/CursorFromDiffProvider.hpp index 6b90dd15..e5f091c1 100644 --- a/src/etl/impl/CursorFromDiffProvider.hpp +++ b/src/etl/impl/CursorFromDiffProvider.hpp @@ -85,10 +85,10 @@ public: ); } - std::vector cursors{data::firstKey}; + std::vector cursors{data::kFIRST_KEY}; rg::copy(liveCursors | vs::take(std::min(liveCursors.size(), numCursors_)), std::back_inserter(cursors)); rg::sort(cursors); - cursors.push_back(data::lastKey); + cursors.push_back(data::kLAST_KEY); std::vector pairs; pairs.reserve(cursors.size()); diff --git a/src/etl/impl/CursorFromFixDiffNumProvider.hpp b/src/etl/impl/CursorFromFixDiffNumProvider.hpp index e7924620..5daac00b 100644 --- a/src/etl/impl/CursorFromFixDiffNumProvider.hpp +++ b/src/etl/impl/CursorFromFixDiffNumProvider.hpp @@ -74,14 +74,14 @@ public: rg::unique(diffs, [](auto const& a, auto const& b) { return a.key == b.key; }); diffs.erase(removalCursor, last); - std::vector cursors{data::firstKey}; + std::vector cursors{data::kFIRST_KEY}; 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::lastKey); // last pair should cover the remaining range + cursors.push_back(data::kLAST_KEY); // last pair should cover the remaining range std::vector pairs; pairs.reserve(cursors.size()); diff --git a/src/etl/impl/ExtractionDataPipe.hpp b/src/etl/impl/ExtractionDataPipe.hpp index fcb1a5f7..1a504448 100644 --- a/src/etl/impl/ExtractionDataPipe.hpp +++ b/src/etl/impl/ExtractionDataPipe.hpp @@ -39,7 +39,7 @@ public: using DataType = std::optional; using QueueType = ThreadSafeQueue; // TODO: probably should use boost::lockfree::queue instead? - constexpr static auto TOTAL_MAX_IN_QUEUE = 1000u; + static constexpr auto kTOTAL_MAX_IN_QUEUE = 1000u; private: util::Logger log_{"ETL"}; @@ -58,7 +58,7 @@ public: */ ExtractionDataPipe(uint32_t stride, uint32_t startSequence) : stride_{stride}, startSequence_{startSequence} { - auto const maxQueueSize = TOTAL_MAX_IN_QUEUE / stride; + auto const maxQueueSize = kTOTAL_MAX_IN_QUEUE / stride; for (size_t i = 0; i < stride_; ++i) queues_.push_back(std::make_unique(maxQueueSize)); } diff --git a/src/etl/impl/ForwardingSource.cpp b/src/etl/impl/ForwardingSource.cpp index ebda3a15..6ca658e8 100644 --- a/src/etl/impl/ForwardingSource.cpp +++ b/src/etl/impl/ForwardingSource.cpp @@ -44,13 +44,13 @@ ForwardingSource::ForwardingSource( std::string ip, std::string wsPort, std::chrono::steady_clock::duration forwardingTimeout, - std::chrono::steady_clock::duration connectionTimeout + std::chrono::steady_clock::duration connTimeout ) : log_(fmt::format("ForwardingSource[{}:{}]", ip, wsPort)) , connectionBuilder_(std::move(ip), std::move(wsPort)) , forwardingTimeout_{forwardingTimeout} { - connectionBuilder_.setConnectionTimeout(connectionTimeout) + connectionBuilder_.setConnectionTimeout(connTimeout) .addHeader( {boost::beast::http::field::user_agent, fmt::format("{} websocket-client-coro", BOOST_BEAST_VERSION_STRING)} ); @@ -76,14 +76,14 @@ ForwardingSource::forwardToRippled( auto expectedConnection = connectionBuilder.connect(yield); if (not expectedConnection) { LOG(log_.debug()) << "Couldn't connect to rippled to forward request."; - return std::unexpected{rpc::ClioError::etlCONNECTION_ERROR}; + return std::unexpected{rpc::ClioError::EtlConnectionError}; } auto& connection = expectedConnection.value(); auto writeError = connection->write(boost::json::serialize(request), yield, forwardingTimeout_); if (writeError) { LOG(log_.debug()) << "Error sending request to rippled to forward request."; - return std::unexpected{rpc::ClioError::etlREQUEST_ERROR}; + return std::unexpected{rpc::ClioError::EtlRequestError}; } auto response = connection->read(yield, forwardingTimeout_); @@ -91,10 +91,10 @@ ForwardingSource::forwardToRippled( if (auto errorCode = response.error().errorCode(); errorCode.has_value() and errorCode->value() == boost::system::errc::timed_out) { LOG(log_.debug()) << "Request to rippled timed out"; - return std::unexpected{rpc::ClioError::etlREQUEST_TIMEOUT}; + return std::unexpected{rpc::ClioError::EtlRequestTimeout}; } LOG(log_.debug()) << "Error sending request to rippled to forward request."; - return std::unexpected{rpc::ClioError::etlREQUEST_ERROR}; + return std::unexpected{rpc::ClioError::EtlRequestError}; } boost::json::value parsedResponse; @@ -104,7 +104,7 @@ ForwardingSource::forwardToRippled( throw std::runtime_error("response is not an object"); } catch (std::exception const& e) { LOG(log_.debug()) << "Error parsing response from rippled: " << e.what() << ". Response: " << *response; - return std::unexpected{rpc::ClioError::etlINVALID_RESPONSE}; + return std::unexpected{rpc::ClioError::EtlInvalidResponse}; } auto responseObject = parsedResponse.as_object(); diff --git a/src/etl/impl/ForwardingSource.hpp b/src/etl/impl/ForwardingSource.hpp index efdb425f..17bfb296 100644 --- a/src/etl/impl/ForwardingSource.hpp +++ b/src/etl/impl/ForwardingSource.hpp @@ -39,14 +39,14 @@ class ForwardingSource { util::requests::WsConnectionBuilder connectionBuilder_; std::chrono::steady_clock::duration forwardingTimeout_; - static constexpr std::chrono::seconds CONNECTION_TIMEOUT{3}; + static constexpr std::chrono::seconds kCONNECTION_TIMEOUT{3}; public: ForwardingSource( std::string ip, std::string wsPort, std::chrono::steady_clock::duration forwardingTimeout, - std::chrono::steady_clock::duration connectionTimeout = CONNECTION_TIMEOUT + std::chrono::steady_clock::duration connTimeout = ForwardingSource::kCONNECTION_TIMEOUT ); /** diff --git a/src/etl/impl/LedgerLoader.hpp b/src/etl/impl/LedgerLoader.hpp index 8f070ca4..753b211b 100644 --- a/src/etl/impl/LedgerLoader.hpp +++ b/src/etl/impl/LedgerLoader.hpp @@ -131,8 +131,8 @@ public: result.mptHoldersData.push_back(*maybeMPTHolder); result.accountTxData.emplace_back(txMeta, sttx.getTransactionID()); - static constexpr std::size_t KEY_SIZE = 32; - std::string keyStr{reinterpret_cast(sttx.getTransactionID().data()), KEY_SIZE}; + static constexpr std::size_t kEY_SIZE = 32; + std::string keyStr{reinterpret_cast(sttx.getTransactionID().data()), kEY_SIZE}; backend_->writeTransaction( std::move(keyStr), ledger.seq, @@ -204,10 +204,10 @@ public: backend_->writeSuccessor(std::move(key), sequence, uint256ToString(succ->key)); } - ripple::uint256 prev = data::firstKey; + ripple::uint256 prev = data::kFIRST_KEY; while (auto cur = backend_->cache().getSuccessor(prev, sequence)) { ASSERT(cur.has_value(), "Succesor for key {} must exist", ripple::strHex(prev)); - if (prev == data::firstKey) + if (prev == data::kFIRST_KEY) backend_->writeSuccessor(uint256ToString(prev), sequence, uint256ToString(cur->key)); if (isBookDir(cur->key, cur->blob)) { @@ -228,12 +228,12 @@ public: } prev = cur->key; - static constexpr std::size_t LOG_INTERVAL = 100000; - if (numWrites % LOG_INTERVAL == 0 && numWrites != 0) + static constexpr std::size_t kLOG_INTERVAL = 100000; + if (numWrites % kLOG_INTERVAL == 0 && numWrites != 0) LOG(log_.info()) << "Wrote " << numWrites << " book successors"; } - backend_->writeSuccessor(uint256ToString(prev), sequence, uint256ToString(data::lastKey)); + backend_->writeSuccessor(uint256ToString(prev), sequence, uint256ToString(data::kLAST_KEY)); ++numWrites; }); diff --git a/src/etl/impl/LedgerPublisher.hpp b/src/etl/impl/LedgerPublisher.hpp index 9b75df6b..0539151d 100644 --- a/src/etl/impl/LedgerPublisher.hpp +++ b/src/etl/impl/LedgerPublisher.hpp @@ -184,8 +184,8 @@ public: // if the ledger closed over MAX_LEDGER_AGE_SECONDS ago, assume we are still catching up and don't publish // TODO: this probably should be a strategy - static constexpr std::uint32_t MAX_LEDGER_AGE_SECONDS = 600; - if (age < MAX_LEDGER_AGE_SECONDS) { + static constexpr std::uint32_t kMAX_LEDGER_AGE_SECONDS = 600; + if (age < kMAX_LEDGER_AGE_SECONDS) { std::optional fees = data::synchronousAndRetryOnTimeout([&](auto yield) { return backend_->fetchFees(lgrInfo.seq, yield); }); @@ -260,9 +260,9 @@ public: auto now = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()) .count(); auto closeTime = lastCloseTime_.time_since_epoch().count(); - if (now < (rippleEpochStart + closeTime)) + if (now < (kRIPPLE_EPOCH_START + closeTime)) return 0; - return now - (rippleEpochStart + closeTime); + return now - (kRIPPLE_EPOCH_START + closeTime); } /** diff --git a/src/etl/impl/SubscriptionSource.cpp b/src/etl/impl/SubscriptionSource.cpp index 3d177e51..1684cd23 100644 --- a/src/etl/impl/SubscriptionSource.cpp +++ b/src/etl/impl/SubscriptionSource.cpp @@ -77,7 +77,7 @@ SubscriptionSource::SubscriptionSource( , subscriptions_(std::move(subscriptions)) , strand_(boost::asio::make_strand(ioContext)) , wsTimeout_(wsTimeout) - , retry_(util::makeRetryExponentialBackoff(retryDelay, RETRY_MAX_DELAY, strand_)) + , retry_(util::makeRetryExponentialBackoff(retryDelay, kRETRY_MAX_DELAY, strand_)) , onConnect_(std::move(onConnect)) , onDisconnect_(std::move(onDisconnect)) , onLedgerClosed_(std::move(onLedgerClosed)) @@ -222,9 +222,9 @@ SubscriptionSource::handleMessage(std::string const& message) auto const object = raw.as_object(); uint32_t ledgerIndex = 0; - static constexpr char const* const JS_LedgerClosed = "ledgerClosed"; - static constexpr char const* const JS_ValidationReceived = "validationReceived"; - static constexpr char const* const JS_ManifestReceived = "manifestReceived"; + static constexpr auto kJS_LEDGER_CLOSED = "ledgerClosed"; + static constexpr auto kJS_VALIDATION_RECEIVED = "validationReceived"; + static constexpr auto kJS_MANIFEST_RECEIVED = "manifestReceived"; if (object.contains(JS(result))) { auto const& result = object.at(JS(result)).as_object(); @@ -237,7 +237,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)) == JS_LedgerClosed) { + } else if (object.contains(JS(type)) && object.at(JS(type)) == kJS_LEDGER_CLOSED) { LOG(log_.debug()) << "Received a message of type 'ledgerClosed' on ledger subscription stream. Message: " << object; if (object.contains(JS(ledger_index))) { @@ -259,10 +259,10 @@ SubscriptionSource::handleMessage(std::string const& message) if (object.contains(JS(transaction)) and !object.contains(JS(meta))) { LOG(log_.debug()) << "Forwarding proposed transaction: " << object; subscriptions_->forwardProposedTransaction(object); - } else if (object.contains(JS(type)) && object.at(JS(type)) == JS_ValidationReceived) { + } else if (object.contains(JS(type)) && object.at(JS(type)) == kJS_VALIDATION_RECEIVED) { LOG(log_.debug()) << "Forwarding validation: " << object; subscriptions_->forwardValidation(object); - } else if (object.contains(JS(type)) && object.at(JS(type)) == JS_ManifestReceived) { + } else if (object.contains(JS(type)) && object.at(JS(type)) == kJS_MANIFEST_RECEIVED) { LOG(log_.debug()) << "Forwarding manifest: " << object; subscriptions_->forwardManifest(object); } @@ -363,12 +363,12 @@ SubscriptionSource::setValidatedRange(std::string range) std::string const& SubscriptionSource::getSubscribeCommandJson() { - static boost::json::object const jsonValue{ + static boost::json::object const kJSON_VALUE{ {"command", "subscribe"}, {"streams", {"ledger", "manifests", "validations", "transactions_proposed"}}, }; - static std::string const jsonString = boost::json::serialize(jsonValue); - return jsonString; + static std::string const kJSON_STRING = boost::json::serialize(kJSON_VALUE); + return kJSON_STRING; } } // namespace etl::impl diff --git a/src/etl/impl/SubscriptionSource.hpp b/src/etl/impl/SubscriptionSource.hpp index 83b69d82..77bdf4b0 100644 --- a/src/etl/impl/SubscriptionSource.hpp +++ b/src/etl/impl/SubscriptionSource.hpp @@ -91,9 +91,9 @@ private: std::future runFuture_; - static constexpr std::chrono::seconds WS_TIMEOUT{30}; - static constexpr std::chrono::seconds RETRY_MAX_DELAY{30}; - static constexpr std::chrono::seconds RETRY_DELAY{1}; + 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}; public: /** @@ -107,8 +107,7 @@ public: * @param subscriptions The subscription manager object * @param onConnect The onConnect hook. Called when the connection is established * @param onDisconnect The onDisconnect hook. Called when the connection is lost - * @param onLedgerClosed The onLedgerClosed hook. Called when the ledger is closed but only if the source is - * forwarding + * @param onLedgerClosed The onLedgerClosed hook. Called when the ledger is closed if the source is forwarding * @param wsTimeout A timeout for websocket operations. Defaults to 30 seconds * @param retryDelay The retry delay. Defaults to 1 second */ @@ -121,8 +120,8 @@ public: OnConnectHook onConnect, OnDisconnectHook onDisconnect, OnLedgerClosedHook onLedgerClosed, - std::chrono::steady_clock::duration const wsTimeout = WS_TIMEOUT, - std::chrono::steady_clock::duration const retryDelay = RETRY_DELAY + std::chrono::steady_clock::duration const wsTimeout = SubscriptionSource::kWS_TIMEOUT, + std::chrono::steady_clock::duration const retryDelay = SubscriptionSource::kRETRY_DELAY ); /** diff --git a/src/etl/impl/Transformer.hpp b/src/etl/impl/Transformer.hpp index a9c31cad..834c3130 100644 --- a/src/etl/impl/Transformer.hpp +++ b/src/etl/impl/Transformer.hpp @@ -308,11 +308,11 @@ private: auto lb = backend_->cache().getPredecessor(obj.key, lgrInfo.seq); if (!lb) - lb = {.key = data::firstKey, .blob = {}}; + lb = {.key = data::kFIRST_KEY, .blob = {}}; auto ub = backend_->cache().getSuccessor(obj.key, lgrInfo.seq); if (!ub) - ub = {.key = data::lastKey, .blob = {}}; + ub = {.key = data::kLAST_KEY, .blob = {}}; if (obj.blob.empty()) { LOG(log_.debug()) << "writing successor for deleted object " << ripple::strHex(obj.key) << " - " @@ -336,10 +336,10 @@ private: LOG(log_.debug()) << "Updating book successor " << ripple::strHex(base) << " - " << ripple::strHex(succ->key); } else { - backend_->writeSuccessor(uint256ToString(base), lgrInfo.seq, uint256ToString(data::lastKey)); + backend_->writeSuccessor(uint256ToString(base), lgrInfo.seq, uint256ToString(data::kLAST_KEY)); LOG(log_.debug()) << "Updating book successor " << ripple::strHex(base) << " - " - << ripple::strHex(data::lastKey); + << ripple::strHex(data::kLAST_KEY); } } } @@ -361,7 +361,7 @@ private: for (auto& obj : *(rawData.mutable_book_successors())) { auto firstBook = std::move(*obj.mutable_first_book()); if (!firstBook.size()) - firstBook = uint256ToString(data::lastKey); + firstBook = uint256ToString(data::kLAST_KEY); LOG(log_.debug()) << "writing book successor " << ripple::strHex(obj.book_base()) << " - " << ripple::strHex(firstBook); @@ -372,10 +372,10 @@ private: if (obj.mod_type() != RawLedgerObjectType::MODIFIED) { std::string* predPtr = obj.mutable_predecessor(); if (predPtr->empty()) - *predPtr = uint256ToString(data::firstKey); + *predPtr = uint256ToString(data::kFIRST_KEY); std::string* succPtr = obj.mutable_successor(); if (succPtr->empty()) - *succPtr = uint256ToString(data::lastKey); + *succPtr = uint256ToString(data::kLAST_KEY); if (obj.mod_type() == RawLedgerObjectType::DELETED) { LOG(log_.debug()) << "Modifying successors for deleted object " << ripple::strHex(obj.key()) diff --git a/src/etlng/Models.hpp b/src/etlng/Models.hpp index 1b7597e5..4e8aa682 100644 --- a/src/etlng/Models.hpp +++ b/src/etlng/Models.hpp @@ -49,7 +49,7 @@ namespace etlng::model { template requires(util::hasNoDuplicates(Types...)) struct Spec { - static constexpr bool SpecTag = true; + static constexpr bool kSPEC_TAG = true; /** * @brief Checks if the transaction type was requested. @@ -57,7 +57,7 @@ struct Spec { * @param type The transaction type * @return true if the transaction was requested; false otherwise */ - [[nodiscard]] constexpr static bool + [[nodiscard]] static constexpr bool wants(ripple::TxType type) noexcept { return ((Types == type) || ...); diff --git a/src/etlng/impl/Extraction.cpp b/src/etlng/impl/Extraction.cpp index 425053b0..6f9a372a 100644 --- a/src/etlng/impl/Extraction.cpp +++ b/src/etlng/impl/Extraction.cpp @@ -118,8 +118,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::firstKey)), - .predecessor = valueOr(obj.predecessor(), uint256ToString(data::lastKey)), + .successor = valueOr(obj.successor(), uint256ToString(data::kFIRST_KEY)), + .predecessor = valueOr(obj.predecessor(), uint256ToString(data::kLAST_KEY)), .type = extractModType(obj.mod_type()), }; } diff --git a/src/etlng/impl/Registry.hpp b/src/etlng/impl/Registry.hpp index 9e720b68..d5d26238 100644 --- a/src/etlng/impl/Registry.hpp +++ b/src/etlng/impl/Registry.hpp @@ -72,7 +72,7 @@ concept HasInitialObjectHook = requires(T p) { }; template -concept ContainsSpec = std::decay_t::spec::SpecTag; +concept ContainsSpec = std::decay_t::spec::kSPEC_TAG; template concept ContainsValidHook = HasLedgerDataHook or HasInitialDataHook or diff --git a/src/feed/SubscriptionManager.hpp b/src/feed/SubscriptionManager.hpp index e07fa34a..096b7fb2 100644 --- a/src/feed/SubscriptionManager.hpp +++ b/src/feed/SubscriptionManager.hpp @@ -77,7 +77,7 @@ public: * @return A shared pointer to a new instance of SubscriptionManager */ static std::shared_ptr - make_SubscriptionManager( + makeSubscriptionManager( util::config::ClioConfigDefinition const& config, std::shared_ptr const& backend ) diff --git a/src/main/Main.cpp b/src/main/Main.cpp index f328ef49..6a817f0d 100644 --- a/src/main/Main.cpp +++ b/src/main/Main.cpp @@ -41,35 +41,35 @@ try { return action.apply( [](app::CliArgs::Action::Exit const& exit) { return exit.exitCode; }, [](app::CliArgs::Action::Run const& run) { - auto const json = ConfigFileJson::make_ConfigFileJson(run.configPath); + auto const json = ConfigFileJson::makeConfigFileJson(run.configPath); if (!json.has_value()) { std::cerr << json.error().error << std::endl; return EXIT_FAILURE; } - auto const errors = ClioConfig.parse(json.value()); + auto const errors = gClioConfig.parse(json.value()); if (errors.has_value()) { for (auto const& err : errors.value()) std::cerr << err.error << std::endl; return EXIT_FAILURE; } - util::LogService::init(ClioConfig); - app::ClioApplication clio{ClioConfig}; + util::LogService::init(gClioConfig); + app::ClioApplication clio{gClioConfig}; return clio.run(run.useNgWebServer); }, [](app::CliArgs::Action::Migrate const& migrate) { - auto const json = ConfigFileJson::make_ConfigFileJson(migrate.configPath); + auto const json = ConfigFileJson::makeConfigFileJson(migrate.configPath); if (!json.has_value()) { std::cerr << json.error().error << std::endl; return EXIT_FAILURE; } - auto const errors = ClioConfig.parse(json.value()); + auto const errors = gClioConfig.parse(json.value()); if (errors.has_value()) { for (auto const& err : errors.value()) std::cerr << err.error << std::endl; return EXIT_FAILURE; } - util::LogService::init(ClioConfig); - app::MigratorApplication migrator{ClioConfig, migrate.subCmd}; + util::LogService::init(gClioConfig); + app::MigratorApplication migrator{gClioConfig, migrate.subCmd}; return migrator.run(); } ); diff --git a/src/migration/MigratiorStatus.hpp b/src/migration/MigratiorStatus.hpp index 4c1a9ba2..c01b0fab 100644 --- a/src/migration/MigratiorStatus.hpp +++ b/src/migration/MigratiorStatus.hpp @@ -79,7 +79,7 @@ public: fromString(std::string const& statusStr); private: - static constexpr std::array(NumStatuses)> statusStrMap = { + static constexpr std::array(NumStatuses)> kSTATUS_STR_MAP = { "Migrated", "NotMigrated", "NotKnown" diff --git a/src/migration/MigratorStatus.cpp b/src/migration/MigratorStatus.cpp index 03379c53..75c66df9 100644 --- a/src/migration/MigratorStatus.cpp +++ b/src/migration/MigratorStatus.cpp @@ -39,14 +39,14 @@ MigratorStatus::operator==(Status const& other) const std::string MigratorStatus::toString() const { - return statusStrMap[static_cast(status_)]; + return kSTATUS_STR_MAP[static_cast(status_)]; } MigratorStatus MigratorStatus::fromString(std::string const& statusStr) { - for (std::size_t i = 0; i < statusStrMap.size(); ++i) { - if (statusStr == statusStrMap[i]) { + for (std::size_t i = 0; i < kSTATUS_STR_MAP.size(); ++i) { + if (statusStr == kSTATUS_STR_MAP[i]) { return MigratorStatus(static_cast(i)); } } diff --git a/src/migration/cassandra/CassandraMigrationBackend.hpp b/src/migration/cassandra/CassandraMigrationBackend.hpp index 1735a920..f967d2f3 100644 --- a/src/migration/cassandra/CassandraMigrationBackend.hpp +++ b/src/migration/cassandra/CassandraMigrationBackend.hpp @@ -76,23 +76,23 @@ public: ) { LOG(log_.debug()) << "Travsering token range: " << start << " - " << end - << " ; table: " << TableDesc::TABLE_NAME; + << " ; table: " << TableDesc::kTABLE_NAME; // for each table we only have one prepared statement - static auto statementPrepared = - migrationSchema_.getPreparedFullScanStatement(handle_, TableDesc::TABLE_NAME, TableDesc::PARTITION_KEY); + static auto kSTATEMENT_PREPARED = + migrationSchema_.getPreparedFullScanStatement(handle_, TableDesc::kTABLE_NAME, TableDesc::kPARTITION_KEY); - auto const statement = statementPrepared.bind(start, end); + auto const statement = kSTATEMENT_PREPARED.bind(start, end); auto const res = this->executor_.read(yield, statement); if (not res) { - LOG(log_.error()) << "Could not fetch data from table: " << TableDesc::TABLE_NAME << " range: " << start + LOG(log_.error()) << "Could not fetch data from table: " << TableDesc::kTABLE_NAME << " range: " << start << " - " << end << ";" << res.error(); return; } auto const& results = res.value(); if (not results.hasRows()) { - LOG(log_.debug()) << "No rows returned - table: " << TableDesc::TABLE_NAME << " range: " << start << " - " + LOG(log_.debug()) << "No rows returned - table: " << TableDesc::kTABLE_NAME << " range: " << start << " - " << end; return; } diff --git a/src/migration/cassandra/impl/CassandraMigrationSchema.hpp b/src/migration/cassandra/impl/CassandraMigrationSchema.hpp index 22c4fedf..d998a663 100644 --- a/src/migration/cassandra/impl/CassandraMigrationSchema.hpp +++ b/src/migration/cassandra/impl/CassandraMigrationSchema.hpp @@ -84,7 +84,7 @@ public: data::cassandra::PreparedStatement const& getPreparedInsertMigratedMigrator(data::cassandra::Handle const& handler) { - static auto prepared = handler.prepare(fmt::format( + static auto kPREPARED = handler.prepare(fmt::format( R"( INSERT INTO {} (migrator_name, status) @@ -92,7 +92,7 @@ public: )", data::cassandra::qualifiedTableName(settingsProvider_.get(), "migrator_status") )); - return prepared; + return kPREPARED; } }; } // namespace migration::cassandra::impl diff --git a/src/migration/cassandra/impl/FullTableScanner.hpp b/src/migration/cassandra/impl/FullTableScanner.hpp index dae94e70..34261893 100644 --- a/src/migration/cassandra/impl/FullTableScanner.hpp +++ b/src/migration/cassandra/impl/FullTableScanner.hpp @@ -74,9 +74,9 @@ class FullTableScanner { * @brief The helper to generate the token ranges. */ struct TokenRangesProvider { - uint32_t numRanges_; + uint32_t numRanges; - TokenRangesProvider(uint32_t numRanges) : numRanges_{numRanges} + TokenRangesProvider(uint32_t numRanges) : numRanges{numRanges} { } @@ -85,18 +85,18 @@ class FullTableScanner { { auto const minValue = std::numeric_limits::min(); auto const maxValue = std::numeric_limits::max(); - if (numRanges_ == 1) + if (numRanges == 1) return {TokenRange{minValue, maxValue}}; // Safely calculate the range size using uint64_t to avoid overflow - uint64_t const rangeSize = (static_cast(maxValue) * 2) / numRanges_; + uint64_t const rangeSize = (static_cast(maxValue) * 2) / numRanges; std::vector ranges; - ranges.reserve(numRanges_); + ranges.reserve(numRanges); - for (std::int64_t i = 0; i < numRanges_; ++i) { + for (std::int64_t i = 0; i < numRanges; ++i) { int64_t const start = minValue + (i * rangeSize); - int64_t const end = (i == numRanges_ - 1) ? maxValue : start + static_cast(rangeSize) - 1; + int64_t const end = (i == numRanges - 1) ? maxValue : start + static_cast(rangeSize) - 1; ranges.emplace_back(start, end); } diff --git a/src/migration/cassandra/impl/ObjectsAdapter.hpp b/src/migration/cassandra/impl/ObjectsAdapter.hpp index 98bb932a..91463e3b 100644 --- a/src/migration/cassandra/impl/ObjectsAdapter.hpp +++ b/src/migration/cassandra/impl/ObjectsAdapter.hpp @@ -42,8 +42,8 @@ namespace migration::cassandra::impl { */ struct TableObjectsDesc { using Row = std::tuple; - static constexpr char const* PARTITION_KEY = "key"; - static constexpr char const* TABLE_NAME = "objects"; + static constexpr char const* kPARTITION_KEY = "key"; + static constexpr char const* kTABLE_NAME = "objects"; }; /** diff --git a/src/migration/cassandra/impl/Spec.hpp b/src/migration/cassandra/impl/Spec.hpp index 2e21f42a..c7195663 100644 --- a/src/migration/cassandra/impl/Spec.hpp +++ b/src/migration/cassandra/impl/Spec.hpp @@ -35,7 +35,7 @@ concept TableSpec = requires { requires std::tuple_size::value >= 0; // Ensures 'row' is a tuple // Check that static constexpr members 'partitionKey' and 'tableName' exist - { T::PARTITION_KEY } -> std::convertible_to; - { T::TABLE_NAME } -> std::convertible_to; + { T::kPARTITION_KEY } -> std::convertible_to; + { T::kTABLE_NAME } -> std::convertible_to; }; } // namespace migration::cassandra::impl diff --git a/src/migration/cassandra/impl/TransactionsAdapter.hpp b/src/migration/cassandra/impl/TransactionsAdapter.hpp index a5003944..6bb27ee8 100644 --- a/src/migration/cassandra/impl/TransactionsAdapter.hpp +++ b/src/migration/cassandra/impl/TransactionsAdapter.hpp @@ -42,8 +42,8 @@ namespace migration::cassandra::impl { struct TableTransactionsDesc { // hash, date, ledger_seq, metadata, transaction using Row = std::tuple; - static constexpr char const* PARTITION_KEY = "hash"; - static constexpr char const* TABLE_NAME = "transactions"; + static constexpr char const* kPARTITION_KEY = "hash"; + static constexpr char const* kTABLE_NAME = "transactions"; }; /** diff --git a/src/migration/impl/MigrationManagerFactory.cpp b/src/migration/impl/MigrationManagerFactory.cpp index 2ed70559..af4c550f 100644 --- a/src/migration/impl/MigrationManagerFactory.cpp +++ b/src/migration/impl/MigrationManagerFactory.cpp @@ -37,7 +37,7 @@ namespace migration::impl { std::expected, std::string> makeMigrationManager(util::config::ClioConfigDefinition const& config) { - static util::Logger const log{"Migration"}; + static util::Logger const log{"Migration"}; // NOLINT(readability-identifier-naming) LOG(log.info()) << "Constructing MigrationManager"; auto const type = config.get("database.type"); diff --git a/src/migration/impl/MigratorsRegister.hpp b/src/migration/impl/MigratorsRegister.hpp index f361bcd0..e01c6e0e 100644 --- a/src/migration/impl/MigratorsRegister.hpp +++ b/src/migration/impl/MigratorsRegister.hpp @@ -66,7 +66,7 @@ class MigratorsRegister { void callMigration(std::string const& name, util::config::ObjectView const& config) { - if (name == Migrator::name) { + if (name == Migrator::kNAME) { LOG(log_.info()) << "Running migration: " << name; Migrator::runMigration(backend_, config); backend_->writeMigratorStatus(name, MigratorStatus(MigratorStatus::Migrated).toString()); @@ -78,7 +78,7 @@ class MigratorsRegister { static constexpr std::string_view getDescriptionIfMatch(std::string_view targetName) { - return (T::name == targetName) ? T::description : ""; + return (T::kNAME == targetName) ? T::kDESCRIPTION : ""; } public: @@ -156,7 +156,7 @@ public: constexpr auto getMigratorNames() const { - return std::array{MigratorType::name...}; + return std::array{MigratorType::kNAME...}; } /** diff --git a/src/migration/impl/Spec.hpp b/src/migration/impl/Spec.hpp index 92d5e8c8..5d6c15f7 100644 --- a/src/migration/impl/Spec.hpp +++ b/src/migration/impl/Spec.hpp @@ -34,11 +34,11 @@ namespace migration::impl { */ template concept MigratorSpec = requires(std::shared_ptr const& backend, util::config::ObjectView const& cfg) { - // Check that 'name' exists and is a string - { T::name } -> std::convertible_to; + // Check that 'kNAME' exists and is a string + { T::kNAME } -> std::convertible_to; - // Check that 'description' exists and is a string - { T::description } -> std::convertible_to; + // Check that 'kDESCRIPTION' exists and is a string + { T::kDESCRIPTION } -> std::convertible_to; // Check that the migrator specifies the backend type it supports typename T::Backend; diff --git a/src/rpc/Counters.hpp b/src/rpc/Counters.hpp index ddc8d169..962c89b7 100644 --- a/src/rpc/Counters.hpp +++ b/src/rpc/Counters.hpp @@ -84,7 +84,7 @@ public: * @return The new instance */ static Counters - make_Counters(WorkQueue const& wq) + makeCounters(WorkQueue const& wq) { return Counters{wq}; } diff --git a/src/rpc/Errors.cpp b/src/rpc/Errors.cpp index f7585903..16e91ae8 100644 --- a/src/rpc/Errors.cpp +++ b/src/rpc/Errors.cpp @@ -42,20 +42,20 @@ namespace rpc { WarningInfo const& getWarningInfo(WarningCode code) { - constexpr static WarningInfo infos[]{ - {warnUNKNOWN, "Unknown warning"}, - {warnRPC_CLIO, + static constexpr WarningInfo kINFOS[]{ + {WarnUnknown, "Unknown warning"}, + {WarnRpcClio, "This is a clio server. clio only serves validated data. If you want to talk to rippled, include " "'ledger_index':'current' in your request"}, - {warnRPC_OUTDATED, "This server may be out of date"}, - {warnRPC_RATE_LIMIT, "You are about to be rate limited"}, - {warnRPC_DEPRECATED, + {WarnRpcOutdated, "This server may be out of date"}, + {WarnRpcRateLimit, "You are about to be rate limited"}, + {WarnRpcDeprecated, "Some fields from your request are deprecated. Please check the documentation at " "https://xrpl.org/docs/references/http-websocket-apis/ and update your request."} }; auto matchByCode = [code](auto const& info) { return info.code == code; }; - if (auto it = std::ranges::find_if(infos, matchByCode); it != end(infos)) + if (auto it = ranges::find_if(kINFOS, matchByCode); it != end(kINFOS)) return *it; throw(out_of_range("Invalid WarningCode")); @@ -74,44 +74,43 @@ makeWarning(WarningCode code) ClioErrorInfo const& getErrorInfo(ClioError code) { - constexpr static ClioErrorInfo infos[]{ - {.code = ClioError::rpcMALFORMED_CURRENCY, .error = "malformedCurrency", .message = "Malformed currency."}, - {.code = ClioError::rpcMALFORMED_REQUEST, .error = "malformedRequest", .message = "Malformed request."}, - {.code = ClioError::rpcMALFORMED_OWNER, .error = "malformedOwner", .message = "Malformed owner."}, - {.code = ClioError::rpcMALFORMED_ADDRESS, .error = "malformedAddress", .message = "Malformed address."}, - {.code = ClioError::rpcINVALID_HOT_WALLET, .error = "invalidHotWallet", .message = "Invalid hot wallet."}, - {.code = ClioError::rpcUNKNOWN_OPTION, .error = "unknownOption", .message = "Unknown option."}, - {.code = ClioError::rpcFIELD_NOT_FOUND_TRANSACTION, + constexpr static ClioErrorInfo kINFOS[]{ + {.code = ClioError::RpcMalformedCurrency, .error = "malformedCurrency", .message = "Malformed currency."}, + {.code = ClioError::RpcMalformedRequest, .error = "malformedRequest", .message = "Malformed request."}, + {.code = ClioError::RpcMalformedOwner, .error = "malformedOwner", .message = "Malformed owner."}, + {.code = ClioError::RpcMalformedAddress, .error = "malformedAddress", .message = "Malformed address."}, + {.code = ClioError::RpcInvalidHotWallet, .error = "invalidHotWallet", .message = "Invalid hot wallet."}, + {.code = ClioError::RpcUnknownOption, .error = "unknownOption", .message = "Unknown option."}, + {.code = ClioError::RpcFieldNotFoundTransaction, .error = "fieldNotFoundTransaction", .message = "Missing field."}, - {.code = ClioError::rpcMALFORMED_ORACLE_DOCUMENT_ID, + {.code = ClioError::RpcMalformedOracleDocumentId, .error = "malformedDocumentID", .message = "Malformed oracle_document_id."}, - {.code = ClioError::rpcMALFORMED_AUTHORIZED_CREDENTIALS, + {.code = ClioError::RpcMalformedAuthorizedCredentials, .error = "malformedAuthorizedCredentials", .message = "Malformed authorized credentials."}, // special system errors - {.code = ClioError::rpcINVALID_API_VERSION, .error = JS(invalid_API_version), .message = "Invalid API version." - }, - {.code = ClioError::rpcCOMMAND_IS_MISSING, + {.code = ClioError::RpcInvalidApiVersion, .error = JS(invalid_API_version), .message = "Invalid API version."}, + {.code = ClioError::RpcCommandIsMissing, .error = JS(missingCommand), .message = "Method is not specified or is not a string."}, - {.code = ClioError::rpcCOMMAND_NOT_STRING, .error = "commandNotString", .message = "Method is not a string."}, - {.code = ClioError::rpcCOMMAND_IS_EMPTY, .error = "emptyCommand", .message = "Method is an empty string."}, - {.code = ClioError::rpcPARAMS_UNPARSEABLE, + {.code = ClioError::RpcCommandNotString, .error = "commandNotString", .message = "Method is not a string."}, + {.code = ClioError::RpcCommandIsEmpty, .error = "emptyCommand", .message = "Method is an empty string."}, + {.code = ClioError::RpcParamsUnparseable, .error = "paramsUnparseable", .message = "Params must be an array holding exactly one object."}, // etl related errors - {.code = ClioError::etlCONNECTION_ERROR, .error = "connectionError", .message = "Couldn't connect to rippled."}, - {.code = ClioError::etlREQUEST_ERROR, .error = "requestError", .message = "Error sending request to rippled."}, - {.code = ClioError::etlREQUEST_TIMEOUT, .error = "timeout", .message = "Request to rippled timed out."}, - {.code = ClioError::etlINVALID_RESPONSE, + {.code = ClioError::EtlConnectionError, .error = "connectionError", .message = "Couldn't connect to rippled."}, + {.code = ClioError::EtlRequestError, .error = "requestError", .message = "Error sending request to rippled."}, + {.code = ClioError::EtlRequestTimeout, .error = "timeout", .message = "Request to rippled timed out."}, + {.code = ClioError::EtlInvalidResponse, .error = "invalidResponse", .message = "Rippled returned an invalid response."} }; auto matchByCode = [code](auto const& info) { return info.code == code; }; - if (auto it = std::ranges::find_if(infos, matchByCode); it != end(infos)) + if (auto it = ranges::find_if(kINFOS, matchByCode); it != end(kINFOS)) return *it; throw(out_of_range("Invalid error code")); diff --git a/src/rpc/Errors.hpp b/src/rpc/Errors.hpp index e177b630..8322cacf 100644 --- a/src/rpc/Errors.hpp +++ b/src/rpc/Errors.hpp @@ -35,30 +35,30 @@ namespace rpc { /** @brief Custom clio RPC Errors. */ enum class ClioError { // normal clio errors start with 5000 - rpcMALFORMED_CURRENCY = 5000, - rpcMALFORMED_REQUEST = 5001, - rpcMALFORMED_OWNER = 5002, - rpcMALFORMED_ADDRESS = 5003, - rpcINVALID_HOT_WALLET = 5004, - rpcUNKNOWN_OPTION = 5005, - rpcFIELD_NOT_FOUND_TRANSACTION = 5006, - rpcMALFORMED_ORACLE_DOCUMENT_ID = 5007, - rpcMALFORMED_AUTHORIZED_CREDENTIALS = 5008, + RpcMalformedCurrency = 5000, + RpcMalformedRequest = 5001, + RpcMalformedOwner = 5002, + RpcMalformedAddress = 5003, + RpcInvalidHotWallet = 5004, + RpcUnknownOption = 5005, + RpcFieldNotFoundTransaction = 5006, + RpcMalformedOracleDocumentId = 5007, + RpcMalformedAuthorizedCredentials = 5008, // special system errors start with 6000 - rpcINVALID_API_VERSION = 6000, - rpcCOMMAND_IS_MISSING = 6001, - rpcCOMMAND_NOT_STRING = 6002, - rpcCOMMAND_IS_EMPTY = 6003, - rpcPARAMS_UNPARSEABLE = 6004, + RpcInvalidApiVersion = 6000, + RpcCommandIsMissing = 6001, + RpcCommandNotString = 6002, + RpcCommandIsEmpty = 6003, + RpcParamsUnparseable = 6004, // TODO: Since it is not only rpc errors here now, we should move it to util // etl related errors start with 7000 // Higher value in this errors means better progress in the forwarding - etlCONNECTION_ERROR = 7000, - etlREQUEST_ERROR = 7001, - etlREQUEST_TIMEOUT = 7002, - etlINVALID_RESPONSE = 7003, + EtlConnectionError = 7000, + EtlRequestError = 7001, + EtlRequestTimeout = 7002, + EtlInvalidResponse = 7003, }; /** @brief Holds info about a particular @ref ClioError. */ @@ -186,11 +186,11 @@ struct Status { /** @brief Warning codes that can be returned by clio. */ enum WarningCode { - warnUNKNOWN = -1, - warnRPC_CLIO = 2001, - warnRPC_OUTDATED = 2002, - warnRPC_RATE_LIMIT = 2003, - warnRPC_DEPRECATED = 2004 + WarnUnknown = -1, + WarnRpcClio = 2001, + WarnRpcOutdated = 2002, + WarnRpcRateLimit = 2003, + WarnRpcDeprecated = 2004 }; /** @brief Holds information about a clio warning. */ @@ -207,13 +207,13 @@ struct WarningInfo { { } - WarningCode code = warnUNKNOWN; + WarningCode code = WarnUnknown; std::string_view const message = "unknown warning"; }; /** @brief Invalid parameters error. */ class InvalidParamsError : public std::exception { - std::string msg; + std::string msg_; public: /** @@ -221,7 +221,7 @@ public: * * @param msg The error message */ - explicit InvalidParamsError(std::string msg) : msg(std::move(msg)) + explicit InvalidParamsError(std::string msg) : msg_(std::move(msg)) { } @@ -233,13 +233,13 @@ public: char const* what() const throw() override { - return msg.c_str(); + return msg_.c_str(); } }; /** @brief Account not found error. */ class AccountNotFoundError : public std::exception { - std::string account; + std::string account_; public: /** @@ -247,7 +247,7 @@ public: * * @param acct The account */ - explicit AccountNotFoundError(std::string acct) : account(std::move(acct)) + explicit AccountNotFoundError(std::string acct) : account_(std::move(acct)) { } @@ -259,12 +259,12 @@ public: char const* what() const throw() override { - return account.c_str(); + return account_.c_str(); } }; /** @brief A globally available @ref rpc::Status that represents a successful state. */ -static Status OK; +static Status gOk; /** * @brief Get the warning info object from a warning code. diff --git a/src/rpc/Factories.cpp b/src/rpc/Factories.cpp index c90c0b48..0747a343 100644 --- a/src/rpc/Factories.cpp +++ b/src/rpc/Factories.cpp @@ -44,7 +44,7 @@ using namespace util; namespace rpc { std::expected -make_WsContext( +makeWsContext( boost::asio::yield_context yc, boost::json::object const& request, web::SubscriptionContextPtr session, @@ -63,18 +63,18 @@ make_WsContext( } if (!commandValue.is_string()) - return Error{{ClioError::rpcCOMMAND_IS_MISSING, "Method/Command is not specified or is not a string."}}; + return Error{{ClioError::RpcCommandIsMissing, "Method/Command is not specified or is not a string."}}; auto const apiVersion = apiVersionParser.get().parse(request); if (!apiVersion) - return Error{{ClioError::rpcINVALID_API_VERSION, apiVersion.error()}}; + return Error{{ClioError::RpcInvalidApiVersion, apiVersion.error()}}; auto const command = boost::json::value_to(commandValue); return web::Context(yc, command, *apiVersion, request, std::move(session), tagFactory, range, clientIp, isAdmin); } std::expected -make_HttpContext( +makeHttpContext( boost::asio::yield_context yc, boost::json::object const& request, util::TagDecoratorFactory const& tagFactory, @@ -85,13 +85,13 @@ make_HttpContext( ) { if (!request.contains("method")) - return Error{{ClioError::rpcCOMMAND_IS_MISSING}}; + return Error{{ClioError::RpcCommandIsMissing}}; if (!request.at("method").is_string()) - return Error{{ClioError::rpcCOMMAND_NOT_STRING}}; + return Error{{ClioError::RpcCommandNotString}}; if (request.at("method").as_string().empty()) - return Error{{ClioError::rpcCOMMAND_IS_EMPTY}}; + return Error{{ClioError::RpcCommandIsEmpty}}; auto const command = boost::json::value_to(request.at("method")); @@ -99,16 +99,16 @@ make_HttpContext( return Error{{RippledError::rpcBAD_SYNTAX, "Subscribe and unsubscribe are only allowed for websocket."}}; if (!request.at("params").is_array()) - return Error{{ClioError::rpcPARAMS_UNPARSEABLE, "Missing params array."}}; + return Error{{ClioError::RpcParamsUnparseable, "Missing params array."}}; boost::json::array const& array = request.at("params").as_array(); if (array.size() != 1 || !array.at(0).is_object()) - return Error{{ClioError::rpcPARAMS_UNPARSEABLE}}; + return Error{{ClioError::RpcParamsUnparseable}}; auto const apiVersion = apiVersionParser.get().parse(request.at("params").as_array().at(0).as_object()); if (!apiVersion) - return Error{{ClioError::rpcINVALID_API_VERSION, apiVersion.error()}}; + return Error{{ClioError::RpcInvalidApiVersion, apiVersion.error()}}; return web::Context( yc, command, *apiVersion, array.at(0).as_object(), nullptr, tagFactory, range, clientIp, isAdmin diff --git a/src/rpc/Factories.hpp b/src/rpc/Factories.hpp index 08e1b726..1569ba18 100644 --- a/src/rpc/Factories.hpp +++ b/src/rpc/Factories.hpp @@ -57,7 +57,7 @@ namespace rpc { * @return A Websocket context or error Status */ std::expected -make_WsContext( +makeWsContext( boost::asio::yield_context yc, boost::json::object const& request, web::SubscriptionContextPtr session, @@ -81,7 +81,7 @@ make_WsContext( * @return A HTTP context or error Status */ std::expected -make_HttpContext( +makeHttpContext( boost::asio::yield_context yc, boost::json::object const& request, util::TagDecoratorFactory const& tagFactory, diff --git a/src/rpc/RPCEngine.hpp b/src/rpc/RPCEngine.hpp index bb140bbd..13216c20 100644 --- a/src/rpc/RPCEngine.hpp +++ b/src/rpc/RPCEngine.hpp @@ -125,7 +125,7 @@ public: * @return A new instance of the RPC engine */ static std::shared_ptr - make_RPCEngine( + makeRPCEngine( util::config::ClioConfigDefinition const& config, std::shared_ptr const& backend, std::shared_ptr const& balancer, diff --git a/src/rpc/RPCHelpers.cpp b/src/rpc/RPCHelpers.cpp index 7e04787f..2294ecec 100644 --- a/src/rpc/RPCHelpers.cpp +++ b/src/rpc/RPCHelpers.cpp @@ -156,9 +156,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 std::uint32_t constexpr FIRST_LEDGER_WITH_DELIVERED_AMOUNT = 4594095; - static std::uint32_t constexpr DELIVERED_AMOUNT_LIVE_DATE = 446000000; - if (ledgerSequence >= FIRST_LEDGER_WITH_DELIVERED_AMOUNT || date > DELIVERED_AMOUNT_LIVE_DATE) { + 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) { return txn->getFieldAmount(ripple::sfAmount); } } @@ -286,13 +286,13 @@ toExpandedJson( std::optional encodeCTID(uint32_t ledgerSeq, uint16_t txnIndex, uint16_t networkId) noexcept { - static uint32_t constexpr MAX_LEDGER_SEQ = 0x0FFF'FFFF; - if (ledgerSeq > MAX_LEDGER_SEQ) + static constexpr uint32_t kMAX_LEDGER_SEQ = 0x0FFF'FFFF; + if (ledgerSeq > kMAX_LEDGER_SEQ) return {}; - static uint64_t constexpr CTID_PREFIX = 0xC000'0000; + static constexpr uint64_t kCTID_PREFIX = 0xC000'0000; uint64_t const ctidValue = - ((CTID_PREFIX + static_cast(ledgerSeq)) << 32) + (static_cast(txnIndex) << 16) + networkId; + ((kCTID_PREFIX + static_cast(ledgerSeq)) << 32) + (static_cast(txnIndex) << 16) + networkId; return {fmt::format("{:016X}", ctidValue)}; } @@ -711,8 +711,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 std::uint32_t constexpr MIN_NODES = 2048; - keys.reserve(std::min(MIN_NODES, limit)); + static constexpr std::uint32_t kMIN_NODES = 2048; + keys.reserve(std::min(kMIN_NODES, limit)); auto start = std::chrono::system_clock::now(); @@ -848,10 +848,10 @@ parseRippleLibSeed(boost::json::value const& value) auto const result = ripple::decodeBase58Token(boost::json::value_to(value), ripple::TokenType::None); - static std::size_t constexpr SEED_SIZE = 18; - static std::array constexpr SEED_PREFIX = {0xE1, 0x4B}; - if (result.size() == SEED_SIZE && static_cast(result[0]) == SEED_PREFIX[0] && - static_cast(result[1]) == SEED_PREFIX[1]) + static constexpr std::size_t kSEED_SIZE = 18; + static constexpr std::array kSEED_PREFIX = {0xE1, 0x4B}; + if (result.size() == kSEED_SIZE && static_cast(result[0]) == kSEED_PREFIX[0] && + static_cast(result[1]) == kSEED_PREFIX[1]) return ripple::Seed(ripple::makeSlice(result.substr(2))); return {}; @@ -1212,94 +1212,94 @@ parseBook(boost::json::object const& request) if (!request.at("taker_gets").is_object()) return Status{RippledError::rpcINVALID_PARAMS, "Field 'taker_gets' is not an object"}; - auto taker_pays = request.at("taker_pays").as_object(); - if (!taker_pays.contains("currency")) + auto takerPays = request.at("taker_pays").as_object(); + if (!takerPays.contains("currency")) return Status{RippledError::rpcSRC_CUR_MALFORMED}; - if (!taker_pays.at("currency").is_string()) + if (!takerPays.at("currency").is_string()) return Status{RippledError::rpcSRC_CUR_MALFORMED}; - auto taker_gets = request.at("taker_gets").as_object(); - if (!taker_gets.contains("currency")) + auto takerGets = request.at("taker_gets").as_object(); + if (!takerGets.contains("currency")) return Status{RippledError::rpcDST_AMT_MALFORMED}; - if (!taker_gets.at("currency").is_string()) { + if (!takerGets.at("currency").is_string()) { return Status{ RippledError::rpcDST_AMT_MALFORMED, }; } - ripple::Currency pay_currency; - if (!ripple::to_currency(pay_currency, boost::json::value_to(taker_pays.at("currency")))) + ripple::Currency payCurrency; + if (!ripple::to_currency(payCurrency, boost::json::value_to(takerPays.at("currency")))) return Status{RippledError::rpcSRC_CUR_MALFORMED}; - ripple::Currency get_currency; - if (!ripple::to_currency(get_currency, boost::json::value_to(taker_gets["currency"]))) + ripple::Currency getCurrency; + if (!ripple::to_currency(getCurrency, boost::json::value_to(takerGets["currency"]))) return Status{RippledError::rpcDST_AMT_MALFORMED}; - ripple::AccountID pay_issuer; - if (taker_pays.contains("issuer")) { - if (!taker_pays.at("issuer").is_string()) + ripple::AccountID payIssuer; + if (takerPays.contains("issuer")) { + if (!takerPays.at("issuer").is_string()) return Status{RippledError::rpcINVALID_PARAMS, "takerPaysIssuerNotString"}; - if (!ripple::to_issuer(pay_issuer, boost::json::value_to(taker_pays.at("issuer")))) + if (!ripple::to_issuer(payIssuer, boost::json::value_to(takerPays.at("issuer")))) return Status{RippledError::rpcSRC_ISR_MALFORMED}; - if (pay_issuer == ripple::noAccount()) + if (payIssuer == ripple::noAccount()) return Status{RippledError::rpcSRC_ISR_MALFORMED}; } else { - pay_issuer = ripple::xrpAccount(); + payIssuer = ripple::xrpAccount(); } - if (isXRP(pay_currency) && !isXRP(pay_issuer)) { + if (isXRP(payCurrency) && !isXRP(payIssuer)) { return Status{ RippledError::rpcSRC_ISR_MALFORMED, "Unneeded field 'taker_pays.issuer' for XRP currency specification." }; } - if (!isXRP(pay_currency) && isXRP(pay_issuer)) { + if (!isXRP(payCurrency) && isXRP(payIssuer)) { return Status{ RippledError::rpcSRC_ISR_MALFORMED, "Invalid field 'taker_pays.issuer', expected non-XRP issuer." }; } - if ((!isXRP(pay_currency)) && (!taker_pays.contains("issuer"))) + if ((!isXRP(payCurrency)) && (!takerPays.contains("issuer"))) return Status{RippledError::rpcSRC_ISR_MALFORMED, "Missing non-XRP issuer."}; - ripple::AccountID get_issuer; + ripple::AccountID getIssuer; - if (taker_gets.contains("issuer")) { - if (!taker_gets["issuer"].is_string()) + if (takerGets.contains("issuer")) { + if (!takerGets["issuer"].is_string()) return Status{RippledError::rpcINVALID_PARAMS, "taker_gets.issuer should be string"}; - if (!ripple::to_issuer(get_issuer, boost::json::value_to(taker_gets.at("issuer")))) + if (!ripple::to_issuer(getIssuer, boost::json::value_to(takerGets.at("issuer")))) return Status{RippledError::rpcDST_ISR_MALFORMED, "Invalid field 'taker_gets.issuer', bad issuer."}; - if (get_issuer == ripple::noAccount()) { + if (getIssuer == ripple::noAccount()) { return Status{ RippledError::rpcDST_ISR_MALFORMED, "Invalid field 'taker_gets.issuer', bad issuer account one." }; } } else { - get_issuer = ripple::xrpAccount(); + getIssuer = ripple::xrpAccount(); } - if (ripple::isXRP(get_currency) && !ripple::isXRP(get_issuer)) { + if (ripple::isXRP(getCurrency) && !ripple::isXRP(getIssuer)) { return Status{ RippledError::rpcDST_ISR_MALFORMED, "Unneeded field 'taker_gets.issuer' for XRP currency specification." }; } - if (!ripple::isXRP(get_currency) && ripple::isXRP(get_issuer)) { + if (!ripple::isXRP(getCurrency) && ripple::isXRP(getIssuer)) { return Status{ RippledError::rpcDST_ISR_MALFORMED, "Invalid field 'taker_gets.issuer', expected non-XRP issuer." }; } - if (pay_currency == get_currency && pay_issuer == get_issuer) + if (payCurrency == getCurrency && payIssuer == getIssuer) return Status{RippledError::rpcBAD_MARKET, "badMarket"}; - return ripple::Book{{pay_currency, pay_issuer}, {get_currency, get_issuer}}; + return ripple::Book{{payCurrency, payIssuer}, {getCurrency, getIssuer}}; } std::variant diff --git a/src/rpc/RPCHelpers.hpp b/src/rpc/RPCHelpers.hpp index 289a3d6e..0a9202d4 100644 --- a/src/rpc/RPCHelpers.hpp +++ b/src/rpc/RPCHelpers.hpp @@ -616,8 +616,8 @@ decodeCTID(T const ctid) noexcept auto const getCTID64 = [](T const ctid) noexcept -> std::optional { if constexpr (std::is_convertible_v) { std::string const ctidString(ctid); - static std::size_t constexpr CTID_STRING_LENGTH = 16; - if (ctidString.length() != CTID_STRING_LENGTH) + static constexpr std::size_t kCTID_STRING_LENGTH = 16; + if (ctidString.length() != kCTID_STRING_LENGTH) return {}; if (!boost::regex_match(ctidString, boost::regex("^[0-9A-F]+$"))) @@ -634,10 +634,10 @@ decodeCTID(T const ctid) noexcept auto const ctidValue = getCTID64(ctid).value_or(0); - static uint64_t constexpr CTID_PREFIX = 0xC000'0000'0000'0000ULL; - static uint64_t constexpr CTID_PREFIX_MASK = 0xF000'0000'0000'0000ULL; + static constexpr uint64_t kCTID_PREFIX = 0xC000'0000'0000'0000ULL; + static constexpr uint64_t kCTID_PREFIX_MASK = 0xF000'0000'0000'0000ULL; - if ((ctidValue & CTID_PREFIX_MASK) != CTID_PREFIX) + if ((ctidValue & kCTID_PREFIX_MASK) != kCTID_PREFIX) return {}; uint32_t const ledgerSeq = (ctidValue >> 32) & 0xFFFF'FFFUL; @@ -659,8 +659,8 @@ logDuration(web::Context const& ctx, T const& dur) { using boost::json::serialize; - static util::Logger const log{"RPC"}; - static std::int64_t constexpr DURATION_ERROR_THRESHOLD_SECONDS = 10; + static util::Logger const log{"RPC"}; // NOLINT(readability-identifier-naming) + static constexpr std::int64_t kDURATION_ERROR_THRESHOLD_SECONDS = 10; auto const millis = std::chrono::duration_cast(dur).count(); auto const seconds = std::chrono::duration_cast(dur).count(); @@ -668,7 +668,7 @@ logDuration(web::Context const& ctx, T const& dur) "Request processing duration = {} milliseconds. request = {}", millis, serialize(util::removeSecret(ctx.params)) ); - if (seconds > DURATION_ERROR_THRESHOLD_SECONDS) { + if (seconds > kDURATION_ERROR_THRESHOLD_SECONDS) { LOG(log.error()) << ctx.tag() << msg; } else if (seconds > 1) { LOG(log.warn()) << ctx.tag() << msg; diff --git a/src/rpc/WorkQueue.cpp b/src/rpc/WorkQueue.cpp index 93a526b9..6f946f96 100644 --- a/src/rpc/WorkQueue.cpp +++ b/src/rpc/WorkQueue.cpp @@ -90,9 +90,9 @@ WorkQueue::stop(std::function onQueueEmpty) } WorkQueue -WorkQueue::make_WorkQueue(util::config::ClioConfigDefinition const& config) +WorkQueue::makeWorkQueue(util::config::ClioConfigDefinition const& config) { - static util::Logger const log{"RPC"}; + static util::Logger const log{"RPC"}; // NOLINT(readability-identifier-naming) auto const serverConfig = config.getObject("server"); auto const numThreads = config.get("workers"); auto const maxQueueSize = serverConfig.get("max_queue_size"); diff --git a/src/rpc/WorkQueue.hpp b/src/rpc/WorkQueue.hpp index 16997cf8..2472135e 100644 --- a/src/rpc/WorkQueue.hpp +++ b/src/rpc/WorkQueue.hpp @@ -96,7 +96,7 @@ public: * @return The work queue */ static WorkQueue - make_WorkQueue(util::config::ClioConfigDefinition const& config); + makeWorkQueue(util::config::ClioConfigDefinition const& config); /** * @brief Submit a job to the work queue. diff --git a/src/rpc/common/APIVersion.hpp b/src/rpc/common/APIVersion.hpp index 009dea3b..d030e54f 100644 --- a/src/rpc/common/APIVersion.hpp +++ b/src/rpc/common/APIVersion.hpp @@ -30,17 +30,17 @@ namespace rpc { /** * @brief Default API version to use if no version is specified by clients */ -static constexpr uint32_t API_VERSION_DEFAULT = 1u; +static constexpr uint32_t kAPI_VERSION_DEFAULT = 1u; /** * @brief Minimum API version supported by this build */ -static constexpr uint32_t API_VERSION_MIN = 1u; +static constexpr uint32_t kAPI_VERSION_MIN = 1u; /** * @brief Maximum API version supported by this build */ -static constexpr uint32_t API_VERSION_MAX = 3u; +static constexpr uint32_t kAPI_VERSION_MAX = 3u; /** * @brief A baseclass for API version helper diff --git a/src/rpc/common/Checkers.hpp b/src/rpc/common/Checkers.hpp index d25076c7..75297d52 100644 --- a/src/rpc/common/Checkers.hpp +++ b/src/rpc/common/Checkers.hpp @@ -78,7 +78,7 @@ public: check(boost::json::value const& value, std::string_view key) { if (value.is_object() and value.as_object().contains(key)) - return Warning{WarningCode::warnRPC_DEPRECATED, fmt::format("Field '{}' is deprecated.", key)}; + return Warning{WarningCode::WarnRpcDeprecated, fmt::format("Field '{}' is deprecated.", key)}; return std::nullopt; } }; @@ -117,7 +117,7 @@ public: auto const res = value_to(value.as_object().at(key)); if (value_ == res) { return Warning{ - WarningCode::warnRPC_DEPRECATED, fmt::format("Value '{}' for field '{}' is deprecated", value_, key) + WarningCode::WarnRpcDeprecated, fmt::format("Value '{}' for field '{}' is deprecated", value_, key) }; } } diff --git a/src/rpc/common/MetaProcessors.cpp b/src/rpc/common/MetaProcessors.cpp index 37efc6a4..8eaf3a8c 100644 --- a/src/rpc/common/MetaProcessors.cpp +++ b/src/rpc/common/MetaProcessors.cpp @@ -40,7 +40,7 @@ Section::verify(boost::json::value& value, std::string_view key) const if (!res.is_object()) return {}; - for (auto const& spec : specs) { + for (auto const& spec : specs_) { if (auto const ret = spec.process(res); not ret) return Error{ret.error()}; } diff --git a/src/rpc/common/MetaProcessors.hpp b/src/rpc/common/MetaProcessors.hpp index a411f785..3a488fbf 100644 --- a/src/rpc/common/MetaProcessors.hpp +++ b/src/rpc/common/MetaProcessors.hpp @@ -20,6 +20,7 @@ #pragma once #include "rpc/Errors.hpp" +#include "rpc/common/Concepts.hpp" #include "rpc/common/Specs.hpp" #include "rpc/common/Types.hpp" @@ -40,7 +41,7 @@ namespace rpc::meta { * @brief A meta-processor that acts as a spec for a sub-object/section. */ class Section final { - std::vector specs; + std::vector specs_; public: /** @@ -48,7 +49,7 @@ public: * * @param specs List of specs @ref FieldSpec */ - explicit Section(std::initializer_list specs) : specs{specs} + explicit Section(std::initializer_list specs) : specs_{specs} { } @@ -163,8 +164,8 @@ private: template requires SomeRequirement or SomeModifier class WithCustomError final { - RequirementOrModifierType reqOrModifier; - Status error; + RequirementOrModifierType reqOrModifier_; + Status error_; public: /** @@ -175,7 +176,7 @@ public: * @param err The custom error to return in case `req` fails */ WithCustomError(RequirementOrModifierType reqOrModifier, Status err) - : reqOrModifier{std::move(reqOrModifier)}, error{std::move(err)} + : reqOrModifier_{std::move(reqOrModifier)}, error_{std::move(err)} { } @@ -190,8 +191,8 @@ public: verify(boost::json::value const& value, std::string_view key) const requires SomeRequirement { - if (auto const res = reqOrModifier.verify(value, key); not res) - return Error{error}; + if (auto const res = reqOrModifier_.verify(value, key); not res) + return Error{error_}; return {}; } @@ -208,8 +209,8 @@ public: verify(boost::json::value& value, std::string_view key) const requires SomeRequirement { - if (auto const res = reqOrModifier.verify(value, key); not res) - return Error{error}; + if (auto const res = reqOrModifier_.verify(value, key); not res) + return Error{error_}; return {}; } @@ -226,8 +227,8 @@ public: requires SomeModifier { - if (auto const res = reqOrModifier.modify(value, key); not res) - return Error{error}; + if (auto const res = reqOrModifier_.modify(value, key); not res) + return Error{error_}; return {}; } }; diff --git a/src/rpc/common/Specs.hpp b/src/rpc/common/Specs.hpp index c7ac4ba5..c5adca8a 100644 --- a/src/rpc/common/Specs.hpp +++ b/src/rpc/common/Specs.hpp @@ -48,7 +48,7 @@ struct FieldSpec final { template FieldSpec(std::string const& key, Processors&&... processors) : processor_{impl::makeFieldProcessor(key, std::forward(processors)...)} - , checker_{impl::EMPTY_FIELD_CHECKER} + , checker_{impl::kEMPTY_FIELD_CHECKER} { } @@ -61,7 +61,7 @@ struct FieldSpec final { */ template FieldSpec(std::string const& key, Checks&&... checks) - : processor_{impl::EMPTY_FIELD_PROCESSOR} + : processor_{impl::kEMPTY_FIELD_PROCESSOR} , checker_{impl::makeFieldChecker(key, std::forward(checks)...)} { } diff --git a/src/rpc/common/Validators.cpp b/src/rpc/common/Validators.cpp index 063b0008..58fd005b 100644 --- a/src/rpc/common/Validators.cpp +++ b/src/rpc/common/Validators.cpp @@ -66,7 +66,7 @@ TimeFormatValidator::verify(boost::json::value const& value, std::string_view ke if (not value.as_object().at(key).is_string()) return Error{Status{RippledError::rpcINVALID_PARAMS}}; - auto const ret = util::SystemTpFromUTCStr(value_to(value.as_object().at(key)), format_); + auto const ret = util::systemTpFromUtcStr(value_to(value.as_object().at(key)), format_); if (!ret) return Error{Status{RippledError::rpcINVALID_PARAMS}}; @@ -91,22 +91,22 @@ checkIsU32Numeric(std::string_view sv) return ec == std::errc(); } -CustomValidator CustomValidators::Uint160HexStringValidator = +CustomValidator CustomValidators::uint160HexStringValidator = CustomValidator{[](boost::json::value const& value, std::string_view key) -> MaybeError { return makeHexStringValidator(value, key); }}; -CustomValidator CustomValidators::Uint192HexStringValidator = +CustomValidator CustomValidators::uint192HexStringValidator = CustomValidator{[](boost::json::value const& value, std::string_view key) -> MaybeError { return makeHexStringValidator(value, key); }}; -CustomValidator CustomValidators::Uint256HexStringValidator = +CustomValidator CustomValidators::uint256HexStringValidator = CustomValidator{[](boost::json::value const& value, std::string_view key) -> MaybeError { return makeHexStringValidator(value, key); }}; -CustomValidator CustomValidators::LedgerIndexValidator = +CustomValidator CustomValidators::ledgerIndexValidator = CustomValidator{[](boost::json::value const& value, std::string_view /* key */) -> MaybeError { auto err = Error{Status{RippledError::rpcINVALID_PARAMS, "ledgerIndexMalformed"}}; @@ -120,7 +120,7 @@ CustomValidator CustomValidators::LedgerIndexValidator = return MaybeError{}; }}; -CustomValidator CustomValidators::AccountValidator = +CustomValidator CustomValidators::accountValidator = CustomValidator{[](boost::json::value const& value, std::string_view key) -> MaybeError { if (!value.is_string()) return Error{Status{RippledError::rpcINVALID_PARAMS, std::string(key) + "NotString"}}; @@ -133,19 +133,19 @@ CustomValidator CustomValidators::AccountValidator = return MaybeError{}; }}; -CustomValidator CustomValidators::AccountBase58Validator = +CustomValidator CustomValidators::accountBase58Validator = CustomValidator{[](boost::json::value const& value, std::string_view key) -> MaybeError { if (!value.is_string()) return Error{Status{RippledError::rpcINVALID_PARAMS, std::string(key) + "NotString"}}; auto const account = util::parseBase58Wrapper(boost::json::value_to(value)); if (!account || account->isZero()) - return Error{Status{ClioError::rpcMALFORMED_ADDRESS}}; + return Error{Status{ClioError::RpcMalformedAddress}}; return MaybeError{}; }}; -CustomValidator CustomValidators::AccountMarkerValidator = +CustomValidator CustomValidators::accountMarkerValidator = CustomValidator{[](boost::json::value const& value, std::string_view key) -> MaybeError { if (!value.is_string()) return Error{Status{RippledError::rpcINVALID_PARAMS, std::string(key) + "NotString"}}; @@ -160,7 +160,7 @@ CustomValidator CustomValidators::AccountMarkerValidator = return MaybeError{}; }}; -CustomValidator CustomValidators::CurrencyValidator = +CustomValidator CustomValidators::currencyValidator = CustomValidator{[](boost::json::value const& value, std::string_view key) -> MaybeError { if (!value.is_string()) return Error{Status{RippledError::rpcINVALID_PARAMS, std::string(key) + "NotString"}}; @@ -171,12 +171,12 @@ CustomValidator CustomValidators::CurrencyValidator = ripple::Currency currency; if (!ripple::to_currency(currency, currencyStr)) - return Error{Status{ClioError::rpcMALFORMED_CURRENCY, "malformedCurrency"}}; + return Error{Status{ClioError::RpcMalformedCurrency, "malformedCurrency"}}; return MaybeError{}; }}; -CustomValidator CustomValidators::IssuerValidator = +CustomValidator CustomValidators::issuerValidator = CustomValidator{[](boost::json::value const& value, std::string_view key) -> MaybeError { if (!value.is_string()) return Error{Status{RippledError::rpcINVALID_PARAMS, std::string(key) + "NotString"}}; @@ -196,31 +196,31 @@ CustomValidator CustomValidators::IssuerValidator = return MaybeError{}; }}; -CustomValidator CustomValidators::SubscribeStreamValidator = +CustomValidator CustomValidators::subscribeStreamValidator = CustomValidator{[](boost::json::value const& value, std::string_view key) -> MaybeError { if (!value.is_array()) return Error{Status{RippledError::rpcINVALID_PARAMS, std::string(key) + "NotArray"}}; - static std::unordered_set const validStreams = { + static std::unordered_set const kVALID_STREAMS = { "ledger", "transactions", "transactions_proposed", "book_changes", "manifests", "validations" }; - static std::unordered_set const notSupportStreams = {"peer_status", "consensus", "server"}; + static std::unordered_set const kNOT_SUPPORT_STREAMS = {"peer_status", "consensus", "server"}; for (auto const& v : value.as_array()) { if (!v.is_string()) return Error{Status{RippledError::rpcINVALID_PARAMS, "streamNotString"}}; - if (notSupportStreams.contains(boost::json::value_to(v))) + if (kNOT_SUPPORT_STREAMS.contains(boost::json::value_to(v))) return Error{Status{RippledError::rpcNOT_SUPPORTED}}; - if (not validStreams.contains(boost::json::value_to(v))) + if (not kVALID_STREAMS.contains(boost::json::value_to(v))) return Error{Status{RippledError::rpcSTREAM_MALFORMED}}; } return MaybeError{}; }}; -CustomValidator CustomValidators::SubscribeAccountsValidator = +CustomValidator CustomValidators::subscribeAccountsValidator = CustomValidator{[](boost::json::value const& value, std::string_view key) -> MaybeError { if (!value.is_array()) return Error{Status{RippledError::rpcINVALID_PARAMS, std::string(key) + "NotArray"}}; @@ -234,14 +234,14 @@ CustomValidator CustomValidators::SubscribeAccountsValidator = obj[keyItem] = v; - if (auto err = AccountValidator.verify(obj, keyItem); !err) + if (auto err = accountValidator.verify(obj, keyItem); !err) return err; } return MaybeError{}; }}; -CustomValidator CustomValidators::CurrencyIssueValidator = +CustomValidator CustomValidators::currencyIssueValidator = CustomValidator{[](boost::json::value const& value, std::string_view key) -> MaybeError { if (not value.is_object()) return Error{Status{RippledError::rpcINVALID_PARAMS, std::string(key) + "NotObject"}}; @@ -249,49 +249,49 @@ CustomValidator CustomValidators::CurrencyIssueValidator = try { parseIssue(value.as_object()); } catch (std::runtime_error const&) { - return Error{Status{ClioError::rpcMALFORMED_REQUEST}}; + return Error{Status{ClioError::RpcMalformedRequest}}; } return MaybeError{}; }}; -CustomValidator CustomValidators::CredentialTypeValidator = +CustomValidator CustomValidators::credentialTypeValidator = CustomValidator{[](boost::json::value const& value, std::string_view key) -> MaybeError { if (not value.is_string()) - return Error{Status{ClioError::rpcMALFORMED_AUTHORIZED_CREDENTIALS, std::string(key) + " NotString"}}; + return Error{Status{ClioError::RpcMalformedAuthorizedCredentials, std::string(key) + " NotString"}}; auto const& credTypeHex = ripple::strViewUnHex(value.as_string()); if (!credTypeHex.has_value()) - return Error{Status{ClioError::rpcMALFORMED_AUTHORIZED_CREDENTIALS, std::string(key) + " NotHexString"}}; + return Error{Status{ClioError::RpcMalformedAuthorizedCredentials, std::string(key) + " NotHexString"}}; if (credTypeHex->empty()) - return Error{Status{ClioError::rpcMALFORMED_AUTHORIZED_CREDENTIALS, std::string(key) + " is empty"}}; + return Error{Status{ClioError::RpcMalformedAuthorizedCredentials, std::string(key) + " is empty"}}; if (credTypeHex->size() > ripple::maxCredentialTypeLength) { return Error{ - Status{ClioError::rpcMALFORMED_AUTHORIZED_CREDENTIALS, std::string(key) + " greater than max length"} + Status{ClioError::RpcMalformedAuthorizedCredentials, std::string(key) + " greater than max length"} }; } return MaybeError{}; }}; -CustomValidator CustomValidators::AuthorizeCredentialValidator = +CustomValidator CustomValidators::authorizeCredentialValidator = CustomValidator{[](boost::json::value const& value, std::string_view key) -> MaybeError { if (not value.is_array()) - return Error{Status{ClioError::rpcMALFORMED_REQUEST, std::string(key) + " not array"}}; + return Error{Status{ClioError::RpcMalformedRequest, std::string(key) + " not array"}}; auto const& authCred = value.as_array(); if (authCred.empty()) { return Error{Status{ - ClioError::rpcMALFORMED_AUTHORIZED_CREDENTIALS, + ClioError::RpcMalformedAuthorizedCredentials, fmt::format("Requires at least one element in authorized_credentials array.") }}; } if (authCred.size() > ripple::maxCredentialsArraySize) { return Error{Status{ - ClioError::rpcMALFORMED_AUTHORIZED_CREDENTIALS, + ClioError::RpcMalformedAuthorizedCredentials, fmt::format( "Max {} number of credentials in authorized_credentials array", ripple::maxCredentialsArraySize ) @@ -301,7 +301,7 @@ CustomValidator CustomValidators::AuthorizeCredentialValidator = for (auto const& credObj : value.as_array()) { if (!credObj.is_object()) { return Error{Status{ - ClioError::rpcMALFORMED_AUTHORIZED_CREDENTIALS, + ClioError::RpcMalformedAuthorizedCredentials, "authorized_credentials elements in array are not objects." }}; } @@ -309,21 +309,21 @@ CustomValidator CustomValidators::AuthorizeCredentialValidator = if (!obj.contains("issuer")) { return Error{ - Status{ClioError::rpcMALFORMED_AUTHORIZED_CREDENTIALS, "Field 'Issuer' is required but missing."} + Status{ClioError::RpcMalformedAuthorizedCredentials, "Field 'Issuer' is required but missing."} }; } // don't want to change issuer error message to be about credentials - if (!IssuerValidator.verify(credObj, "issuer")) - return Error{Status{ClioError::rpcMALFORMED_AUTHORIZED_CREDENTIALS, "issuer NotString"}}; + if (!issuerValidator.verify(credObj, "issuer")) + return Error{Status{ClioError::RpcMalformedAuthorizedCredentials, "issuer NotString"}}; if (!obj.contains("credential_type")) { return Error{Status{ - ClioError::rpcMALFORMED_AUTHORIZED_CREDENTIALS, "Field 'CredentialType' is required but missing." + ClioError::RpcMalformedAuthorizedCredentials, "Field 'CredentialType' is required but missing." }}; } - if (auto const err = CredentialTypeValidator.verify(credObj, "credential_type"); !err) + if (auto const err = credentialTypeValidator.verify(credObj, "credential_type"); !err) return err; } diff --git a/src/rpc/common/Validators.hpp b/src/rpc/common/Validators.hpp index 6fcf37c3..ad23fdba 100644 --- a/src/rpc/common/Validators.hpp +++ b/src/rpc/common/Validators.hpp @@ -481,21 +481,21 @@ struct CustomValidators final { * LedgerIndex must be a string or an int. If the specified LedgerIndex is a string, its value must be either * "validated" or a valid integer value represented as a string. */ - static CustomValidator LedgerIndexValidator; + static CustomValidator ledgerIndexValidator; /** * @brief Provides a commonly used validator for accounts. * * Account must be a string and the converted public key is valid. */ - static CustomValidator AccountValidator; + static CustomValidator accountValidator; /** * @brief Provides a commonly used validator for accounts. * * Account must be a string and can convert to base58. */ - static CustomValidator AccountBase58Validator; + static CustomValidator accountBase58Validator; /** * @brief Provides a commonly used validator for markers. @@ -503,7 +503,7 @@ struct CustomValidators final { * A marker is composed of a comma-separated index and a start hint. * The former will be read as hex, and the latter can be cast to uint64. */ - static CustomValidator AccountMarkerValidator; + static CustomValidator accountMarkerValidator; /** * @brief Provides a commonly used validator for uint160(AccountID) hex string. @@ -511,7 +511,7 @@ struct CustomValidators final { * It must be a string and also a decodable hex. * AccountID uses this validator. */ - static CustomValidator Uint160HexStringValidator; + static CustomValidator uint160HexStringValidator; /** * @brief Provides a commonly used validator for uint192 hex string. @@ -519,7 +519,7 @@ struct CustomValidators final { * It must be a string and also a decodable hex. * MPTIssuanceID uses this validator. */ - static CustomValidator Uint192HexStringValidator; + static CustomValidator uint192HexStringValidator; /** * @brief Provides a commonly used validator for uint256 hex string. @@ -527,50 +527,50 @@ struct CustomValidators final { * It must be a string and also a decodable hex. * Transaction index, ledger hash all use this validator. */ - static CustomValidator Uint256HexStringValidator; + static CustomValidator uint256HexStringValidator; /** * @brief Provides a commonly used validator for currency, including standard currency code and token code. */ - static CustomValidator CurrencyValidator; + static CustomValidator currencyValidator; /** * @brief Provides a commonly used validator for issuer type. * * It must be a hex string or base58 string. */ - static CustomValidator IssuerValidator; + static CustomValidator issuerValidator; /** * @brief Provides a validator for validating streams used in subscribe/unsubscribe. */ - static CustomValidator SubscribeStreamValidator; + static CustomValidator subscribeStreamValidator; /** * @brief Provides a validator for validating accounts used in subscribe/unsubscribe. */ - static CustomValidator SubscribeAccountsValidator; + static CustomValidator subscribeAccountsValidator; /** * @brief Validates an asset (ripple::Issue). * * Used by amm_info. */ - static CustomValidator CurrencyIssueValidator; + static CustomValidator currencyIssueValidator; /** * @brief Provides a validator for validating authorized_credentials json array. * * Used by deposit_preauth. */ - static CustomValidator AuthorizeCredentialValidator; + static CustomValidator authorizeCredentialValidator; /** * @brief Provides a validator for validating credential_type. * * Used by AuthorizeCredentialValidator in deposit_preauth. */ - static CustomValidator CredentialTypeValidator; + static CustomValidator credentialTypeValidator; }; /** diff --git a/src/rpc/common/impl/APIVersionParser.hpp b/src/rpc/common/impl/APIVersionParser.hpp index b4f8d454..3fa84d21 100644 --- a/src/rpc/common/impl/APIVersionParser.hpp +++ b/src/rpc/common/impl/APIVersionParser.hpp @@ -40,9 +40,9 @@ class ProductionAPIVersionParser : public APIVersionParser { public: ProductionAPIVersionParser( - uint32_t defaultVersion = API_VERSION_DEFAULT, - uint32_t minVersion = API_VERSION_MIN, - uint32_t maxVersion = API_VERSION_MAX + uint32_t defaultVersion = kAPI_VERSION_DEFAULT, + uint32_t minVersion = kAPI_VERSION_MIN, + uint32_t maxVersion = kAPI_VERSION_MAX ); ProductionAPIVersionParser(util::config::ObjectView const& config); diff --git a/src/rpc/common/impl/Factories.hpp b/src/rpc/common/impl/Factories.hpp index f51d59f7..16bd9d27 100644 --- a/src/rpc/common/impl/Factories.hpp +++ b/src/rpc/common/impl/Factories.hpp @@ -39,7 +39,7 @@ namespace rpc::impl { using FieldSpecProcessor = std::function; -static FieldSpecProcessor const EMPTY_FIELD_PROCESSOR = [](boost::json::value&) -> MaybeError { return {}; }; +static FieldSpecProcessor const kEMPTY_FIELD_PROCESSOR = [](boost::json::value&) -> MaybeError { return {}; }; template [[nodiscard]] FieldSpecProcessor @@ -77,7 +77,7 @@ makeFieldProcessor(std::string const& key, Processors&&... procs) using FieldChecker = std::function; -static FieldChecker const EMPTY_FIELD_CHECKER = [](boost::json::value const&) -> check::Warnings { return {}; }; +static FieldChecker const kEMPTY_FIELD_CHECKER = [](boost::json::value const&) -> check::Warnings { return {}; }; template [[nodiscard]] FieldChecker diff --git a/src/rpc/common/impl/ForwardingProxy.hpp b/src/rpc/common/impl/ForwardingProxy.hpp index cb69d04d..e4e2b32e 100644 --- a/src/rpc/common/impl/ForwardingProxy.hpp +++ b/src/rpc/common/impl/ForwardingProxy.hpp @@ -104,7 +104,7 @@ public: bool isProxied(std::string const& method) const { - static std::unordered_set const proxiedCommands{ + static std::unordered_set const kPROXIED_COMMANDS{ "server_definitions", "server_state", "submit", @@ -118,7 +118,7 @@ public: "channel_verify", }; - return proxiedCommands.contains(method); + return kPROXIED_COMMANDS.contains(method); } private: @@ -145,9 +145,9 @@ private: bool isForcedForward(web::Context const& ctx) const { - static constexpr auto FORCE_FORWARD = "force_forward"; - return ctx.isAdmin and ctx.params.contains(FORCE_FORWARD) and ctx.params.at(FORCE_FORWARD).is_bool() and - ctx.params.at(FORCE_FORWARD).as_bool(); + 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(); } }; diff --git a/src/rpc/common/impl/Processors.hpp b/src/rpc/common/impl/Processors.hpp index c04df899..0c5c16fc 100644 --- a/src/rpc/common/impl/Processors.hpp +++ b/src/rpc/common/impl/Processors.hpp @@ -21,14 +21,12 @@ #include "rpc/common/Concepts.hpp" #include "rpc/common/Types.hpp" +#include "util/UnsupportedType.hpp" #include namespace rpc::impl { -template -static constexpr bool unsupported_handler_v = false; - template struct DefaultProcessor final { [[nodiscard]] ReturnType @@ -63,7 +61,7 @@ struct DefaultProcessor final { return ReturnType{value_from(ret.value())}; } else { // when concept SomeHandlerWithInput and SomeHandlerWithoutInput not cover all Handler case - static_assert(unsupported_handler_v); + static_assert(util::Unsupported); } } }; diff --git a/src/rpc/handlers/AMMInfo.cpp b/src/rpc/handlers/AMMInfo.cpp index 872d94dd..93ed4924 100644 --- a/src/rpc/handlers/AMMInfo.cpp +++ b/src/rpc/handlers/AMMInfo.cpp @@ -65,11 +65,11 @@ std::string toIso8601(ripple::NetClock::time_point tp) { using namespace std::chrono; - static auto constexpr rippleEpochOffset = seconds{rippleEpochStart}; + static constexpr auto kRIPPLE_EPOCH_OFFSET = seconds{kRIPPLE_EPOCH_START}; return date::format( "%Y-%Om-%dT%H:%M:%OS%z", - date::sys_time(system_clock::time_point{tp.time_since_epoch() + rippleEpochOffset}) + date::sys_time(system_clock::time_point{tp.time_since_epoch() + kRIPPLE_EPOCH_OFFSET}) ); }; @@ -229,7 +229,7 @@ AMMInfoHandler::process(AMMInfoHandler::Input input, Context const& ctx) const RpcSpecConstRef AMMInfoHandler::spec([[maybe_unused]] uint32_t apiVersion) { - static auto const stringIssueValidator = + static auto const kSTRING_ISSUE_VALIDATOR = validation::CustomValidator{[](boost::json::value const& value, std::string_view key) -> MaybeError { if (not value.is_string()) return Error{Status{RippledError::rpcINVALID_PARAMS, std::string(key) + "NotString"}}; @@ -243,36 +243,36 @@ AMMInfoHandler::spec([[maybe_unused]] uint32_t apiVersion) return MaybeError{}; }}; - static auto const rpcSpec = RpcSpec{ - {JS(ledger_hash), validation::CustomValidators::Uint256HexStringValidator}, - {JS(ledger_index), validation::CustomValidators::LedgerIndexValidator}, + static auto const kRPC_SPEC = RpcSpec{ + {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, + {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, {JS(asset), meta::WithCustomError{ validation::Type{}, Status(RippledError::rpcISSUE_MALFORMED) }, - meta::IfType{stringIssueValidator}, + meta::IfType{kSTRING_ISSUE_VALIDATOR}, meta::IfType{ meta::WithCustomError{ - validation::CustomValidators::CurrencyIssueValidator, Status(RippledError::rpcISSUE_MALFORMED) + validation::CustomValidators::currencyIssueValidator, Status(RippledError::rpcISSUE_MALFORMED) }, }}, {JS(asset2), meta::WithCustomError{ validation::Type{}, Status(RippledError::rpcISSUE_MALFORMED) }, - meta::IfType{stringIssueValidator}, + meta::IfType{kSTRING_ISSUE_VALIDATOR}, meta::IfType{ meta::WithCustomError{ - validation::CustomValidators::CurrencyIssueValidator, Status(RippledError::rpcISSUE_MALFORMED) + validation::CustomValidators::currencyIssueValidator, Status(RippledError::rpcISSUE_MALFORMED) }, }}, {JS(amm_account), - meta::WithCustomError{validation::CustomValidators::AccountValidator, Status(RippledError::rpcACT_MALFORMED)}}, + meta::WithCustomError{validation::CustomValidators::accountValidator, Status(RippledError::rpcACT_MALFORMED)}}, {JS(account), - meta::WithCustomError{validation::CustomValidators::AccountValidator, Status(RippledError::rpcACT_MALFORMED)}}, + meta::WithCustomError{validation::CustomValidators::accountValidator, Status(RippledError::rpcACT_MALFORMED)}}, }; - return rpcSpec; + return kRPC_SPEC; } void diff --git a/src/rpc/handlers/AccountChannels.hpp b/src/rpc/handlers/AccountChannels.hpp index 792efbdc..b2051dfd 100644 --- a/src/rpc/handlers/AccountChannels.hpp +++ b/src/rpc/handlers/AccountChannels.hpp @@ -51,9 +51,9 @@ class AccountChannelsHandler { std::shared_ptr const sharedPtrBackend_; public: - static constexpr auto LIMIT_MIN = 10; - static constexpr auto LIMIT_MAX = 400; - static constexpr auto LIMIT_DEFAULT = 200; + static constexpr auto kLIMIT_MIN = 10; + static constexpr auto kLIMIT_MAX = 400; + static constexpr auto kLIMIT_DEFAULT = 200; /** * @brief A struct to hold data for one channel response @@ -97,7 +97,7 @@ public: std::optional destinationAccount; std::optional ledgerHash; std::optional ledgerIndex; - uint32_t limit = LIMIT_DEFAULT; + uint32_t limit = kLIMIT_DEFAULT; std::optional marker; }; @@ -122,19 +122,19 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const rpcSpec = RpcSpec{ - {JS(account), validation::Required{}, validation::CustomValidators::AccountValidator}, - {JS(destination_account), validation::Type{}, validation::CustomValidators::AccountValidator}, - {JS(ledger_hash), validation::CustomValidators::Uint256HexStringValidator}, + static auto const kRPC_SPEC = RpcSpec{ + {JS(account), validation::Required{}, validation::CustomValidators::accountValidator}, + {JS(destination_account), validation::Type{}, validation::CustomValidators::accountValidator}, + {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, {JS(limit), validation::Type{}, validation::Min(1u), - modifiers::Clamp{LIMIT_MIN, LIMIT_MAX}}, - {JS(ledger_index), validation::CustomValidators::LedgerIndexValidator}, - {JS(marker), validation::CustomValidators::AccountMarkerValidator}, + modifiers::Clamp{kLIMIT_MIN, kLIMIT_MAX}}, + {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, + {JS(marker), validation::CustomValidators::accountMarkerValidator}, }; - return rpcSpec; + return kRPC_SPEC; } /** diff --git a/src/rpc/handlers/AccountCurrencies.hpp b/src/rpc/handlers/AccountCurrencies.hpp index 0db03fd3..604171de 100644 --- a/src/rpc/handlers/AccountCurrencies.hpp +++ b/src/rpc/handlers/AccountCurrencies.hpp @@ -91,15 +91,15 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const rpcSpec = RpcSpec{ - {JS(account), validation::Required{}, validation::CustomValidators::AccountValidator}, - {JS(ledger_hash), validation::CustomValidators::Uint256HexStringValidator}, - {JS(ledger_index), validation::CustomValidators::LedgerIndexValidator}, + static auto const kRPC_SPEC = RpcSpec{ + {JS(account), validation::Required{}, validation::CustomValidators::accountValidator}, + {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, + {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, {"account_index", check::Deprecated{}}, {JS(strict), check::Deprecated{}} }; - return rpcSpec; + return kRPC_SPEC; } /** diff --git a/src/rpc/handlers/AccountInfo.hpp b/src/rpc/handlers/AccountInfo.hpp index bf37a202..5a2cb812 100644 --- a/src/rpc/handlers/AccountInfo.hpp +++ b/src/rpc/handlers/AccountInfo.hpp @@ -136,19 +136,19 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const rpcSpecV1 = RpcSpec{ - {JS(account), validation::CustomValidators::AccountValidator}, - {JS(ident), validation::CustomValidators::AccountValidator}, + static auto const kRPC_SPEC_V1 = RpcSpec{ + {JS(account), validation::CustomValidators::accountValidator}, + {JS(ident), validation::CustomValidators::accountValidator}, {JS(ident), check::Deprecated{}}, - {JS(ledger_hash), validation::CustomValidators::Uint256HexStringValidator}, - {JS(ledger_index), validation::CustomValidators::LedgerIndexValidator}, + {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, + {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, {JS(ledger), check::Deprecated{}}, {JS(strict), check::Deprecated{}} }; - static auto const rpcSpec = RpcSpec{rpcSpecV1, {{JS(signer_lists), validation::Type{}}}}; + static auto const kRPC_SPEC = RpcSpec{kRPC_SPEC_V1, {{JS(signer_lists), validation::Type{}}}}; - return apiVersion == 1 ? rpcSpecV1 : rpcSpec; + return apiVersion == 1 ? kRPC_SPEC_V1 : kRPC_SPEC; } /** diff --git a/src/rpc/handlers/AccountLines.hpp b/src/rpc/handlers/AccountLines.hpp index 3165d976..26662429 100644 --- a/src/rpc/handlers/AccountLines.hpp +++ b/src/rpc/handlers/AccountLines.hpp @@ -25,6 +25,7 @@ #include "rpc/common/Checkers.hpp" #include "rpc/common/MetaProcessors.hpp" #include "rpc/common/Modifiers.hpp" +#include "rpc/common/Specs.hpp" #include "rpc/common/Types.hpp" #include "rpc/common/Validators.hpp" @@ -54,9 +55,9 @@ class AccountLinesHandler { std::shared_ptr const sharedPtrBackend_; public: - static auto constexpr LIMIT_MIN = 10; - static auto constexpr LIMIT_MAX = 400; - static auto constexpr LIMIT_DEFAULT = 200; + static constexpr auto kLIMIT_MIN = 10; + static constexpr auto kLIMIT_MAX = 400; + static constexpr auto kLIMIT_DEFAULT = 200; /** * @brief A struct to hold data for one line response @@ -100,7 +101,7 @@ public: std::optional peer; bool ignoreDefault = false; // TODO: document // https://github.com/XRPLF/xrpl-dev-portal/issues/1839 - uint32_t limit = LIMIT_DEFAULT; + uint32_t limit = kLIMIT_DEFAULT; std::optional marker; }; @@ -124,29 +125,29 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const rpcSpec = RpcSpec{ + static auto const kRPC_SPEC = RpcSpec{ {JS(account), validation::Required{}, meta::WithCustomError{ - validation::CustomValidators::AccountValidator, Status(RippledError::rpcACT_MALFORMED) + validation::CustomValidators::accountValidator, Status(RippledError::rpcACT_MALFORMED) }}, {JS(peer), meta::WithCustomError{ - validation::CustomValidators::AccountValidator, Status(RippledError::rpcACT_MALFORMED) + validation::CustomValidators::accountValidator, Status(RippledError::rpcACT_MALFORMED) }}, {JS(ignore_default), validation::Type{}}, - {JS(ledger_hash), validation::CustomValidators::Uint256HexStringValidator}, + {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, {JS(limit), validation::Type{}, validation::Min(1u), - modifiers::Clamp{LIMIT_MIN, LIMIT_MAX}}, - {JS(ledger_index), validation::CustomValidators::LedgerIndexValidator}, - {JS(marker), validation::CustomValidators::AccountMarkerValidator}, + modifiers::Clamp{kLIMIT_MIN, kLIMIT_MAX}}, + {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, + {JS(marker), validation::CustomValidators::accountMarkerValidator}, {JS(ledger), check::Deprecated{}}, {"peer_index", check::Deprecated{}}, }; - return rpcSpec; + return kRPC_SPEC; } /** diff --git a/src/rpc/handlers/AccountNFTs.hpp b/src/rpc/handlers/AccountNFTs.hpp index a5ebe6ad..6999c1a6 100644 --- a/src/rpc/handlers/AccountNFTs.hpp +++ b/src/rpc/handlers/AccountNFTs.hpp @@ -47,9 +47,9 @@ class AccountNFTsHandler { std::shared_ptr sharedPtrBackend_; public: - static auto constexpr LIMIT_MIN = 20; - static auto constexpr LIMIT_MAX = 400; - static auto constexpr LIMIT_DEFAULT = 100; + static constexpr auto kLIMIT_MIN = 20; + static constexpr auto kLIMIT_MAX = 400; + static constexpr auto kLIMIT_DEFAULT = 100; /** * @brief A struct to hold the output data of the command @@ -72,7 +72,7 @@ public: std::string account; std::optional ledgerHash; std::optional ledgerIndex; - uint32_t limit = LIMIT_DEFAULT; // Limit the number of token pages to retrieve. [20,400] + uint32_t limit = kLIMIT_DEFAULT; // Limit the number of token pages to retrieve. [20,400] std::optional marker; }; @@ -96,18 +96,18 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const rpcSpec = RpcSpec{ - {JS(account), validation::Required{}, validation::CustomValidators::AccountValidator}, - {JS(ledger_hash), validation::CustomValidators::Uint256HexStringValidator}, - {JS(ledger_index), validation::CustomValidators::LedgerIndexValidator}, - {JS(marker), validation::CustomValidators::Uint256HexStringValidator}, + static auto const kRPC_SPEC = RpcSpec{ + {JS(account), validation::Required{}, validation::CustomValidators::accountValidator}, + {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, + {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, + {JS(marker), validation::CustomValidators::uint256HexStringValidator}, {JS(limit), validation::Type{}, validation::Min(1u), - modifiers::Clamp{LIMIT_MIN, LIMIT_MAX}}, + modifiers::Clamp{kLIMIT_MIN, kLIMIT_MAX}}, }; - return rpcSpec; + return kRPC_SPEC; } /** diff --git a/src/rpc/handlers/AccountObjects.cpp b/src/rpc/handlers/AccountObjects.cpp index e6d60127..cc720e7d 100644 --- a/src/rpc/handlers/AccountObjects.cpp +++ b/src/rpc/handlers/AccountObjects.cpp @@ -73,7 +73,7 @@ AccountObjectsHandler::process(AccountObjectsHandler::Input input, Context const if (input.deletionBlockersOnly) { typeFilter.emplace(); - auto const& deletionBlockers = util::LedgerTypes::GetDeletionBlockerLedgerTypes(); + auto const& deletionBlockers = util::LedgerTypes::getDeletionBlockerLedgerTypes(); typeFilter->reserve(deletionBlockers.size()); for (auto type : deletionBlockers) { @@ -161,7 +161,7 @@ tag_invoke(boost::json::value_to_tag, boost::json: } if (jsonObject.contains(JS(type))) - input.type = util::LedgerTypes::GetLedgerEntryTypeFromStr(boost::json::value_to(jv.at(JS(type)))); + input.type = util::LedgerTypes::getLedgerEntryTypeFromStr(boost::json::value_to(jv.at(JS(type)))); if (jsonObject.contains(JS(limit))) input.limit = jv.at(JS(limit)).as_int64(); diff --git a/src/rpc/handlers/AccountObjects.hpp b/src/rpc/handlers/AccountObjects.hpp index c52f94f9..5945dbf2 100644 --- a/src/rpc/handlers/AccountObjects.hpp +++ b/src/rpc/handlers/AccountObjects.hpp @@ -56,9 +56,9 @@ class AccountObjectsHandler { std::shared_ptr sharedPtrBackend_; public: - static auto constexpr LIMIT_MIN = 10; - static auto constexpr LIMIT_MAX = 400; - static auto constexpr LIMIT_DEFAULT = 200; + static constexpr auto kLIMIT_MIN = 10; + static constexpr auto kLIMIT_MAX = 400; + static constexpr auto kLIMIT_DEFAULT = 200; /** * @brief A struct to hold the output data of the command @@ -80,7 +80,7 @@ public: std::string account; std::optional ledgerHash; std::optional ledgerIndex; - uint32_t limit = LIMIT_DEFAULT; // [10,400] + uint32_t limit = kLIMIT_DEFAULT; // [10,400] std::optional marker; std::optional type; bool deletionBlockersOnly = false; @@ -107,23 +107,23 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - auto const& accountOwnedTypes = util::LedgerTypes::GetAccountOwnedLedgerTypeStrList(); - static auto const rpcSpec = RpcSpec{ - {JS(account), validation::Required{}, validation::CustomValidators::AccountValidator}, - {JS(ledger_hash), validation::CustomValidators::Uint256HexStringValidator}, - {JS(ledger_index), validation::CustomValidators::LedgerIndexValidator}, + auto const& accountOwnedTypes = util::LedgerTypes::getAccountOwnedLedgerTypeStrList(); + static auto const kRPC_SPEC = RpcSpec{ + {JS(account), validation::Required{}, validation::CustomValidators::accountValidator}, + {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, + {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, {JS(limit), validation::Type{}, validation::Min(1u), - modifiers::Clamp(LIMIT_MIN, LIMIT_MAX)}, + modifiers::Clamp(kLIMIT_MIN, kLIMIT_MAX)}, {JS(type), validation::Type{}, validation::OneOf(accountOwnedTypes.cbegin(), accountOwnedTypes.cend())}, - {JS(marker), validation::CustomValidators::AccountMarkerValidator}, + {JS(marker), validation::CustomValidators::accountMarkerValidator}, {JS(deletion_blockers_only), validation::Type{}}, }; - return rpcSpec; + return kRPC_SPEC; } /** diff --git a/src/rpc/handlers/AccountOffers.hpp b/src/rpc/handlers/AccountOffers.hpp index e8652649..a53ea29e 100644 --- a/src/rpc/handlers/AccountOffers.hpp +++ b/src/rpc/handlers/AccountOffers.hpp @@ -50,9 +50,9 @@ class AccountOffersHandler { std::shared_ptr sharedPtrBackend_; public: - static auto constexpr LIMIT_MIN = 10; - static auto constexpr LIMIT_MAX = 400; - static auto constexpr LIMIT_DEFAULT = 200; + static constexpr auto kLIMIT_MIN = 10; + static constexpr auto kLIMIT_MAX = 400; + static constexpr auto kLIMIT_DEFAULT = 200; /** * @brief A struct to hold data for one offer response @@ -86,7 +86,7 @@ public: std::string account; std::optional ledgerHash; std::optional ledgerIndex; - uint32_t limit = LIMIT_DEFAULT; + uint32_t limit = kLIMIT_DEFAULT; std::optional marker; }; @@ -111,20 +111,20 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const rpcSpec = RpcSpec{ - {JS(account), validation::Required{}, validation::CustomValidators::AccountValidator}, - {JS(ledger_hash), validation::CustomValidators::Uint256HexStringValidator}, - {JS(ledger_index), validation::CustomValidators::LedgerIndexValidator}, - {JS(marker), validation::CustomValidators::AccountMarkerValidator}, + static auto const kRPC_SPEC = RpcSpec{ + {JS(account), validation::Required{}, validation::CustomValidators::accountValidator}, + {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, + {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, + {JS(marker), validation::CustomValidators::accountMarkerValidator}, {JS(limit), validation::Type{}, validation::Min(1u), - modifiers::Clamp{LIMIT_MIN, LIMIT_MAX}}, + modifiers::Clamp{kLIMIT_MIN, kLIMIT_MAX}}, {JS(ledger), check::Deprecated{}}, {JS(strict), check::Deprecated{}}, }; - return rpcSpec; + return kRPC_SPEC; } /** diff --git a/src/rpc/handlers/AccountTx.cpp b/src/rpc/handlers/AccountTx.cpp index 5339cb49..9b9c68ad 100644 --- a/src/rpc/handlers/AccountTx.cpp +++ b/src/rpc/handlers/AccountTx.cpp @@ -120,7 +120,7 @@ AccountTxHandler::process(AccountTxHandler::Input input, Context const& ctx) con } } - auto const limit = input.limit.value_or(LIMIT_DEFAULT); + auto const limit = input.limit.value_or(kLIMIT_DEFAULT); auto const accountID = accountFromStringStrict(input.account); auto const [txnsAndCursor, timeDiff] = util::timed([&]() { return sharedPtrBackend_->fetchAccountTransactions(*accountID, limit, input.forward, cursor, ctx.yield); diff --git a/src/rpc/handlers/AccountTx.hpp b/src/rpc/handlers/AccountTx.hpp index 2fdcda6a..712ff82c 100644 --- a/src/rpc/handlers/AccountTx.hpp +++ b/src/rpc/handlers/AccountTx.hpp @@ -58,8 +58,8 @@ class AccountTxHandler { public: // no max limit - static auto constexpr LIMIT_MIN = 1; - static auto constexpr LIMIT_DEFAULT = 200; + static constexpr auto kLIMIT_MIN = 1; + static constexpr auto kLIMIT_DEFAULT = 200; /** * @brief A struct to hold the marker data @@ -124,16 +124,16 @@ public: spec([[maybe_unused]] uint32_t apiVersion) { auto const& typesKeysInLowercase = util::getTxTypesInLowercase(); - static auto const rpcSpecForV1 = RpcSpec{ - {JS(account), validation::Required{}, validation::CustomValidators::AccountValidator}, - {JS(ledger_hash), validation::CustomValidators::Uint256HexStringValidator}, - {JS(ledger_index), validation::CustomValidators::LedgerIndexValidator}, + static auto const kRPC_SPEC_FOR_V1 = RpcSpec{ + {JS(account), validation::Required{}, validation::CustomValidators::accountValidator}, + {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, + {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, {JS(ledger_index_min), validation::Type{}}, {JS(ledger_index_max), validation::Type{}}, {JS(limit), validation::Type{}, validation::Min(1u), - modifiers::Clamp{LIMIT_MIN, std::numeric_limits::max()}}, + modifiers::Clamp{kLIMIT_MIN, std::numeric_limits::max()}}, {JS(marker), meta::WithCustomError{ validation::Type{}, @@ -151,15 +151,15 @@ public: }, }; - static auto const rpcSpec = RpcSpec{ - rpcSpecForV1, + static auto const kRPC_SPEC = RpcSpec{ + kRPC_SPEC_FOR_V1, { {JS(binary), validation::Type{}}, {JS(forward), validation::Type{}}, } }; - return apiVersion == 1 ? rpcSpecForV1 : rpcSpec; + return apiVersion == 1 ? kRPC_SPEC_FOR_V1 : kRPC_SPEC; } /** diff --git a/src/rpc/handlers/BookChanges.hpp b/src/rpc/handlers/BookChanges.hpp index d8db9580..1d2b1a39 100644 --- a/src/rpc/handlers/BookChanges.hpp +++ b/src/rpc/handlers/BookChanges.hpp @@ -88,12 +88,12 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const rpcSpec = RpcSpec{ - {JS(ledger_hash), validation::CustomValidators::Uint256HexStringValidator}, - {JS(ledger_index), validation::CustomValidators::LedgerIndexValidator}, + static auto const kRPC_SPEC = RpcSpec{ + {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, + {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, }; - return rpcSpec; + return kRPC_SPEC; } /** diff --git a/src/rpc/handlers/BookOffers.hpp b/src/rpc/handlers/BookOffers.hpp index a5c186fd..01d2b253 100644 --- a/src/rpc/handlers/BookOffers.hpp +++ b/src/rpc/handlers/BookOffers.hpp @@ -53,9 +53,9 @@ class BookOffersHandler { std::shared_ptr sharedPtrBackend_; public: - static auto constexpr LIMIT_MIN = 1; - static auto constexpr LIMIT_MAX = 100; - static auto constexpr LIMIT_DEFAULT = 60; + static constexpr auto kLIMIT_MIN = 1; + static constexpr auto kLIMIT_MAX = 100; + static constexpr auto kLIMIT_DEFAULT = 60; /** * @brief A struct to hold the output data of the command @@ -76,7 +76,7 @@ public: struct Input { std::optional ledgerHash; std::optional ledgerIndex; - uint32_t limit = LIMIT_DEFAULT; + uint32_t limit = kLIMIT_DEFAULT; std::optional taker; ripple::Currency paysCurrency; ripple::Currency getsCurrency; @@ -105,7 +105,7 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const rpcSpec = RpcSpec{ + static auto const kRPC_SPEC = RpcSpec{ {JS(taker_gets), validation::Required{}, validation::Type{}, @@ -113,11 +113,11 @@ public: {JS(currency), validation::Required{}, meta::WithCustomError{ - validation::CustomValidators::CurrencyValidator, Status(RippledError::rpcDST_AMT_MALFORMED) + validation::CustomValidators::currencyValidator, Status(RippledError::rpcDST_AMT_MALFORMED) }}, {JS(issuer), meta::WithCustomError{ - validation::CustomValidators::IssuerValidator, Status(RippledError::rpcDST_ISR_MALFORMED) + validation::CustomValidators::issuerValidator, Status(RippledError::rpcDST_ISR_MALFORMED) }} }}, {JS(taker_pays), @@ -127,28 +127,28 @@ public: {JS(currency), validation::Required{}, meta::WithCustomError{ - validation::CustomValidators::CurrencyValidator, Status(RippledError::rpcSRC_CUR_MALFORMED) + validation::CustomValidators::currencyValidator, Status(RippledError::rpcSRC_CUR_MALFORMED) }}, {JS(issuer), meta::WithCustomError{ - validation::CustomValidators::IssuerValidator, Status(RippledError::rpcSRC_ISR_MALFORMED) + validation::CustomValidators::issuerValidator, Status(RippledError::rpcSRC_ISR_MALFORMED) }} }}, // return INVALID_PARAMS if account format is wrong for "taker" {JS(taker), meta::WithCustomError{ - validation::CustomValidators::AccountValidator, + validation::CustomValidators::accountValidator, Status(RippledError::rpcINVALID_PARAMS, "Invalid field 'taker'.") }}, {JS(limit), validation::Type{}, validation::Min(1u), - modifiers::Clamp{LIMIT_MIN, LIMIT_MAX}}, - {JS(ledger_hash), validation::CustomValidators::Uint256HexStringValidator}, - {JS(ledger_index), validation::CustomValidators::LedgerIndexValidator}, + modifiers::Clamp{kLIMIT_MIN, kLIMIT_MAX}}, + {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, + {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, }; - return rpcSpec; + return kRPC_SPEC; } /** diff --git a/src/rpc/handlers/DepositAuthorized.hpp b/src/rpc/handlers/DepositAuthorized.hpp index 5383962a..15e7a365 100644 --- a/src/rpc/handlers/DepositAuthorized.hpp +++ b/src/rpc/handlers/DepositAuthorized.hpp @@ -99,15 +99,15 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const rpcSpec = RpcSpec{ - {JS(source_account), validation::Required{}, validation::CustomValidators::AccountValidator}, - {JS(destination_account), validation::Required{}, validation::CustomValidators::AccountValidator}, - {JS(ledger_hash), validation::CustomValidators::Uint256HexStringValidator}, - {JS(ledger_index), validation::CustomValidators::LedgerIndexValidator}, + static auto const kRPC_SPEC = RpcSpec{ + {JS(source_account), validation::Required{}, validation::CustomValidators::accountValidator}, + {JS(destination_account), validation::Required{}, validation::CustomValidators::accountValidator}, + {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, + {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, {JS(credentials), validation::Type{}, validation::Hex256ItemType()} }; - return rpcSpec; + return kRPC_SPEC; } /** diff --git a/src/rpc/handlers/Feature.cpp b/src/rpc/handlers/Feature.cpp index fc21eea8..6a3d2f32 100644 --- a/src/rpc/handlers/Feature.cpp +++ b/src/rpc/handlers/Feature.cpp @@ -112,17 +112,17 @@ FeatureHandler::process(FeatureHandler::Input input, Context const& ctx) const RpcSpecConstRef FeatureHandler::spec([[maybe_unused]] uint32_t apiVersion) { - static RpcSpec const rpcSpec = { + static RpcSpec const kRPC_SPEC = { {JS(feature), validation::Type{}}, {JS(vetoed), meta::WithCustomError{ validation::NotSupported{}, Status(RippledError::rpcNO_PERMISSION, "The admin portion of feature API is not available through Clio.") }}, - {JS(ledger_hash), validation::CustomValidators::Uint256HexStringValidator}, - {JS(ledger_index), validation::CustomValidators::LedgerIndexValidator}, + {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, + {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, }; - return rpcSpec; + return kRPC_SPEC; } void diff --git a/src/rpc/handlers/GatewayBalances.cpp b/src/rpc/handlers/GatewayBalances.cpp index 3695d061..93f89dde 100644 --- a/src/rpc/handlers/GatewayBalances.cpp +++ b/src/rpc/handlers/GatewayBalances.cpp @@ -147,7 +147,7 @@ GatewayBalancesHandler::process(GatewayBalancesHandler::Input input, Context con auto inHotbalances = [&](auto const& hw) { return output.hotBalances.contains(hw); }; if (not std::ranges::all_of(input.hotWallets, inHotbalances)) - return Error{Status{ClioError::rpcINVALID_HOT_WALLET}}; + return Error{Status{ClioError::RpcInvalidHotWallet}}; output.accountID = input.account; output.ledgerHash = ripple::strHex(lgrInfo.hash); diff --git a/src/rpc/handlers/GatewayBalances.hpp b/src/rpc/handlers/GatewayBalances.hpp index adc9023b..2822c64c 100644 --- a/src/rpc/handlers/GatewayBalances.hpp +++ b/src/rpc/handlers/GatewayBalances.hpp @@ -108,7 +108,7 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const hotWalletValidator = + static auto const kHOT_WALLET_VALIDATOR = validation::CustomValidator{[](boost::json::value const& value, std::string_view key) -> MaybeError { if (!value.is_string() && !value.is_array()) return Error{Status{RippledError::rpcINVALID_PARAMS, std::string(key) + "NotStringOrArray"}}; @@ -138,14 +138,14 @@ public: return MaybeError{}; }}; - static auto const rpcSpec = RpcSpec{ - {JS(account), validation::Required{}, validation::CustomValidators::AccountValidator}, - {JS(ledger_hash), validation::CustomValidators::Uint256HexStringValidator}, - {JS(ledger_index), validation::CustomValidators::LedgerIndexValidator}, - {JS(hotwallet), hotWalletValidator} + static auto const kRPC_SPEC = RpcSpec{ + {JS(account), validation::Required{}, validation::CustomValidators::accountValidator}, + {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, + {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, + {JS(hotwallet), kHOT_WALLET_VALIDATOR} }; - return rpcSpec; + return kRPC_SPEC; } /** diff --git a/src/rpc/handlers/GetAggregatePrice.cpp b/src/rpc/handlers/GetAggregatePrice.cpp index 525bdec6..fcf2a8f5 100644 --- a/src/rpc/handlers/GetAggregatePrice.cpp +++ b/src/rpc/handlers/GetAggregatePrice.cpp @@ -174,11 +174,11 @@ GetAggregatePriceHandler::process(GetAggregatePriceHandler::Input input, Context auto const median = [&, size = out.extireStats.size]() { auto const middle = size / 2; if ((size % 2) == 0) { - static ripple::STAmount const two{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, two, ripple::noIssue()); + return divide(a1 + a2, kTWO, ripple::noIssue()); } return itAdvance(timestampPricesBiMap.right.begin(), middle)->first; }(); @@ -194,7 +194,7 @@ GetAggregatePriceHandler::tracebackOracleObject( std::function const& callback ) const { - static auto constexpr HISTORY_MAX = 3; + static constexpr auto kHISTORY_MAX = 3; std::optional optOracleObject = oracleObject; std::optional optCurrentObject = optOracleObject; @@ -212,7 +212,7 @@ GetAggregatePriceHandler::tracebackOracleObject( if (callback(*optOracleObject) or isNew) return; - if (++history > HISTORY_MAX) + if (++history > kHISTORY_MAX) return; auto const prevTxIndex = optCurrentObject->getFieldH256(ripple::sfPreviousTxnID); diff --git a/src/rpc/handlers/GetAggregatePrice.hpp b/src/rpc/handlers/GetAggregatePrice.hpp index 73a5d6f3..ace044e3 100644 --- a/src/rpc/handlers/GetAggregatePrice.hpp +++ b/src/rpc/handlers/GetAggregatePrice.hpp @@ -130,11 +130,11 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto constexpr ORACLES_MAX = 200; + static constexpr auto kORACLES_MAX = 200; - static auto const oraclesValidator = + static auto const kORACLES_VALIDATOR = modifiers::CustomModifier{[](boost::json::value& value, std::string_view) -> MaybeError { - if (!value.is_array() or value.as_array().empty() or value.as_array().size() > ORACLES_MAX) + if (!value.is_array() or value.as_array().empty() or value.as_array().size() > kORACLES_MAX) return Error{Status{RippledError::rpcORACLE_MALFORMED}}; for (auto& oracle : value.as_array()) { @@ -153,7 +153,7 @@ public: return maybeError; maybeError = - validation::CustomValidators::AccountBase58Validator.verify(oracle.as_object(), JS(account)); + validation::CustomValidators::accountBase58Validator.verify(oracle.as_object(), JS(account)); if (!maybeError) return Error{Status{RippledError::rpcINVALID_PARAMS}}; }; @@ -161,23 +161,23 @@ public: return MaybeError{}; }}; - static auto const rpcSpec = RpcSpec{ - {JS(ledger_hash), validation::CustomValidators::Uint256HexStringValidator}, - {JS(ledger_index), validation::CustomValidators::LedgerIndexValidator}, + static auto const kRPC_SPEC = 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 doc: // https://xrpl.org/docs/references/protocol/data-types/currency-formats#currency-codes // usually Clio returns rpcMALFORMED_CURRENCY , return InvalidParam here just to mimic rippled {JS(base_asset), validation::Required{}, meta::WithCustomError{ - validation::CustomValidators::CurrencyValidator, Status(RippledError::rpcINVALID_PARAMS) + validation::CustomValidators::currencyValidator, Status(RippledError::rpcINVALID_PARAMS) }}, {JS(quote_asset), validation::Required{}, meta::WithCustomError{ - validation::CustomValidators::CurrencyValidator, Status(RippledError::rpcINVALID_PARAMS) + validation::CustomValidators::currencyValidator, Status(RippledError::rpcINVALID_PARAMS) }}, - {JS(oracles), validation::Required{}, oraclesValidator}, + {JS(oracles), validation::Required{}, kORACLES_VALIDATOR}, // note: Unlike `rippled`, Clio only supports UInt as input, no string, no `null`, etc. {JS(time_threshold), validation::Type{}}, { @@ -187,7 +187,7 @@ public: } }; - return rpcSpec; + return kRPC_SPEC; } /** diff --git a/src/rpc/handlers/Ledger.hpp b/src/rpc/handlers/Ledger.hpp index 13b83397..b507dd70 100644 --- a/src/rpc/handlers/Ledger.hpp +++ b/src/rpc/handlers/Ledger.hpp @@ -103,15 +103,15 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const rpcSpec = RpcSpec{ + static auto const kRPC_SPEC = RpcSpec{ {JS(full), validation::Type{}, validation::NotSupported{true}}, {JS(full), check::Deprecated{}}, {JS(accounts), validation::Type{}, validation::NotSupported{true}}, {JS(accounts), check::Deprecated{}}, {JS(owner_funds), validation::Type{}}, {JS(queue), validation::Type{}, validation::NotSupported{true}}, - {JS(ledger_hash), validation::CustomValidators::Uint256HexStringValidator}, - {JS(ledger_index), validation::CustomValidators::LedgerIndexValidator}, + {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, + {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, {JS(transactions), validation::Type{}}, {JS(expand), validation::Type{}}, {JS(binary), validation::Type{}}, @@ -120,7 +120,7 @@ public: {JS(type), check::Deprecated{}}, }; - return rpcSpec; + return kRPC_SPEC; } /** diff --git a/src/rpc/handlers/LedgerData.cpp b/src/rpc/handlers/LedgerData.cpp index 3b97015f..0b6d396e 100644 --- a/src/rpc/handlers/LedgerData.cpp +++ b/src/rpc/handlers/LedgerData.cpp @@ -113,7 +113,7 @@ LedgerDataHandler::process(Input input, Context const& ctx) const // limit's limitation is different based on binary or json // framework can not handler the check right now, adjust the value here auto const limit = - std::min(input.limit, input.binary ? LedgerDataHandler::LIMITBINARY : LedgerDataHandler::LIMITJSON); + std::min(input.limit, input.binary ? LedgerDataHandler::kLIMIT_BINARY : LedgerDataHandler::kLIMIT_JSON); auto page = sharedPtrBackend_->fetchLedgerPage(input.marker, lgrInfo.seq, limit, input.outOfOrder, ctx.yield); results = std::move(page.objects); @@ -189,7 +189,7 @@ tag_invoke(boost::json::value_to_tag, boost::json::val if (jsonObject.contains(JS(binary))) { input.binary = jsonObject.at(JS(binary)).as_bool(); - input.limit = input.binary ? LedgerDataHandler::LIMITBINARY : LedgerDataHandler::LIMITJSON; + input.limit = input.binary ? LedgerDataHandler::kLIMIT_BINARY : LedgerDataHandler::kLIMIT_JSON; } if (jsonObject.contains(JS(limit))) @@ -218,7 +218,7 @@ tag_invoke(boost::json::value_to_tag, boost::json::val } if (jsonObject.contains(JS(type))) - input.type = util::LedgerTypes::GetLedgerEntryTypeFromStr(boost::json::value_to(jv.at(JS(type)))); + input.type = util::LedgerTypes::getLedgerEntryTypeFromStr(boost::json::value_to(jv.at(JS(type)))); return input; } diff --git a/src/rpc/handlers/LedgerData.hpp b/src/rpc/handlers/LedgerData.hpp index 1932f684..d7938ccb 100644 --- a/src/rpc/handlers/LedgerData.hpp +++ b/src/rpc/handlers/LedgerData.hpp @@ -59,8 +59,8 @@ class LedgerDataHandler { public: // constants - static uint32_t constexpr LIMITBINARY = 2048; - static uint32_t constexpr LIMITJSON = 256; + static constexpr uint32_t kLIMIT_BINARY = 2048; + static constexpr uint32_t kLIMIT_JSON = 256; /** * @brief A struct to hold the output data of the command @@ -86,7 +86,7 @@ public: std::optional ledgerHash; std::optional ledgerIndex; bool binary = false; - uint32_t limit = LedgerDataHandler::LIMITJSON; // max 256 for json ; 2048 for binary + uint32_t limit = LedgerDataHandler::kLIMIT_JSON; // max 256 for json ; 2048 for binary std::optional marker; std::optional diffMarker; bool outOfOrder = false; @@ -113,16 +113,16 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - auto const& ledgerTypeStrs = util::LedgerTypes::GetLedgerEntryTypeStrList(); - static auto const rpcSpec = RpcSpec{ + auto const& ledgerTypeStrs = util::LedgerTypes::getLedgerEntryTypeStrList(); + static auto const kRPC_SPEC = RpcSpec{ {JS(binary), validation::Type{}}, {"out_of_order", validation::Type{}}, - {JS(ledger_hash), validation::CustomValidators::Uint256HexStringValidator}, - {JS(ledger_index), validation::CustomValidators::LedgerIndexValidator}, + {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, + {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, {JS(limit), validation::Type{}, validation::Min(1u)}, {JS(marker), validation::Type{}, - meta::IfType{validation::CustomValidators::Uint256HexStringValidator}}, + meta::IfType{validation::CustomValidators::uint256HexStringValidator}}, {JS(type), meta::WithCustomError{ validation::Type{}, Status{ripple::rpcINVALID_PARAMS, "Invalid field 'type', not string."} @@ -130,7 +130,7 @@ public: validation::OneOf(ledgerTypeStrs.cbegin(), ledgerTypeStrs.cend())}, {JS(ledger), check::Deprecated{}}, }; - return rpcSpec; + return kRPC_SPEC; } /** diff --git a/src/rpc/handlers/LedgerEntry.cpp b/src/rpc/handlers/LedgerEntry.cpp index a39470af..36ff6156 100644 --- a/src/rpc/handlers/LedgerEntry.cpp +++ b/src/rpc/handlers/LedgerEntry.cpp @@ -104,7 +104,7 @@ LedgerEntryHandler::process(LedgerEntryHandler::Input input, Context const& ctx) if (input.depositPreauth->contains(JS(authorized)) == input.depositPreauth->contains(JS(authorized_credentials))) { return Error{ - Status{ClioError::rpcMALFORMED_REQUEST, "Must have one of authorized or authorized_credentials."} + Status{ClioError::RpcMalformedRequest, "Must have one of authorized or authorized_credentials."} }; } @@ -120,7 +120,7 @@ LedgerEntryHandler::process(LedgerEntryHandler::Input input, Context const& ctx) auto const authCreds = credentials::createAuthCredentials(authorizedCredentials); if (authCreds.size() != authorizedCredentials.size()) - return Error{Status{ClioError::rpcMALFORMED_AUTHORIZED_CREDENTIALS, "duplicates in credentials."}}; + return Error{Status{ClioError::RpcMalformedAuthorizedCredentials, "duplicates in credentials."}}; key = ripple::keylet::depositPreauth(owner.value(), authCreds).key; } @@ -149,14 +149,14 @@ LedgerEntryHandler::process(LedgerEntryHandler::Input input, Context const& ctx) .key; } else if (input.bridge) { if (!input.bridgeAccount && !input.chainClaimId && !input.createAccountClaimId) - return Error{Status{ClioError::rpcMALFORMED_REQUEST}}; + return Error{Status{ClioError::RpcMalformedRequest}}; if (input.bridgeAccount) { auto const bridgeAccount = util::parseBase58Wrapper(*(input.bridgeAccount)); auto const chainType = ripple::STXChainBridge::srcChain(bridgeAccount == input.bridge->lockingChainDoor()); if (bridgeAccount != input.bridge->door(chainType)) - return Error{Status{ClioError::rpcMALFORMED_REQUEST}}; + return Error{Status{ClioError::RpcMalformedRequest}}; key = ripple::keylet::bridge(input.bridge->value(), chainType).key; } else if (input.chainClaimId) { @@ -182,7 +182,7 @@ LedgerEntryHandler::process(LedgerEntryHandler::Input input, Context const& ctx) } else { // Must specify 1 of the following fields to indicate what type if (ctx.apiVersion == 1) - return Error{Status{ClioError::rpcUNKNOWN_OPTION}}; + return Error{Status{ClioError::RpcUnknownOption}}; return Error{Status{RippledError::rpcINVALID_PARAMS}}; } @@ -297,7 +297,7 @@ tag_invoke(boost::json::value_to_tag, boost::json::va input.binary = jv.at(JS(binary)).as_bool(); // check all the protential index - static auto const indexFieldTypeMap = std::unordered_map{ + static auto const kINDEX_FIELD_TYPE_MAP = std::unordered_map{ {JS(index), ripple::ltANY}, {JS(directory), ripple::ltDIR_NODE}, {JS(offer), ripple::ltOFFER}, @@ -348,12 +348,12 @@ tag_invoke(boost::json::value_to_tag, boost::json::va return ripple::keylet::credential(*subject, *issuer, ripple::Slice(credType->data(), credType->size())).key; }; - auto const indexFieldType = std::ranges::find_if(indexFieldTypeMap, [&jsonObject](auto const& pair) { + auto const indexFieldType = std::ranges::find_if(kINDEX_FIELD_TYPE_MAP, [&jsonObject](auto const& pair) { auto const& [field, _] = pair; return jsonObject.contains(field) && jsonObject.at(field).is_string(); }); - if (indexFieldType != indexFieldTypeMap.end()) { + if (indexFieldType != kINDEX_FIELD_TYPE_MAP.end()) { input.index = boost::json::value_to(jv.at(indexFieldType->first)); input.expectedType = indexFieldType->second; } diff --git a/src/rpc/handlers/LedgerEntry.hpp b/src/rpc/handlers/LedgerEntry.hpp index 87980b75..a6ab89ee 100644 --- a/src/rpc/handlers/LedgerEntry.hpp +++ b/src/rpc/handlers/LedgerEntry.hpp @@ -135,7 +135,7 @@ public: // Validator only works in this handler // The accounts array must have two different elements // Each element must be a valid address - static auto const rippleStateAccountsCheck = + static auto const kRIPPLE_STATE_ACCOUNTS_CHECK = validation::CustomValidator{[](boost::json::value const& value, std::string_view /* key */) -> MaybeError { if (!value.is_array() || value.as_array().size() != 2 || !value.as_array()[0].is_string() || !value.as_array()[1].is_string() || @@ -151,225 +151,225 @@ public: ); if (!id1 || !id2) - return Error{Status{ClioError::rpcMALFORMED_ADDRESS, "malformedAddresses"}}; + return Error{Status{ClioError::RpcMalformedAddress, "malformedAddresses"}}; return MaybeError{}; }}; - static auto const malformedRequestHexStringValidator = meta::WithCustomError{ - validation::CustomValidators::Uint256HexStringValidator, Status(ClioError::rpcMALFORMED_REQUEST) + static auto const kMALFORMED_REQUEST_HEX_STRING_VALIDATOR = meta::WithCustomError{ + validation::CustomValidators::uint256HexStringValidator, Status(ClioError::RpcMalformedRequest) }; - static auto const malformedRequestIntValidator = - meta::WithCustomError{validation::Type{}, Status(ClioError::rpcMALFORMED_REQUEST)}; + static auto const kMALFORMED_REQUEST_INT_VALIDATOR = + meta::WithCustomError{validation::Type{}, Status(ClioError::RpcMalformedRequest)}; - static auto const bridgeJsonValidator = meta::WithCustomError{ + static auto const kBRIDGE_JSON_VALIDATOR = meta::WithCustomError{ meta::IfType{meta::Section{ {ripple::sfLockingChainDoor.getJsonName().c_str(), validation::Required{}, - validation::CustomValidators::AccountBase58Validator}, + validation::CustomValidators::accountBase58Validator}, {ripple::sfIssuingChainDoor.getJsonName().c_str(), validation::Required{}, - validation::CustomValidators::AccountBase58Validator}, + validation::CustomValidators::accountBase58Validator}, {ripple::sfLockingChainIssue.getJsonName().c_str(), validation::Required{}, - validation::CustomValidators::CurrencyIssueValidator}, + validation::CustomValidators::currencyIssueValidator}, {ripple::sfIssuingChainIssue.getJsonName().c_str(), validation::Required{}, - validation::CustomValidators::CurrencyIssueValidator}, + validation::CustomValidators::currencyIssueValidator}, }}, - Status(ClioError::rpcMALFORMED_REQUEST) + Status(ClioError::RpcMalformedRequest) }; - static auto const rpcSpec = RpcSpec{ + static auto const kRPC_SPEC = RpcSpec{ {JS(binary), validation::Type{}}, - {JS(ledger_hash), validation::CustomValidators::Uint256HexStringValidator}, - {JS(ledger_index), validation::CustomValidators::LedgerIndexValidator}, - {JS(index), malformedRequestHexStringValidator}, - {JS(account_root), validation::CustomValidators::AccountBase58Validator}, - {JS(did), validation::CustomValidators::AccountBase58Validator}, - {JS(check), malformedRequestHexStringValidator}, + {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, + {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, + {JS(index), kMALFORMED_REQUEST_HEX_STRING_VALIDATOR}, + {JS(account_root), validation::CustomValidators::accountBase58Validator}, + {JS(did), validation::CustomValidators::accountBase58Validator}, + {JS(check), kMALFORMED_REQUEST_HEX_STRING_VALIDATOR}, {JS(deposit_preauth), validation::Type{}, - meta::IfType{malformedRequestHexStringValidator}, + meta::IfType{kMALFORMED_REQUEST_HEX_STRING_VALIDATOR}, meta::IfType{ meta::Section{ {JS(owner), validation::Required{}, meta::WithCustomError{ - validation::CustomValidators::AccountBase58Validator, Status(ClioError::rpcMALFORMED_OWNER) + validation::CustomValidators::accountBase58Validator, Status(ClioError::RpcMalformedOwner) }}, - {JS(authorized), validation::CustomValidators::AccountBase58Validator}, - {JS(authorized_credentials), validation::CustomValidators::AuthorizeCredentialValidator} + {JS(authorized), validation::CustomValidators::accountBase58Validator}, + {JS(authorized_credentials), validation::CustomValidators::authorizeCredentialValidator} }, }}, {JS(directory), validation::Type{}, - meta::IfType{malformedRequestHexStringValidator}, + meta::IfType{kMALFORMED_REQUEST_HEX_STRING_VALIDATOR}, meta::IfType{meta::Section{ - {JS(owner), validation::CustomValidators::AccountBase58Validator}, - {JS(dir_root), validation::CustomValidators::Uint256HexStringValidator}, - {JS(sub_index), malformedRequestIntValidator} + {JS(owner), validation::CustomValidators::accountBase58Validator}, + {JS(dir_root), validation::CustomValidators::uint256HexStringValidator}, + {JS(sub_index), kMALFORMED_REQUEST_INT_VALIDATOR} }}}, {JS(escrow), validation::Type{}, - meta::IfType{malformedRequestHexStringValidator}, + meta::IfType{kMALFORMED_REQUEST_HEX_STRING_VALIDATOR}, meta::IfType{ meta::Section{ {JS(owner), validation::Required{}, meta::WithCustomError{ - validation::CustomValidators::AccountBase58Validator, Status(ClioError::rpcMALFORMED_OWNER) + validation::CustomValidators::accountBase58Validator, Status(ClioError::RpcMalformedOwner) }}, - {JS(seq), validation::Required{}, malformedRequestIntValidator}, + {JS(seq), validation::Required{}, kMALFORMED_REQUEST_INT_VALIDATOR}, }, }}, {JS(offer), validation::Type{}, - meta::IfType{malformedRequestHexStringValidator}, + meta::IfType{kMALFORMED_REQUEST_HEX_STRING_VALIDATOR}, meta::IfType{ meta::Section{ - {JS(account), validation::Required{}, validation::CustomValidators::AccountBase58Validator}, - {JS(seq), validation::Required{}, malformedRequestIntValidator}, + {JS(account), validation::Required{}, validation::CustomValidators::accountBase58Validator}, + {JS(seq), validation::Required{}, kMALFORMED_REQUEST_INT_VALIDATOR}, }, }}, - {JS(payment_channel), malformedRequestHexStringValidator}, + {JS(payment_channel), kMALFORMED_REQUEST_HEX_STRING_VALIDATOR}, {JS(ripple_state), validation::Type{}, meta::Section{ - {JS(accounts), validation::Required{}, rippleStateAccountsCheck}, - {JS(currency), validation::Required{}, validation::CustomValidators::CurrencyValidator}, + {JS(accounts), validation::Required{}, kRIPPLE_STATE_ACCOUNTS_CHECK}, + {JS(currency), validation::Required{}, validation::CustomValidators::currencyValidator}, }}, {JS(ticket), validation::Type{}, - meta::IfType{malformedRequestHexStringValidator}, + meta::IfType{kMALFORMED_REQUEST_HEX_STRING_VALIDATOR}, meta::IfType{ meta::Section{ - {JS(account), validation::Required{}, validation::CustomValidators::AccountBase58Validator}, - {JS(ticket_seq), validation::Required{}, malformedRequestIntValidator}, + {JS(account), validation::Required{}, validation::CustomValidators::accountBase58Validator}, + {JS(ticket_seq), validation::Required{}, kMALFORMED_REQUEST_INT_VALIDATOR}, }, }}, - {JS(nft_page), malformedRequestHexStringValidator}, + {JS(nft_page), kMALFORMED_REQUEST_HEX_STRING_VALIDATOR}, {JS(amm), validation::Type{}, - meta::IfType{malformedRequestHexStringValidator}, + meta::IfType{kMALFORMED_REQUEST_HEX_STRING_VALIDATOR}, meta::IfType{ meta::Section{ {JS(asset), - meta::WithCustomError{validation::Required{}, Status(ClioError::rpcMALFORMED_REQUEST)}, + meta::WithCustomError{validation::Required{}, Status(ClioError::RpcMalformedRequest)}, meta::WithCustomError{ - validation::Type{}, Status(ClioError::rpcMALFORMED_REQUEST) + validation::Type{}, Status(ClioError::RpcMalformedRequest) }, - validation::CustomValidators::CurrencyIssueValidator}, + validation::CustomValidators::currencyIssueValidator}, {JS(asset2), - meta::WithCustomError{validation::Required{}, Status(ClioError::rpcMALFORMED_REQUEST)}, + meta::WithCustomError{validation::Required{}, Status(ClioError::RpcMalformedRequest)}, meta::WithCustomError{ - validation::Type{}, Status(ClioError::rpcMALFORMED_REQUEST) + validation::Type{}, Status(ClioError::RpcMalformedRequest) }, - validation::CustomValidators::CurrencyIssueValidator}, + validation::CustomValidators::currencyIssueValidator}, }, }}, {JS(bridge), - meta::WithCustomError{validation::Type{}, Status(ClioError::rpcMALFORMED_REQUEST)}, - bridgeJsonValidator}, + meta::WithCustomError{validation::Type{}, Status(ClioError::RpcMalformedRequest)}, + kBRIDGE_JSON_VALIDATOR}, {JS(bridge_account), meta::WithCustomError{ - validation::CustomValidators::AccountBase58Validator, Status(ClioError::rpcMALFORMED_REQUEST) + validation::CustomValidators::accountBase58Validator, Status(ClioError::RpcMalformedRequest) }}, {JS(xchain_owned_claim_id), meta::WithCustomError{ - validation::Type{}, Status(ClioError::rpcMALFORMED_REQUEST) + validation::Type{}, Status(ClioError::RpcMalformedRequest) }, - meta::IfType{malformedRequestHexStringValidator}, - bridgeJsonValidator, + meta::IfType{kMALFORMED_REQUEST_HEX_STRING_VALIDATOR}, + kBRIDGE_JSON_VALIDATOR, meta::WithCustomError{ meta::IfType{ meta::Section{{JS(xchain_owned_claim_id), validation::Required{}, validation::Type{}}} }, - Status(ClioError::rpcMALFORMED_REQUEST) + Status(ClioError::RpcMalformedRequest) }}, {JS(xchain_owned_create_account_claim_id), meta::WithCustomError{ - validation::Type{}, Status(ClioError::rpcMALFORMED_REQUEST) + validation::Type{}, Status(ClioError::RpcMalformedRequest) }, - meta::IfType{malformedRequestHexStringValidator}, - bridgeJsonValidator, + meta::IfType{kMALFORMED_REQUEST_HEX_STRING_VALIDATOR}, + kBRIDGE_JSON_VALIDATOR, meta::WithCustomError{ meta::IfType{meta::Section{ {JS(xchain_owned_create_account_claim_id), validation::Required{}, validation::Type{}} }}, - Status(ClioError::rpcMALFORMED_REQUEST) + Status(ClioError::RpcMalformedRequest) }}, {JS(oracle), meta::WithCustomError{ - validation::Type{}, Status(ClioError::rpcMALFORMED_REQUEST) + validation::Type{}, Status(ClioError::RpcMalformedRequest) }, meta::IfType{ - meta::WithCustomError{malformedRequestHexStringValidator, Status(ClioError::rpcMALFORMED_ADDRESS)} + meta::WithCustomError{kMALFORMED_REQUEST_HEX_STRING_VALIDATOR, Status(ClioError::RpcMalformedAddress)} }, meta::IfType{meta::Section{ {JS(account), - meta::WithCustomError{validation::Required{}, Status(ClioError::rpcMALFORMED_REQUEST)}, + meta::WithCustomError{validation::Required{}, Status(ClioError::RpcMalformedRequest)}, meta::WithCustomError{ - validation::CustomValidators::AccountBase58Validator, Status(ClioError::rpcMALFORMED_ADDRESS) + validation::CustomValidators::accountBase58Validator, Status(ClioError::RpcMalformedAddress) }}, // note: Unlike `rippled`, Clio only supports UInt as input, no string, no `null`, etc.: {JS(oracle_document_id), - meta::WithCustomError{validation::Required{}, Status(ClioError::rpcMALFORMED_REQUEST)}, + meta::WithCustomError{validation::Required{}, Status(ClioError::RpcMalformedRequest)}, meta::WithCustomError{ - validation::Type{}, Status(ClioError::rpcMALFORMED_ORACLE_DOCUMENT_ID) + validation::Type{}, Status(ClioError::RpcMalformedOracleDocumentId) }, - meta::WithCustomError{modifiers::ToNumber{}, Status(ClioError::rpcMALFORMED_ORACLE_DOCUMENT_ID)}}, + meta::WithCustomError{modifiers::ToNumber{}, Status(ClioError::RpcMalformedOracleDocumentId)}}, }}}, {JS(credential), meta::WithCustomError{ - validation::Type{}, Status(ClioError::rpcMALFORMED_REQUEST) + validation::Type{}, Status(ClioError::RpcMalformedRequest) }, meta::IfType{ - meta::WithCustomError{malformedRequestHexStringValidator, Status(ClioError::rpcMALFORMED_ADDRESS)} + meta::WithCustomError{kMALFORMED_REQUEST_HEX_STRING_VALIDATOR, Status(ClioError::RpcMalformedAddress)} }, meta::IfType{meta::Section{ {JS(subject), - meta::WithCustomError{validation::Required{}, Status(ClioError::rpcMALFORMED_REQUEST)}, + meta::WithCustomError{validation::Required{}, Status(ClioError::RpcMalformedRequest)}, meta::WithCustomError{ - validation::CustomValidators::AccountBase58Validator, Status(ClioError::rpcMALFORMED_ADDRESS) + validation::CustomValidators::accountBase58Validator, Status(ClioError::RpcMalformedAddress) }}, {JS(issuer), - meta::WithCustomError{validation::Required{}, Status(ClioError::rpcMALFORMED_REQUEST)}, + meta::WithCustomError{validation::Required{}, Status(ClioError::RpcMalformedRequest)}, meta::WithCustomError{ - validation::CustomValidators::AccountBase58Validator, Status(ClioError::rpcMALFORMED_ADDRESS) + validation::CustomValidators::accountBase58Validator, Status(ClioError::RpcMalformedAddress) }}, { JS(credential_type), - meta::WithCustomError{validation::Required{}, Status(ClioError::rpcMALFORMED_REQUEST)}, - meta::WithCustomError{validation::Type{}, Status(ClioError::rpcMALFORMED_REQUEST)}, + meta::WithCustomError{validation::Required{}, Status(ClioError::RpcMalformedRequest)}, + meta::WithCustomError{validation::Type{}, Status(ClioError::RpcMalformedRequest)}, }, }}}, {JS(mpt_issuance), meta::WithCustomError{ - validation::CustomValidators::Uint192HexStringValidator, Status(ClioError::rpcMALFORMED_REQUEST) + validation::CustomValidators::uint192HexStringValidator, Status(ClioError::RpcMalformedRequest) }}, {JS(mptoken), meta::WithCustomError{ - validation::Type{}, Status(ClioError::rpcMALFORMED_REQUEST) + validation::Type{}, Status(ClioError::RpcMalformedRequest) }, - meta::IfType{malformedRequestHexStringValidator}, + meta::IfType{kMALFORMED_REQUEST_HEX_STRING_VALIDATOR}, meta::IfType{ meta::Section{ { JS(account), - meta::WithCustomError{validation::Required{}, Status(ClioError::rpcMALFORMED_REQUEST)}, + meta::WithCustomError{validation::Required{}, Status(ClioError::RpcMalformedRequest)}, meta::WithCustomError{ - validation::CustomValidators::AccountBase58Validator, - Status(ClioError::rpcMALFORMED_ADDRESS) + validation::CustomValidators::accountBase58Validator, + Status(ClioError::RpcMalformedAddress) }, }, { JS(mpt_issuance_id), - meta::WithCustomError{validation::Required{}, Status(ClioError::rpcMALFORMED_REQUEST)}, + meta::WithCustomError{validation::Required{}, Status(ClioError::RpcMalformedRequest)}, meta::WithCustomError{ - validation::CustomValidators::Uint192HexStringValidator, - Status(ClioError::rpcMALFORMED_REQUEST) + validation::CustomValidators::uint192HexStringValidator, + Status(ClioError::RpcMalformedRequest) }, }, }, @@ -378,7 +378,7 @@ public: {"include_deleted", validation::Type{}}, }; - return rpcSpec; + return kRPC_SPEC; } /** diff --git a/src/rpc/handlers/LedgerIndex.cpp b/src/rpc/handlers/LedgerIndex.cpp index e6816fdd..33a90079 100644 --- a/src/rpc/handlers/LedgerIndex.cpp +++ b/src/rpc/handlers/LedgerIndex.cpp @@ -61,7 +61,7 @@ LedgerIndexHandler::process(LedgerIndexHandler::Input input, Context const& ctx) return fillOutputByIndex(maxIndex); auto const convertISOTimeStrToTicks = [](std::string const& isoTimeStr) { - auto const systemTime = util::SystemTpFromUTCStr(isoTimeStr, DATE_FORMAT); + auto const systemTime = util::systemTpFromUtcStr(isoTimeStr, kDATE_FORMAT); // systemTime must be valid after validation passed return systemTime->time_since_epoch().count(); }; @@ -70,7 +70,7 @@ LedgerIndexHandler::process(LedgerIndexHandler::Input input, Context const& ctx) auto const earlierThan = [&](std::uint32_t ledgerIndex) { auto const header = sharedPtrBackend_->fetchLedgerBySequence(ledgerIndex, ctx.yield); - auto const ledgerTime = util::SystemTpFromLedgerCloseTime(header->closeTime); + auto const ledgerTime = util::systemTpFromLedgerCloseTime(header->closeTime); return ticks < ledgerTime.time_since_epoch().count(); }; diff --git a/src/rpc/handlers/LedgerIndex.hpp b/src/rpc/handlers/LedgerIndex.hpp index c6777028..7aa8969b 100644 --- a/src/rpc/handlers/LedgerIndex.hpp +++ b/src/rpc/handlers/LedgerIndex.hpp @@ -41,7 +41,7 @@ namespace rpc { */ class LedgerIndexHandler { std::shared_ptr sharedPtrBackend_; - static constexpr auto DATE_FORMAT = "%Y-%m-%dT%TZ"; + static constexpr auto kDATE_FORMAT = "%Y-%m-%dT%TZ"; public: /** @@ -80,10 +80,10 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const rpcSpec = RpcSpec{ - {JS(date), validation::Type{}, validation::TimeFormatValidator{DATE_FORMAT}}, + static auto const kRPC_SPEC = RpcSpec{ + {JS(date), validation::Type{}, validation::TimeFormatValidator{kDATE_FORMAT}}, }; - return rpcSpec; + return kRPC_SPEC; } /** diff --git a/src/rpc/handlers/MPTHolders.cpp b/src/rpc/handlers/MPTHolders.cpp index 03676c02..0182b7a5 100644 --- a/src/rpc/handlers/MPTHolders.cpp +++ b/src/rpc/handlers/MPTHolders.cpp @@ -59,7 +59,7 @@ MPTHoldersHandler::process(MPTHoldersHandler::Input input, Context const& ctx) c return Error{*status}; auto const lgrInfo = std::get(lgrInfoOrStatus); - auto const limit = input.limit.value_or(MPTHoldersHandler::LIMIT_DEFAULT); + auto const limit = input.limit.value_or(MPTHoldersHandler::kLIMIT_DEFAULT); auto const mptID = ripple::uint192{input.mptID.c_str()}; auto const issuanceLedgerObject = diff --git a/src/rpc/handlers/MPTHolders.hpp b/src/rpc/handlers/MPTHolders.hpp index 1bc55a34..c53d6b92 100644 --- a/src/rpc/handlers/MPTHolders.hpp +++ b/src/rpc/handlers/MPTHolders.hpp @@ -26,6 +26,16 @@ #include "rpc/common/Types.hpp" #include "rpc/common/Validators.hpp" +#include +#include +#include +#include + +#include +#include +#include +#include + namespace rpc { /** @@ -35,9 +45,9 @@ class MPTHoldersHandler { std::shared_ptr sharedPtrBackend_; public: - static auto constexpr LIMIT_MIN = 1; - static auto constexpr LIMIT_MAX = 100; - static auto constexpr LIMIT_DEFAULT = 50; + static constexpr auto kLIMIT_MIN = 1; + static constexpr auto kLIMIT_MAX = 100; + static constexpr auto kLIMIT_DEFAULT = 50; /** * @brief A struct to hold the output data of the command @@ -82,18 +92,18 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const rpcSpec = RpcSpec{ - {JS(mpt_issuance_id), validation::Required{}, validation::CustomValidators::Uint192HexStringValidator}, - {JS(ledger_hash), validation::CustomValidators::Uint256HexStringValidator}, - {JS(ledger_index), validation::CustomValidators::LedgerIndexValidator}, + static auto const kRPC_SPEC = RpcSpec{ + {JS(mpt_issuance_id), validation::Required{}, validation::CustomValidators::uint192HexStringValidator}, + {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, + {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, {JS(limit), validation::Type{}, validation::Min(1u), - modifiers::Clamp{LIMIT_MIN, LIMIT_MAX}}, - {JS(marker), validation::CustomValidators::Uint160HexStringValidator}, + modifiers::Clamp{kLIMIT_MIN, kLIMIT_MAX}}, + {JS(marker), validation::CustomValidators::uint160HexStringValidator}, }; - return rpcSpec; + return kRPC_SPEC; } /** diff --git a/src/rpc/handlers/NFTHistory.cpp b/src/rpc/handlers/NFTHistory.cpp index 40a94ef4..91dbfbf3 100644 --- a/src/rpc/handlers/NFTHistory.cpp +++ b/src/rpc/handlers/NFTHistory.cpp @@ -103,7 +103,7 @@ NFTHistoryHandler::process(NFTHistoryHandler::Input input, Context const& ctx) c } } - auto const limit = input.limit.value_or(LIMIT_DEFAULT); + auto const limit = input.limit.value_or(kLIMIT_DEFAULT); auto const tokenID = ripple::uint256{input.nftID.c_str()}; auto const [txnsAndCursor, timeDiff] = util::timed([&]() { diff --git a/src/rpc/handlers/NFTHistory.hpp b/src/rpc/handlers/NFTHistory.hpp index 431159c6..a8d0b51a 100644 --- a/src/rpc/handlers/NFTHistory.hpp +++ b/src/rpc/handlers/NFTHistory.hpp @@ -53,9 +53,9 @@ class NFTHistoryHandler { std::shared_ptr sharedPtrBackend_; public: - static auto constexpr LIMIT_MIN = 1; - static auto constexpr LIMIT_MAX = 100; - static auto constexpr LIMIT_DEFAULT = 50; + static constexpr auto kLIMIT_MIN = 1; + static constexpr auto kLIMIT_MAX = 100; + static constexpr auto kLIMIT_DEFAULT = 50; /** * @brief A struct to hold the marker data @@ -118,10 +118,10 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const rpcSpec = RpcSpec{ - {JS(nft_id), validation::Required{}, validation::CustomValidators::Uint256HexStringValidator}, - {JS(ledger_hash), validation::CustomValidators::Uint256HexStringValidator}, - {JS(ledger_index), validation::CustomValidators::LedgerIndexValidator}, + static auto const kRPC_SPEC = RpcSpec{ + {JS(nft_id), validation::Required{}, validation::CustomValidators::uint256HexStringValidator}, + {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, + {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, {JS(ledger_index_min), validation::Type{}}, {JS(ledger_index_max), validation::Type{}}, {JS(binary), validation::Type{}}, @@ -129,7 +129,7 @@ public: {JS(limit), validation::Type{}, validation::Min(1u), - modifiers::Clamp{LIMIT_MIN, LIMIT_MAX}}, + modifiers::Clamp{kLIMIT_MIN, kLIMIT_MAX}}, {JS(marker), meta::WithCustomError{ validation::Type{}, Status{RippledError::rpcINVALID_PARAMS, "invalidMarker"} @@ -140,7 +140,7 @@ public: }}, }; - return rpcSpec; + return kRPC_SPEC; } /** diff --git a/src/rpc/handlers/NFTInfo.hpp b/src/rpc/handlers/NFTInfo.hpp index e01c173d..ccbe4e0e 100644 --- a/src/rpc/handlers/NFTInfo.hpp +++ b/src/rpc/handlers/NFTInfo.hpp @@ -94,13 +94,13 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const rpcSpec = RpcSpec{ - {JS(nft_id), validation::Required{}, validation::CustomValidators::Uint256HexStringValidator}, - {JS(ledger_hash), validation::CustomValidators::Uint256HexStringValidator}, - {JS(ledger_index), validation::CustomValidators::LedgerIndexValidator}, + static auto const kRPC_SPEC = RpcSpec{ + {JS(nft_id), validation::Required{}, validation::CustomValidators::uint256HexStringValidator}, + {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, + {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, }; - return rpcSpec; + return kRPC_SPEC; } /** diff --git a/src/rpc/handlers/NFTOffersCommon.hpp b/src/rpc/handlers/NFTOffersCommon.hpp index be1e899e..21eb23bd 100644 --- a/src/rpc/handlers/NFTOffersCommon.hpp +++ b/src/rpc/handlers/NFTOffersCommon.hpp @@ -49,9 +49,9 @@ class NFTOffersHandlerBase { std::shared_ptr sharedPtrBackend_; public: - static auto constexpr LIMIT_MIN = 50; - static auto constexpr LIMIT_MAX = 500; - static auto constexpr LIMIT_DEFAULT = 250; + static constexpr auto kLIMIT_MIN = 50; + static constexpr auto kLIMIT_MAX = 500; + static constexpr auto kLIMIT_DEFAULT = 250; /** * @brief A struct to hold the output data of the command @@ -73,7 +73,7 @@ public: std::string nftID; std::optional ledgerHash; std::optional ledgerIndex; - uint32_t limit = LIMIT_DEFAULT; + uint32_t limit = kLIMIT_DEFAULT; std::optional marker; }; @@ -98,18 +98,18 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const rpcSpec = RpcSpec{ - {JS(nft_id), validation::Required{}, validation::CustomValidators::Uint256HexStringValidator}, - {JS(ledger_hash), validation::CustomValidators::Uint256HexStringValidator}, - {JS(ledger_index), validation::CustomValidators::LedgerIndexValidator}, + static auto const kRPC_SPEC = RpcSpec{ + {JS(nft_id), validation::Required{}, validation::CustomValidators::uint256HexStringValidator}, + {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, + {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, {JS(limit), validation::Type{}, validation::Min(1u), - modifiers::Clamp{LIMIT_MIN, LIMIT_MAX}}, - {JS(marker), validation::CustomValidators::Uint256HexStringValidator}, + modifiers::Clamp{kLIMIT_MIN, kLIMIT_MAX}}, + {JS(marker), validation::CustomValidators::uint256HexStringValidator}, }; - return rpcSpec; + return kRPC_SPEC; } protected: diff --git a/src/rpc/handlers/NFTsByIssuer.cpp b/src/rpc/handlers/NFTsByIssuer.cpp index 5b517aff..54b777d8 100644 --- a/src/rpc/handlers/NFTsByIssuer.cpp +++ b/src/rpc/handlers/NFTsByIssuer.cpp @@ -59,7 +59,7 @@ NFTsByIssuerHandler::process(NFTsByIssuerHandler::Input input, Context const& ct auto const lgrInfo = std::get(lgrInfoOrStatus); - auto const limit = input.limit.value_or(NFTsByIssuerHandler::LIMIT_DEFAULT); + auto const limit = input.limit.value_or(NFTsByIssuerHandler::kLIMIT_DEFAULT); auto const issuer = accountFromStringStrict(input.issuer); auto const accountLedgerObject = diff --git a/src/rpc/handlers/NFTsByIssuer.hpp b/src/rpc/handlers/NFTsByIssuer.hpp index 60b32e3a..d82cf3bc 100644 --- a/src/rpc/handlers/NFTsByIssuer.hpp +++ b/src/rpc/handlers/NFTsByIssuer.hpp @@ -45,9 +45,9 @@ class NFTsByIssuerHandler { std::shared_ptr sharedPtrBackend_; public: - static auto constexpr LIMIT_MIN = 1; - static auto constexpr LIMIT_MAX = 100; - static auto constexpr LIMIT_DEFAULT = 50; + static constexpr auto kLIMIT_MIN = 1; + static constexpr auto kLIMIT_MAX = 100; + static constexpr auto kLIMIT_DEFAULT = 50; /** * @brief A struct to hold the output data of the command @@ -94,19 +94,19 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const rpcSpec = RpcSpec{ - {JS(issuer), validation::Required{}, validation::CustomValidators::AccountValidator}, + static auto const kRPC_SPEC = RpcSpec{ + {JS(issuer), validation::Required{}, validation::CustomValidators::accountValidator}, {JS(nft_taxon), validation::Type{}}, - {JS(ledger_hash), validation::CustomValidators::Uint256HexStringValidator}, - {JS(ledger_index), validation::CustomValidators::LedgerIndexValidator}, + {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, + {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, {JS(limit), validation::Type{}, validation::Min(1u), - modifiers::Clamp{LIMIT_MIN, LIMIT_MAX}}, - {JS(marker), validation::CustomValidators::Uint256HexStringValidator}, + modifiers::Clamp{kLIMIT_MIN, kLIMIT_MAX}}, + {JS(marker), validation::CustomValidators::uint256HexStringValidator}, }; - return rpcSpec; + return kRPC_SPEC; } /** diff --git a/src/rpc/handlers/NoRippleCheck.hpp b/src/rpc/handlers/NoRippleCheck.hpp index 608a8558..249dcdd3 100644 --- a/src/rpc/handlers/NoRippleCheck.hpp +++ b/src/rpc/handlers/NoRippleCheck.hpp @@ -55,9 +55,9 @@ class NoRippleCheckHandler { std::shared_ptr sharedPtrBackend_; public: - static auto constexpr LIMIT_MIN = 1; - static auto constexpr LIMIT_MAX = 500; - static auto constexpr LIMIT_DEFAULT = 300; + static constexpr auto kLIMIT_MIN = 1; + static constexpr auto kLIMIT_MAX = 500; + static constexpr auto kLIMIT_DEFAULT = 300; /** * @brief A struct to hold the output data of the command @@ -79,7 +79,7 @@ public: bool roleGateway = false; std::optional ledgerHash; std::optional ledgerIndex; - uint32_t limit = LIMIT_DEFAULT; + uint32_t limit = kLIMIT_DEFAULT; JsonBool transactions{false}; }; @@ -104,29 +104,29 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const rpcSpecV1 = RpcSpec{ - {JS(account), validation::Required{}, validation::CustomValidators::AccountValidator}, + static auto const kRPC_SPEC_V1 = RpcSpec{ + {JS(account), validation::Required{}, validation::CustomValidators::accountValidator}, {JS(role), validation::Required{}, meta::WithCustomError{ validation::OneOf{"gateway", "user"}, Status{RippledError::rpcINVALID_PARAMS, "role field is invalid"} }}, - {JS(ledger_hash), validation::CustomValidators::Uint256HexStringValidator}, - {JS(ledger_index), validation::CustomValidators::LedgerIndexValidator}, + {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, + {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, {JS(limit), validation::Type(), validation::Min(1u), - modifiers::Clamp{LIMIT_MIN, LIMIT_MAX}} + modifiers::Clamp{kLIMIT_MIN, kLIMIT_MAX}} }; - static auto const rpcSpec = RpcSpec{ - rpcSpecV1, + static auto const kRPC_SPEC = RpcSpec{ + kRPC_SPEC_V1, { {JS(transactions), validation::Type()}, } }; - return apiVersion == 1 ? rpcSpecV1 : rpcSpec; + return apiVersion == 1 ? kRPC_SPEC_V1 : kRPC_SPEC; } /** diff --git a/src/rpc/handlers/ServerInfo.hpp b/src/rpc/handlers/ServerInfo.hpp index e68f5698..00845072 100644 --- a/src/rpc/handlers/ServerInfo.hpp +++ b/src/rpc/handlers/ServerInfo.hpp @@ -68,7 +68,7 @@ namespace rpc { */ template class BaseServerInfoHandler { - static constexpr auto BACKEND_COUNTERS_KEY = "backend_counters"; + static constexpr auto kBACKEND_COUNTERS_KEY = "backend_counters"; std::shared_ptr backend_; std::shared_ptr subscriptions_; @@ -179,8 +179,8 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static RpcSpec const rpcSpec = {}; - return rpcSpec; + static RpcSpec const kRPC_SPEC = {}; + return kRPC_SPEC; } /** @@ -211,7 +211,7 @@ public: auto const sinceEpoch = duration_cast(system_clock::now().time_since_epoch()).count(); auto const age = static_cast(sinceEpoch) - static_cast(lgrInfo->closeTime.time_since_epoch().count()) - - static_cast(rippleEpochStart); + static_cast(kRIPPLE_EPOCH_START); output.info.completeLedgers = fmt::format("{}-{}", range->minSequence, range->maxSequence); @@ -304,7 +304,7 @@ private: jv.as_object()[JS(counters)] = info.adminSection->counters; jv.as_object()[JS(counters)].as_object()["subscriptions"] = info.adminSection->subscriptions; if (info.adminSection->backendCounters.has_value()) { - jv.as_object()[BACKEND_COUNTERS_KEY] = *info.adminSection->backendCounters; + jv.as_object()[kBACKEND_COUNTERS_KEY] = *info.adminSection->backendCounters; } } } @@ -340,8 +340,8 @@ private: { auto input = BaseServerInfoHandler::Input{}; auto const jsonObject = jv.as_object(); - if (jsonObject.contains(BACKEND_COUNTERS_KEY) && jsonObject.at(BACKEND_COUNTERS_KEY).is_bool()) - input.backendCounters = jv.at(BACKEND_COUNTERS_KEY).as_bool(); + if (jsonObject.contains(kBACKEND_COUNTERS_KEY) && jsonObject.at(kBACKEND_COUNTERS_KEY).is_bool()) + input.backendCounters = jv.at(kBACKEND_COUNTERS_KEY).as_bool(); return input; } }; diff --git a/src/rpc/handlers/Subscribe.cpp b/src/rpc/handlers/Subscribe.cpp index 4e0ff2e7..206e2336 100644 --- a/src/rpc/handlers/Subscribe.cpp +++ b/src/rpc/handlers/Subscribe.cpp @@ -64,7 +64,7 @@ SubscribeHandler::SubscribeHandler( RpcSpecConstRef SubscribeHandler::spec([[maybe_unused]] uint32_t apiVersion) { - static auto const booksValidator = + static auto const kBOOKS_VALIDATOR = validation::CustomValidator{[](boost::json::value const& value, std::string_view key) -> MaybeError { if (!value.is_array()) return Error{Status{RippledError::rpcINVALID_PARAMS, std::string(key) + "NotArray"}}; @@ -81,7 +81,7 @@ SubscribeHandler::spec([[maybe_unused]] uint32_t apiVersion) if (book.as_object().contains("taker")) { if (auto err = meta::WithCustomError( - validation::CustomValidators::AccountValidator, + validation::CustomValidators::accountValidator, Status{RippledError::rpcBAD_ISSUER, "Issuer account malformed."} ) .verify(book.as_object(), "taker"); @@ -97,17 +97,17 @@ SubscribeHandler::spec([[maybe_unused]] uint32_t apiVersion) return MaybeError{}; }}; - static auto const rpcSpec = RpcSpec{ - {JS(streams), validation::CustomValidators::SubscribeStreamValidator}, - {JS(accounts), validation::CustomValidators::SubscribeAccountsValidator}, - {JS(accounts_proposed), validation::CustomValidators::SubscribeAccountsValidator}, - {JS(books), booksValidator}, + static auto const kRPC_SPEC = RpcSpec{ + {JS(streams), validation::CustomValidators::subscribeStreamValidator}, + {JS(accounts), validation::CustomValidators::subscribeAccountsValidator}, + {JS(accounts_proposed), validation::CustomValidators::subscribeAccountsValidator}, + {JS(books), kBOOKS_VALIDATOR}, {"user", check::Deprecated{}}, {JS(password), check::Deprecated{}}, {JS(rt_accounts), check::Deprecated{}} }; - return rpcSpec; + return kRPC_SPEC; } SubscribeHandler::Result @@ -196,7 +196,7 @@ SubscribeHandler::subscribeToBooks( Output& output ) const { - static auto constexpr fetchLimit = 200; + static constexpr auto kFETCH_LIMIT = 200; std::optional rng; @@ -210,7 +210,7 @@ SubscribeHandler::subscribeToBooks( auto const getOrderBook = [&](auto const& book, auto& snapshots) { auto const bookBase = getBookBase(book); auto const [offers, _] = - sharedPtrBackend_->fetchBookOffers(bookBase, rng->maxSequence, fetchLimit, yield); + sharedPtrBackend_->fetchBookOffers(bookBase, rng->maxSequence, kFETCH_LIMIT, yield); // the taker is not really uesed, same issue with // https://github.com/XRPLF/xrpl-dev-portal/issues/1818 diff --git a/src/rpc/handlers/TransactionEntry.hpp b/src/rpc/handlers/TransactionEntry.hpp index 5fe62739..8b506948 100644 --- a/src/rpc/handlers/TransactionEntry.hpp +++ b/src/rpc/handlers/TransactionEntry.hpp @@ -92,15 +92,15 @@ public: static RpcSpecConstRef spec([[maybe_unused]] uint32_t apiVersion) { - static auto const rpcSpec = RpcSpec{ + static auto const kRPC_SPEC = RpcSpec{ {JS(tx_hash), - meta::WithCustomError{validation::Required{}, Status(ClioError::rpcFIELD_NOT_FOUND_TRANSACTION)}, - validation::CustomValidators::Uint256HexStringValidator}, - {JS(ledger_hash), validation::CustomValidators::Uint256HexStringValidator}, - {JS(ledger_index), validation::CustomValidators::LedgerIndexValidator}, + meta::WithCustomError{validation::Required{}, Status(ClioError::RpcFieldNotFoundTransaction)}, + validation::CustomValidators::uint256HexStringValidator}, + {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, + {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, }; - return rpcSpec; + return kRPC_SPEC; } /** diff --git a/src/rpc/handlers/Tx.hpp b/src/rpc/handlers/Tx.hpp index e41a61db..b05a64c1 100644 --- a/src/rpc/handlers/Tx.hpp +++ b/src/rpc/handlers/Tx.hpp @@ -117,16 +117,16 @@ public: static RpcSpecConstRef spec(uint32_t apiVersion) { - static RpcSpec const rpcSpecForV1 = { - {JS(transaction), validation::CustomValidators::Uint256HexStringValidator}, + static RpcSpec const kRPC_SPEC_FOR_V1 = { + {JS(transaction), validation::CustomValidators::uint256HexStringValidator}, {JS(min_ledger), validation::Type{}}, {JS(max_ledger), validation::Type{}}, {JS(ctid), validation::Type{}}, }; - static auto const rpcSpec = RpcSpec{rpcSpecForV1, {{JS(binary), validation::Type{}}}}; + static auto const kRPC_SPEC = RpcSpec{kRPC_SPEC_FOR_V1, {{JS(binary), validation::Type{}}}}; - return apiVersion == 1 ? rpcSpecForV1 : rpcSpec; + return apiVersion == 1 ? kRPC_SPEC_FOR_V1 : kRPC_SPEC; } /** @@ -145,14 +145,14 @@ public: if (!input.ctid && !input.transaction) // at least one identifier must be supplied return Error{Status{RippledError::rpcINVALID_PARAMS}}; - static auto constexpr maxLedgerRange = 1000u; + static constexpr auto kMAX_LEDGER_RANGE = 1000u; auto const rangeSupplied = input.minLedger && input.maxLedger; if (rangeSupplied) { if (*input.minLedger > *input.maxLedger) return Error{Status{RippledError::rpcINVALID_LGR_RANGE}}; - if (*input.maxLedger - *input.minLedger > maxLedgerRange) + if (*input.maxLedger - *input.minLedger > kMAX_LEDGER_RANGE) return Error{Status{RippledError::rpcEXCESSIVE_LGR_RANGE}}; } diff --git a/src/rpc/handlers/Unsubscribe.cpp b/src/rpc/handlers/Unsubscribe.cpp index ac5f12b2..64def3cd 100644 --- a/src/rpc/handlers/Unsubscribe.cpp +++ b/src/rpc/handlers/Unsubscribe.cpp @@ -53,7 +53,7 @@ UnsubscribeHandler::UnsubscribeHandler(std::shared_ptr MaybeError { if (!value.is_array()) return Error{Status{RippledError::rpcINVALID_PARAMS, std::string(key) + "NotArray"}}; @@ -73,17 +73,17 @@ UnsubscribeHandler::spec([[maybe_unused]] uint32_t apiVersion) return MaybeError{}; }}; - static auto const rpcSpec = RpcSpec{ - {JS(streams), validation::CustomValidators::SubscribeStreamValidator}, - {JS(accounts), validation::CustomValidators::SubscribeAccountsValidator}, - {JS(accounts_proposed), validation::CustomValidators::SubscribeAccountsValidator}, - {JS(books), booksValidator}, + static auto const kRPC_SPEC = RpcSpec{ + {JS(streams), validation::CustomValidators::subscribeStreamValidator}, + {JS(accounts), validation::CustomValidators::subscribeAccountsValidator}, + {JS(accounts_proposed), validation::CustomValidators::subscribeAccountsValidator}, + {JS(books), kBOOKS_VALIDATOR}, {JS(url), check::Deprecated{}}, {JS(rt_accounts), check::Deprecated{}}, {"rt_transactions", check::Deprecated{}}, }; - return rpcSpec; + return kRPC_SPEC; } UnsubscribeHandler::Result diff --git a/src/util/Concepts.hpp b/src/util/Concepts.hpp index a6dd33b4..1b7f2565 100644 --- a/src/util/Concepts.hpp +++ b/src/util/Concepts.hpp @@ -58,9 +58,9 @@ template constexpr bool hasNoDuplicateNames() { - constexpr std::array names = {Types::name...}; - return !std::ranges::any_of(names, [&](std::string_view const& name1) { - return std::ranges::any_of(names, [&](std::string_view const& name2) { + constexpr std::array kNAMES = {Types::kNAME...}; + return !std::ranges::any_of(kNAMES, [&](std::string_view const& name1) { + return std::ranges::any_of(kNAMES, [&](std::string_view const& name2) { return &name1 != &name2 && name1 == name2; // Ensure different elements are compared }); }); diff --git a/src/util/Constants.hpp b/src/util/Constants.hpp index fdb5f913..e148ea58 100644 --- a/src/util/Constants.hpp +++ b/src/util/Constants.hpp @@ -22,5 +22,5 @@ #include namespace util { -static constexpr std::size_t MILLISECONDS_PER_SECOND = 1000; +static constexpr std::size_t kMILLISECONDS_PER_SECOND = 1000; } // namespace util diff --git a/src/util/LedgerUtils.cpp b/src/util/LedgerUtils.cpp index 7739af65..9adbf420 100644 --- a/src/util/LedgerUtils.cpp +++ b/src/util/LedgerUtils.cpp @@ -28,18 +28,18 @@ namespace util { ripple::LedgerEntryType -LedgerTypes::GetLedgerEntryTypeFromStr(std::string const& entryName) +LedgerTypes::getLedgerEntryTypeFromStr(std::string const& entryName) { - static std::unordered_map typeMap = []() { + static std::unordered_map kTYPE_MAP = []() { std::unordered_map map; - std::ranges::for_each(LEDGER_TYPES, [&map](auto const& item) { map[item.name] = item.type; }); + std::ranges::for_each(kLEDGER_TYPES, [&map](auto const& item) { map[item.name_] = item.type_; }); return map; }(); - if (typeMap.find(entryName) == typeMap.end()) + if (kTYPE_MAP.find(entryName) == kTYPE_MAP.end()) return ripple::ltANY; - return typeMap.at(entryName); + return kTYPE_MAP.at(entryName); } } // namespace util diff --git a/src/util/LedgerUtils.hpp b/src/util/LedgerUtils.hpp index 002c4011..3ada20a6 100644 --- a/src/util/LedgerUtils.hpp +++ b/src/util/LedgerUtils.hpp @@ -47,30 +47,31 @@ class LedgerTypeAttribute { Chain, // The ledger object is shared across the chain DeletionBlocker // The ledger object is owned by account and it blocks deletion }; - ripple::LedgerEntryType type = ripple::ltANY; - char const* name = nullptr; - LedgerCategory category = LedgerCategory::Invalid; + + ripple::LedgerEntryType type_ = ripple::ltANY; + char const* name_ = nullptr; + LedgerCategory category_ = LedgerCategory::Invalid; constexpr LedgerTypeAttribute(char const* name, ripple::LedgerEntryType type, LedgerCategory category) - : type(type), name(name), category(category) + : type_(type), name_(name), category_(category) { } public: static constexpr LedgerTypeAttribute - ChainLedgerType(char const* name, ripple::LedgerEntryType type) + chainLedgerType(char const* name, ripple::LedgerEntryType type) { return LedgerTypeAttribute(name, type, LedgerCategory::Chain); } static constexpr LedgerTypeAttribute - AccountOwnedLedgerType(char const* name, ripple::LedgerEntryType type) + accountOwnedLedgerType(char const* name, ripple::LedgerEntryType type) { return LedgerTypeAttribute(name, type, LedgerCategory::AccountOwned); } static constexpr LedgerTypeAttribute - DeletionBlockerLedgerType(char const* name, ripple::LedgerEntryType type) + deletionBlockerLedgerType(char const* name, ripple::LedgerEntryType type) { return LedgerTypeAttribute(name, type, LedgerCategory::DeletionBlocker); } @@ -86,36 +87,36 @@ class LedgerTypes { using LedgerTypeAttribute = impl::LedgerTypeAttribute; using LedgerTypeAttributeList = LedgerTypeAttribute[]; - static constexpr LedgerTypeAttributeList const LEDGER_TYPES{ - LedgerTypeAttribute::AccountOwnedLedgerType(JS(account), ripple::ltACCOUNT_ROOT), - LedgerTypeAttribute::ChainLedgerType(JS(amendments), ripple::ltAMENDMENTS), - LedgerTypeAttribute::DeletionBlockerLedgerType(JS(check), ripple::ltCHECK), - LedgerTypeAttribute::AccountOwnedLedgerType(JS(deposit_preauth), ripple::ltDEPOSIT_PREAUTH), + static constexpr LedgerTypeAttributeList const kLEDGER_TYPES{ + LedgerTypeAttribute::accountOwnedLedgerType(JS(account), ripple::ltACCOUNT_ROOT), + LedgerTypeAttribute::chainLedgerType(JS(amendments), ripple::ltAMENDMENTS), + LedgerTypeAttribute::deletionBlockerLedgerType(JS(check), ripple::ltCHECK), + LedgerTypeAttribute::accountOwnedLedgerType(JS(deposit_preauth), ripple::ltDEPOSIT_PREAUTH), // dir node belongs to account, but can not be filtered from account_objects - LedgerTypeAttribute::ChainLedgerType(JS(directory), ripple::ltDIR_NODE), - LedgerTypeAttribute::DeletionBlockerLedgerType(JS(escrow), ripple::ltESCROW), - LedgerTypeAttribute::ChainLedgerType(JS(fee), ripple::ltFEE_SETTINGS), - LedgerTypeAttribute::ChainLedgerType(JS(hashes), ripple::ltLEDGER_HASHES), - LedgerTypeAttribute::AccountOwnedLedgerType(JS(offer), ripple::ltOFFER), - LedgerTypeAttribute::DeletionBlockerLedgerType(JS(payment_channel), ripple::ltPAYCHAN), - LedgerTypeAttribute::AccountOwnedLedgerType(JS(signer_list), ripple::ltSIGNER_LIST), - LedgerTypeAttribute::DeletionBlockerLedgerType(JS(state), ripple::ltRIPPLE_STATE), - LedgerTypeAttribute::AccountOwnedLedgerType(JS(ticket), ripple::ltTICKET), - LedgerTypeAttribute::AccountOwnedLedgerType(JS(nft_offer), ripple::ltNFTOKEN_OFFER), - LedgerTypeAttribute::DeletionBlockerLedgerType(JS(nft_page), ripple::ltNFTOKEN_PAGE), - LedgerTypeAttribute::AccountOwnedLedgerType(JS(amm), ripple::ltAMM), - LedgerTypeAttribute::DeletionBlockerLedgerType(JS(bridge), ripple::ltBRIDGE), - LedgerTypeAttribute::DeletionBlockerLedgerType(JS(xchain_owned_claim_id), ripple::ltXCHAIN_OWNED_CLAIM_ID), - LedgerTypeAttribute::DeletionBlockerLedgerType( + LedgerTypeAttribute::chainLedgerType(JS(directory), ripple::ltDIR_NODE), + LedgerTypeAttribute::deletionBlockerLedgerType(JS(escrow), ripple::ltESCROW), + LedgerTypeAttribute::chainLedgerType(JS(fee), ripple::ltFEE_SETTINGS), + LedgerTypeAttribute::chainLedgerType(JS(hashes), ripple::ltLEDGER_HASHES), + LedgerTypeAttribute::accountOwnedLedgerType(JS(offer), ripple::ltOFFER), + LedgerTypeAttribute::deletionBlockerLedgerType(JS(payment_channel), ripple::ltPAYCHAN), + LedgerTypeAttribute::accountOwnedLedgerType(JS(signer_list), ripple::ltSIGNER_LIST), + LedgerTypeAttribute::deletionBlockerLedgerType(JS(state), ripple::ltRIPPLE_STATE), + LedgerTypeAttribute::accountOwnedLedgerType(JS(ticket), ripple::ltTICKET), + LedgerTypeAttribute::accountOwnedLedgerType(JS(nft_offer), ripple::ltNFTOKEN_OFFER), + LedgerTypeAttribute::deletionBlockerLedgerType(JS(nft_page), ripple::ltNFTOKEN_PAGE), + LedgerTypeAttribute::accountOwnedLedgerType(JS(amm), ripple::ltAMM), + LedgerTypeAttribute::deletionBlockerLedgerType(JS(bridge), ripple::ltBRIDGE), + LedgerTypeAttribute::deletionBlockerLedgerType(JS(xchain_owned_claim_id), ripple::ltXCHAIN_OWNED_CLAIM_ID), + LedgerTypeAttribute::deletionBlockerLedgerType( JS(xchain_owned_create_account_claim_id), ripple::ltXCHAIN_OWNED_CREATE_ACCOUNT_CLAIM_ID ), - LedgerTypeAttribute::AccountOwnedLedgerType(JS(did), ripple::ltDID), - LedgerTypeAttribute::AccountOwnedLedgerType(JS(oracle), ripple::ltORACLE), - LedgerTypeAttribute::AccountOwnedLedgerType(JS(credential), ripple::ltCREDENTIAL), - LedgerTypeAttribute::ChainLedgerType(JS(nunl), ripple::ltNEGATIVE_UNL), - LedgerTypeAttribute::DeletionBlockerLedgerType(JS(mpt_issuance), ripple::ltMPTOKEN_ISSUANCE), - LedgerTypeAttribute::DeletionBlockerLedgerType(JS(mptoken), ripple::ltMPTOKEN), + LedgerTypeAttribute::accountOwnedLedgerType(JS(did), ripple::ltDID), + LedgerTypeAttribute::accountOwnedLedgerType(JS(oracle), ripple::ltORACLE), + LedgerTypeAttribute::accountOwnedLedgerType(JS(credential), ripple::ltCREDENTIAL), + LedgerTypeAttribute::chainLedgerType(JS(nunl), ripple::ltNEGATIVE_UNL), + LedgerTypeAttribute::deletionBlockerLedgerType(JS(mpt_issuance), ripple::ltMPTOKEN_ISSUANCE), + LedgerTypeAttribute::deletionBlockerLedgerType(JS(mptoken), ripple::ltMPTOKEN), }; public: @@ -124,10 +125,10 @@ public: * @return A list of all ledger entry type as string. */ static constexpr auto - GetLedgerEntryTypeStrList() + getLedgerEntryTypeStrList() { - std::array res{}; - std::ranges::transform(LEDGER_TYPES, std::begin(res), [](auto const& item) { return item.name; }); + std::array res{}; + std::ranges::transform(kLEDGER_TYPES, std::begin(res), [](auto const& item) { return item.name_; }); return res; } @@ -137,18 +138,19 @@ public: * @return A list of all account owned ledger entry type as string. */ static constexpr auto - GetAccountOwnedLedgerTypeStrList() + getAccountOwnedLedgerTypeStrList() { - auto constexpr filter = [](auto const& item) { - return item.category != LedgerTypeAttribute::LedgerCategory::Chain; + constexpr auto kFILTER = [](auto const& item) { + return item.category_ != LedgerTypeAttribute::LedgerCategory::Chain; }; - auto constexpr accountOwnedCount = std::count_if(std::begin(LEDGER_TYPES), std::end(LEDGER_TYPES), filter); - std::array res{}; + constexpr auto kACCOUNT_OWNED_COUNT = + std::count_if(std::begin(kLEDGER_TYPES), std::end(kLEDGER_TYPES), kFILTER); + std::array res{}; auto it = std::begin(res); - std::ranges::for_each(LEDGER_TYPES, [&](auto const& item) { - if (filter(item)) { - *it = item.name; + std::ranges::for_each(kLEDGER_TYPES, [&](auto const& item) { + if (kFILTER(item)) { + *it = item.name_; ++it; } }); @@ -161,18 +163,19 @@ public: * @return A list of all account deletion blocker's type as string. */ static constexpr auto - GetDeletionBlockerLedgerTypes() + getDeletionBlockerLedgerTypes() { - auto constexpr filter = [](auto const& item) { - return item.category == LedgerTypeAttribute::LedgerCategory::DeletionBlocker; + constexpr auto kFILTER = [](auto const& item) { + return item.category_ == LedgerTypeAttribute::LedgerCategory::DeletionBlocker; }; - auto constexpr deletionBlockersCount = std::count_if(std::begin(LEDGER_TYPES), std::end(LEDGER_TYPES), filter); - std::array res{}; + constexpr auto kDELETION_BLOCKERS_COUNT = + std::count_if(std::begin(kLEDGER_TYPES), std::end(kLEDGER_TYPES), kFILTER); + std::array res{}; auto it = std::begin(res); - std::ranges::for_each(LEDGER_TYPES, [&](auto const& item) { - if (filter(item)) { - *it = item.type; + std::ranges::for_each(kLEDGER_TYPES, [&](auto const& item) { + if (kFILTER(item)) { + *it = item.type_; ++it; } }); @@ -186,7 +189,7 @@ public: * @return The ripple::LedgerEntryType of the given string, returns ltANY if not found. */ static ripple::LedgerEntryType - GetLedgerEntryTypeFromStr(std::string const& entryName); + getLedgerEntryTypeFromStr(std::string const& entryName); }; /** diff --git a/src/util/Random.cpp b/src/util/Random.cpp index cba88c42..73feaf92 100644 --- a/src/util/Random.cpp +++ b/src/util/Random.cpp @@ -28,9 +28,9 @@ namespace util { void Random::setSeed(size_t seed) { - generator_.seed(seed); + generator.seed(seed); } -std::mt19937_64 Random::generator_{std::chrono::system_clock::now().time_since_epoch().count()}; +std::mt19937_64 Random::generator{std::chrono::system_clock::now().time_since_epoch().count()}; } // namespace util diff --git a/src/util/Random.hpp b/src/util/Random.hpp index 0a31833b..3ce00d51 100644 --- a/src/util/Random.hpp +++ b/src/util/Random.hpp @@ -45,10 +45,10 @@ public: ASSERT(min <= max, "Min cannot be greater than max. min: {}, max: {}", min, max); if constexpr (std::is_floating_point_v) { std::uniform_real_distribution distribution(min, max); - return distribution(generator_); + return distribution(generator); } std::uniform_int_distribution distribution(min, max); - return distribution(generator_); + return distribution(generator); } /** @@ -60,7 +60,7 @@ public: setSeed(size_t seed); private: - static std::mt19937_64 generator_; + static std::mt19937_64 generator; }; } // namespace util diff --git a/src/util/SignalsHandler.cpp b/src/util/SignalsHandler.cpp index 427a7b93..3897ba01 100644 --- a/src/util/SignalsHandler.cpp +++ b/src/util/SignalsHandler.cpp @@ -25,7 +25,6 @@ #include #include -#include #include #include #include @@ -35,38 +34,38 @@ namespace util { namespace impl { class SignalsHandlerStatic { - static SignalsHandler* handler_; + static SignalsHandler* installedHandler; public: static void registerHandler(SignalsHandler& handler) { - ASSERT(handler_ == nullptr, "There could be only one instance of SignalsHandler"); - handler_ = &handler; + ASSERT(installedHandler == nullptr, "There could be only one instance of SignalsHandler"); + installedHandler = &handler; } static void resetHandler() { - handler_ = nullptr; + installedHandler = nullptr; } static void handleSignal(int signal) { - ASSERT(handler_ != nullptr, "SignalsHandler is not initialized"); - handler_->stopHandler_(signal); + ASSERT(installedHandler != nullptr, "SignalsHandler is not initialized"); + installedHandler->stopHandler_(signal); } static void handleSecondSignal(int signal) { - ASSERT(handler_ != nullptr, "SignalsHandler is not initialized"); - handler_->secondSignalHandler_(signal); + ASSERT(installedHandler != nullptr, "SignalsHandler is not initialized"); + installedHandler->secondSignalHandler_(signal); } }; -SignalsHandler* SignalsHandlerStatic::handler_ = nullptr; +SignalsHandler* SignalsHandlerStatic::installedHandler = nullptr; } // namespace impl @@ -120,7 +119,7 @@ SignalsHandler::cancelTimer() void SignalsHandler::setHandler(void (*handler)(int)) { - for (int const signal : HANDLED_SIGNALS) { + for (int const signal : kHANDLED_SIGNALS) { std::signal(signal, handler == nullptr ? SIG_DFL : handler); } } diff --git a/src/util/SignalsHandler.hpp b/src/util/SignalsHandler.hpp index 9c51d8a5..addf0334 100644 --- a/src/util/SignalsHandler.hpp +++ b/src/util/SignalsHandler.hpp @@ -71,7 +71,7 @@ public: */ SignalsHandler( util::config::ClioConfigDefinition const& config, - std::function forceExitHandler = defaultForceExitHandler_ + std::function forceExitHandler = kDEFAULT_FORCE_EXIT_HANDLER ); SignalsHandler(SignalsHandler const&) = delete; @@ -100,7 +100,7 @@ public: stopSignal_.connect(static_cast(priority), std::forward(callback)); } - static constexpr auto HANDLED_SIGNALS = {SIGINT, SIGTERM}; + static constexpr auto kHANDLED_SIGNALS = {SIGINT, SIGTERM}; private: /** @@ -117,7 +117,7 @@ private: static void setHandler(void (*handler)(int) = nullptr); - static auto constexpr defaultForceExitHandler_ = []() { std::exit(EXIT_FAILURE); }; + static constexpr auto kDEFAULT_FORCE_EXIT_HANDLER = []() { std::exit(EXIT_FAILURE); }; }; } // namespace util diff --git a/src/util/Taggable.cpp b/src/util/Taggable.cpp index d97ad13c..655077e0 100644 --- a/src/util/Taggable.cpp +++ b/src/util/Taggable.cpp @@ -30,18 +30,18 @@ namespace util::impl { UIntTagGenerator::TagType UIntTagGenerator::next() { - static std::atomic_uint64_t num{0}; - return num++; + static std::atomic_uint64_t kNUM{0}; + return kNUM++; } UUIDTagGenerator::TagType UUIDTagGenerator::next() { - static boost::uuids::random_generator gen{}; - static std::mutex mtx{}; + static boost::uuids::random_generator kGEN{}; + static std::mutex kMTX{}; - std::lock_guard const lk(mtx); - return gen(); + std::lock_guard const lk(kMTX); + return kGEN(); } } // namespace util::impl diff --git a/src/util/TimeUtils.cpp b/src/util/TimeUtils.cpp index 7a97cac4..85ce4d09 100644 --- a/src/util/TimeUtils.cpp +++ b/src/util/TimeUtils.cpp @@ -28,7 +28,7 @@ namespace util { [[nodiscard]] std::optional -SystemTpFromUTCStr(std::string const& dateStr, std::string const& format) +systemTpFromUtcStr(std::string const& dateStr, std::string const& format) { std::tm timeStruct{}; auto const ret = strptime(dateStr.c_str(), format.c_str(), &timeStruct); @@ -39,7 +39,7 @@ SystemTpFromUTCStr(std::string const& dateStr, std::string const& format) } [[nodiscard]] std::chrono::system_clock::time_point -SystemTpFromLedgerCloseTime(ripple::NetClock::time_point closeTime) +systemTpFromLedgerCloseTime(ripple::NetClock::time_point closeTime) { return std::chrono::system_clock::time_point{closeTime.time_since_epoch() + ripple::epoch_offset}; } diff --git a/src/util/TimeUtils.hpp b/src/util/TimeUtils.hpp index b6320a89..84ac5fee 100644 --- a/src/util/TimeUtils.hpp +++ b/src/util/TimeUtils.hpp @@ -33,7 +33,7 @@ namespace util { * @return The system_clock::time_point if the conversion was successful, otherwise std::nullopt. */ [[nodiscard]] std::optional -SystemTpFromUTCStr(std::string const& dateStr, std::string const& format); +systemTpFromUtcStr(std::string const& dateStr, std::string const& format); /** * @brief Convert a ledger close time which is XRPL network clock to a system_clock::time_point. @@ -41,6 +41,6 @@ SystemTpFromUTCStr(std::string const& dateStr, std::string const& format); * @return The system_clock::time_point. */ [[nodiscard]] std::chrono::system_clock::time_point -SystemTpFromLedgerCloseTime(ripple::NetClock::time_point closeTime); +systemTpFromLedgerCloseTime(ripple::NetClock::time_point closeTime); } // namespace util diff --git a/src/util/TxUtils.cpp b/src/util/TxUtils.cpp index 6ae6e29d..40360e6f 100644 --- a/src/util/TxUtils.cpp +++ b/src/util/TxUtils.cpp @@ -36,7 +36,7 @@ namespace util { [[nodiscard]] std::unordered_set const& getTxTypesInLowercase() { - static std::unordered_set const typesKeysInLowercase = []() { + static std::unordered_set const kTYPES_KEYS_IN_LOWERCASE = []() { std::unordered_set keys; std::transform( ripple::TxFormats::getInstance().begin(), @@ -47,6 +47,6 @@ getTxTypesInLowercase() return keys; }(); - return typesKeysInLowercase; + return kTYPES_KEYS_IN_LOWERCASE; } } // namespace util diff --git a/src/util/UnsupportedType.hpp b/src/util/UnsupportedType.hpp index b2e03172..ae825a3b 100644 --- a/src/util/UnsupportedType.hpp +++ b/src/util/UnsupportedType.hpp @@ -23,6 +23,6 @@ namespace util { /** @brief used for compile time checking of unsupported types */ template -static constexpr bool Unsupported = false; +static constexpr bool Unsupported = false; // NOLINT(readability-identifier-naming) } // namespace util diff --git a/src/util/async/Error.hpp b/src/util/async/Error.hpp index b0b9c5f1..abb19401 100644 --- a/src/util/async/Error.hpp +++ b/src/util/async/Error.hpp @@ -68,7 +68,7 @@ struct ExecutionError { std::string message; }; -// these are not the robots you are looking for... +// these are not the droids you are looking for... static_assert(std::is_copy_constructible_v>); } // namespace util::async diff --git a/src/util/async/Operation.hpp b/src/util/async/Operation.hpp index ffda0efd..742e346c 100644 --- a/src/util/async/Operation.hpp +++ b/src/util/async/Operation.hpp @@ -72,11 +72,12 @@ public: template struct BasicScheduledOperation { - struct State { + class State { std::mutex m_; std::condition_variable ready_; std::optional op_{std::nullopt}; + public: void emplace(auto&& op) { @@ -94,11 +95,11 @@ struct BasicScheduledOperation { } }; - std::shared_ptr state_ = std::make_shared(); - typename CtxType::Timer timer_; + std::shared_ptr state = std::make_shared(); + typename CtxType::Timer timer; BasicScheduledOperation(auto& executor, auto delay, auto&& fn) - : timer_(executor, delay, [state = state_, fn = std::forward(fn)](auto ec) mutable { + : timer(executor, delay, [state = state, fn = std::forward(fn)](auto ec) mutable { state->emplace(fn(ec)); }) { @@ -107,26 +108,26 @@ struct BasicScheduledOperation { [[nodiscard]] auto get() { - return state_->get().get(); + return state->get().get(); } void wait() noexcept { - state_->get().wait(); + state->get().wait(); } void cancel() noexcept { - timer_.cancel(); + timer.cancel(); } void requestStop() noexcept requires(SomeStoppableOperation) { - state_->get().requestStop(); + state->get().requestStop(); } void diff --git a/src/util/async/context/BasicExecutionContext.hpp b/src/util/async/context/BasicExecutionContext.hpp index 9a650a58..b2b92182 100644 --- a/src/util/async/context/BasicExecutionContext.hpp +++ b/src/util/async/context/BasicExecutionContext.hpp @@ -138,7 +138,7 @@ class BasicExecutionContext { public: /** @brief Whether operations on this execution context are noexcept */ - static constexpr bool isNoexcept = noexcept(ErrorHandlerType::wrap([](auto&) { throw 0; })); + static constexpr bool kIS_NOEXCEPT = noexcept(ErrorHandlerType::wrap([](auto&) { throw 0; })); using ContextHolderType = ContextType; @@ -202,7 +202,7 @@ public: SomeStdDuration auto delay, SomeHandlerWith auto&& fn, std::optional timeout = std::nullopt - ) noexcept(isNoexcept) + ) noexcept(kIS_NOEXCEPT) { if constexpr (not std::is_same_v) { return TimerContextProvider::getContext(*this).scheduleAfter( @@ -242,7 +242,7 @@ public: SomeStdDuration auto delay, SomeHandlerWith auto&& fn, std::optional timeout = std::nullopt - ) noexcept(isNoexcept) + ) noexcept(kIS_NOEXCEPT) { if constexpr (not std::is_same_v) { return TimerContextProvider::getContext(*this).scheduleAfter( @@ -278,7 +278,7 @@ public: * @return A repeating stoppable operation that can be used to wait for its cancellation */ [[nodiscard]] auto - executeRepeatedly(SomeStdDuration auto interval, SomeHandlerWithoutStopToken auto&& fn) noexcept(isNoexcept) + executeRepeatedly(SomeStdDuration auto interval, SomeHandlerWithoutStopToken auto&& fn) noexcept(kIS_NOEXCEPT) { if constexpr (not std::is_same_v) { return TimerContextProvider::getContext(*this).executeRepeatedly(interval, std::forward(fn)); @@ -298,7 +298,7 @@ public: execute( SomeHandlerWith auto&& fn, std::optional timeout = std::nullopt - ) noexcept(isNoexcept) + ) noexcept(kIS_NOEXCEPT) { return DispatcherType::dispatch( context_, @@ -328,7 +328,7 @@ public: * @return A stoppable operation that can be used to wait for the result */ [[nodiscard]] auto - execute(SomeHandlerWith auto&& fn, SomeStdDuration auto timeout) noexcept(isNoexcept) + execute(SomeHandlerWith auto&& fn, SomeStdDuration auto timeout) noexcept(kIS_NOEXCEPT) { return execute( std::forward(fn), @@ -343,7 +343,7 @@ public: * @return A unstoppable operation that can be used to wait for the result */ [[nodiscard]] auto - execute(SomeHandlerWithoutStopToken auto&& fn) noexcept(isNoexcept) + execute(SomeHandlerWithoutStopToken auto&& fn) noexcept(kIS_NOEXCEPT) { return DispatcherType::dispatch( context_, diff --git a/src/util/async/context/SystemExecutionContext.hpp b/src/util/async/context/SystemExecutionContext.hpp index c0a65888..46d19164 100644 --- a/src/util/async/context/SystemExecutionContext.hpp +++ b/src/util/async/context/SystemExecutionContext.hpp @@ -39,8 +39,8 @@ public: [[nodiscard]] static auto& instance() { - static util::async::PoolExecutionContext systemExecutionContext{}; - return systemExecutionContext; + static util::async::PoolExecutionContext kSYSTEM_EXECUTION_CONTEXT{}; + return kSYSTEM_EXECUTION_CONTEXT; } }; diff --git a/src/util/async/context/impl/Strand.hpp b/src/util/async/context/impl/Strand.hpp index e16bfd61..6a6cfd11 100644 --- a/src/util/async/context/impl/Strand.hpp +++ b/src/util/async/context/impl/Strand.hpp @@ -45,7 +45,7 @@ class BasicStrand { friend AssociatedExecutorExtractor; public: - static constexpr bool isNoexcept = noexcept(ErrorHandlerType::wrap([](auto&) { throw 0; })); + static constexpr bool kIS_NOEXCEPT = noexcept(ErrorHandlerType::wrap([](auto&) { throw 0; })); using ContextHolderType = typename ParentContextType::ContextHolderType::Strand; using ExecutorType = typename ContextHolderType::Executor; @@ -65,7 +65,7 @@ public: [[nodiscard]] auto execute(SomeHandlerWith auto&& fn, std::optional timeout = std::nullopt) const - noexcept(isNoexcept) + noexcept(kIS_NOEXCEPT) { return DispatcherType::dispatch( context_, @@ -89,7 +89,7 @@ public: } [[nodiscard]] auto - execute(SomeHandlerWith auto&& fn, SomeStdDuration auto timeout) const noexcept(isNoexcept) + execute(SomeHandlerWith auto&& fn, SomeStdDuration auto timeout) const noexcept(kIS_NOEXCEPT) { return execute( std::forward(fn), @@ -98,7 +98,7 @@ public: } [[nodiscard]] auto - execute(SomeHandlerWithoutStopToken auto&& fn) const noexcept(isNoexcept) + execute(SomeHandlerWithoutStopToken auto&& fn) const noexcept(kIS_NOEXCEPT) { return DispatcherType::dispatch( context_, diff --git a/src/util/async/context/impl/Utils.hpp b/src/util/async/context/impl/Utils.hpp index 2cd8045a..75280d7a 100644 --- a/src/util/async/context/impl/Utils.hpp +++ b/src/util/async/context/impl/Utils.hpp @@ -39,7 +39,7 @@ inline constexpr struct AssociatedExecutorExtractor { { return ctx.context_.getExecutor(); } -} extractAssociatedExecutor; +} extractAssociatedExecutor; // NOLINT(readability-identifier-naming) template [[nodiscard]] constexpr auto diff --git a/src/util/config/Config.cpp b/src/util/config/Config.cpp index f88ce89f..36e79eeb 100644 --- a/src/util/config/Config.cpp +++ b/src/util/config/Config.cpp @@ -73,7 +73,7 @@ Config::lookup(KeyType key) const std::reference_wrapper cur = std::cref(store_); auto hasBrokenPath = false; - auto tokenized = impl::Tokenizer{key}; + auto tokenized = impl::Tokenizer{key}; std::string subkey{}; auto maybeSection = tokenized.next(); @@ -91,7 +91,7 @@ Config::lookup(KeyType key) const } } - subkey += Separator; + subkey += kSEPARATOR; maybeSection = tokenized.next(); } @@ -104,9 +104,9 @@ std::optional Config::maybeArray(KeyType key) const { try { - auto maybe_arr = lookup(key); - if (maybe_arr && maybe_arr->is_array()) { - auto& arr = maybe_arr->as_array(); + auto maybeArr = lookup(key); + if (maybeArr && maybeArr->is_array()) { + auto& arr = maybeArr->as_array(); ArrayType out; out.reserve(arr.size()); @@ -125,16 +125,16 @@ Config::maybeArray(KeyType key) const Config::ArrayType Config::array(KeyType key) const { - if (auto maybe_arr = maybeArray(key); maybe_arr) - return maybe_arr.value(); + if (auto maybeArr = maybeArray(key); maybeArr) + return maybeArr.value(); throw std::logic_error("No array found at '" + key + "'"); } Config::ArrayType Config::arrayOr(KeyType key, ArrayType fallback) const { - if (auto maybe_arr = maybeArray(key); maybe_arr) - return maybe_arr.value(); + if (auto maybeArr = maybeArray(key); maybeArr) + return maybeArr.value(); return fallback; } @@ -151,18 +151,18 @@ Config::arrayOrThrow(KeyType key, std::string_view err) const Config Config::section(KeyType key) const { - auto maybe_element = lookup(key); - if (maybe_element && maybe_element->is_object()) - return Config{std::move(*maybe_element)}; + auto maybeElement = lookup(key); + if (maybeElement && maybeElement->is_object()) + return Config{std::move(*maybeElement)}; throw std::logic_error("No section found at '" + key + "'"); } Config Config::sectionOr(KeyType key, boost::json::object fallback) const { - auto maybe_element = lookup(key); - if (maybe_element && maybe_element->is_object()) - return Config{std::move(*maybe_element)}; + auto maybeElement = lookup(key); + if (maybeElement && maybeElement->is_object()) + return Config{std::move(*maybeElement)}; return Config{std::move(fallback)}; } @@ -184,7 +184,7 @@ std::chrono::milliseconds Config::toMilliseconds(float value) { ASSERT(value >= 0.0f, "Floating point value of seconds must be non-negative, got: {}", value); - return std::chrono::milliseconds{std::lroundf(value * static_cast(util::MILLISECONDS_PER_SECOND))}; + return std::chrono::milliseconds{std::lroundf(value * static_cast(util::kMILLISECONDS_PER_SECOND))}; } Config diff --git a/src/util/config/Config.hpp b/src/util/config/Config.hpp index 85c17e8e..e7f35ba4 100644 --- a/src/util/config/Config.hpp +++ b/src/util/config/Config.hpp @@ -48,7 +48,7 @@ namespace util { */ class Config final { boost::json::value store_; - static constexpr char Separator = '.'; + static constexpr char kSEPARATOR = '.'; public: using KeyType = std::string; @@ -107,9 +107,9 @@ public: [[nodiscard]] std::optional maybeValue(KeyType key) const { - auto maybe_element = lookup(key); - if (maybe_element) - return std::make_optional(checkedAs(key, *maybe_element)); + auto maybeElement = lookup(key); + if (maybeElement) + return std::make_optional(checkedAs(key, *maybeElement)); return std::nullopt; } @@ -379,7 +379,7 @@ private: { using boost::json::value_to; - auto error_if = [&key, &value](bool condition) { + auto errorIf = [&key, &value](bool condition) { if (condition) { throw std::runtime_error( "Type for key '" + key + "' is '" + std::string{to_string(value.kind())} + @@ -389,13 +389,13 @@ private: }; if constexpr (std::is_same_v) { - error_if(not value.is_bool()); + errorIf(not value.is_bool()); } else if constexpr (std::is_same_v) { - error_if(not value.is_string()); + errorIf(not value.is_string()); } else if constexpr (std::is_same_v or std::is_same_v) { - error_if(not value.is_number()); + errorIf(not value.is_number()); } else if constexpr (std::is_convertible_v || std::is_convertible_v) { - error_if(not value.is_int64() && not value.is_uint64()); + errorIf(not value.is_int64() && not value.is_uint64()); } return value_to(value); diff --git a/src/util/log/Logger.cpp b/src/util/log/Logger.cpp index 30d9ee1e..2a1dc7a1 100644 --- a/src/util/log/Logger.cpp +++ b/src/util/log/Logger.cpp @@ -64,14 +64,14 @@ namespace util { -Logger LogService::general_log_ = Logger{"General"}; -Logger LogService::alert_log_ = Logger{"Alert"}; -boost::log::filter LogService::filter_{}; +Logger LogService::generalLog = Logger{"General"}; +Logger LogService::alertLog = Logger{"Alert"}; +boost::log::filter LogService::filter{}; std::ostream& operator<<(std::ostream& stream, Severity sev) { - static constexpr std::array labels = { + static constexpr std::array kLABELS = { "TRC", "DBG", "NFO", @@ -80,7 +80,7 @@ operator<<(std::ostream& stream, Severity sev) "FTL", }; - return stream << labels.at(static_cast(sev)); + return stream << kLABELS.at(static_cast(sev)); } /** @@ -122,12 +122,12 @@ LogService::init(config::ClioConfigDefinition const& config) if (config.get("log_to_console")) { boost::log::add_console_log( - std::cout, keywords::format = format, keywords::filter = log_severity < Severity::FTL + std::cout, keywords::format = format, keywords::filter = LogSeverity < Severity::FTL ); } // Always print fatal logs to cerr - boost::log::add_console_log(std::cerr, keywords::format = format, keywords::filter = log_severity >= Severity::FTL); + boost::log::add_console_log(std::cerr, keywords::format = format, keywords::filter = LogSeverity >= Severity::FTL); auto const logDir = config.maybeValue("log_directory"); if (logDir) { @@ -156,35 +156,35 @@ LogService::init(config::ClioConfigDefinition const& config) // get default severity, can be overridden per channel using the `log_channels` array auto const defaultSeverity = getSeverityLevel(config.get("log_level")); - std::unordered_map min_severity; - for (auto const& channel : Logger::CHANNELS) - min_severity[channel] = defaultSeverity; - min_severity["Alert"] = Severity::WRN; // Channel for alerts, always warning severity + std::unordered_map minSeverity; + for (auto const& channel : Logger::kCHANNELS) + minSeverity[channel] = defaultSeverity; + minSeverity["Alert"] = Severity::WRN; // Channel for alerts, always warning severity auto const overrides = config.getArray("log_channels"); for (auto it = overrides.begin(); it != overrides.end(); ++it) { auto const& cfg = *it; auto name = cfg.get("channel"); - if (std::count(std::begin(Logger::CHANNELS), std::end(Logger::CHANNELS), name) == 0) + if (std::count(std::begin(Logger::kCHANNELS), std::end(Logger::kCHANNELS), name) == 0) throw std::runtime_error("Can't override settings for log channel " + name + ": invalid channel"); - min_severity[name] = getSeverityLevel(config.get("log_level")); + minSeverity[name] = getSeverityLevel(config.get("log_level")); } - auto log_filter = [min_severity = std::move(min_severity), - defaultSeverity](boost::log::attribute_value_set const& attributes) -> bool { - auto const channel = attributes[log_channel]; - auto const severity = attributes[log_severity]; + auto logFilter = [minSeverity = std::move(minSeverity), + defaultSeverity](boost::log::attribute_value_set const& attributes) -> bool { + auto const channel = attributes[LogChannel]; + auto const severity = attributes[LogSeverity]; if (!channel || !severity) return false; - if (auto const it = min_severity.find(channel.get()); it != min_severity.end()) + if (auto const it = minSeverity.find(channel.get()); it != minSeverity.end()) return severity.get() >= it->second; return severity.get() >= defaultSeverity; }; - filter_ = boost::log::filter{std::move(log_filter)}; - boost::log::core::get()->set_filter(filter_); + filter = boost::log::filter{std::move(logFilter)}; + boost::log::core::get()->set_filter(filter); LOG(LogService::info()) << "Default log level = " << defaultSeverity; } @@ -220,16 +220,16 @@ Logger::fatal(SourceLocationType const& loc) const }; std::string -Logger::Pump::pretty_path(SourceLocationType const& loc, size_t max_depth) +Logger::Pump::prettyPath(SourceLocationType const& loc, size_t maxDepth) { - auto const file_path = std::string{loc.file_name()}; - auto idx = file_path.size(); - while (max_depth-- > 0) { - idx = file_path.rfind('/', idx - 1); + auto const filePath = std::string{loc.file_name()}; + auto idx = filePath.size(); + while (maxDepth-- > 0) { + idx = filePath.rfind('/', idx - 1); if (idx == std::string::npos || idx == 0) break; } - return file_path.substr(idx == std::string::npos ? 0 : idx + 1) + ':' + std::to_string(loc.line()); + return filePath.substr(idx == std::string::npos ? 0 : idx + 1) + ':' + std::to_string(loc.line()); } } // namespace util diff --git a/src/util/log/Logger.hpp b/src/util/log/Logger.hpp index 493056c6..a3df8ffa 100644 --- a/src/util/log/Logger.hpp +++ b/src/util/log/Logger.hpp @@ -83,8 +83,10 @@ enum class Severity { }; /** @cond */ -BOOST_LOG_ATTRIBUTE_KEYWORD(log_severity, "Severity", Severity); -BOOST_LOG_ATTRIBUTE_KEYWORD(log_channel, "Channel", std::string); +// NOLINTBEGIN(readability-identifier-naming) +BOOST_LOG_ATTRIBUTE_KEYWORD(LogSeverity, "Severity", Severity); +BOOST_LOG_ATTRIBUTE_KEYWORD(LogChannel, "Channel", std::string); +// NOLINTEND(readability-identifier-naming) /** @endcond */ /** @@ -128,7 +130,7 @@ class Logger final { { if (rec_) { pump_.emplace(boost::log::aux::make_record_pump(logger, rec_)); - pump_->stream() << boost::log::add_value("SourceLocation", pretty_path(loc)); + pump_->stream() << boost::log::add_value("SourceLocation", prettyPath(loc)); } } @@ -165,11 +167,11 @@ class Logger final { private: [[nodiscard]] static std::string - pretty_path(SourceLocationType const& loc, size_t max_depth = 3); + prettyPath(SourceLocationType const& loc, size_t maxDepth = 3); }; public: - static constexpr std::array CHANNELS = { + static constexpr std::array kCHANNELS = { "General", "WebServer", "Backend", @@ -265,9 +267,9 @@ public: * entrypoint for logging into the `General` channel as well as raising alerts. */ class LogService { - static Logger general_log_; /*< Global logger for General channel */ - static Logger alert_log_; /*< Global logger for Alerts channel */ - static boost::log::filter filter_; + static Logger generalLog; /*< Global logger for General channel */ + static Logger alertLog; /*< Global logger for Alerts channel */ + static boost::log::filter filter; public: LogService() = delete; @@ -289,7 +291,7 @@ public: [[nodiscard]] static Logger::Pump trace(SourceLocationType const& loc = CURRENT_SRC_LOCATION) { - return general_log_.trace(loc); + return generalLog.trace(loc); } /** @@ -301,7 +303,7 @@ public: [[nodiscard]] static Logger::Pump debug(SourceLocationType const& loc = CURRENT_SRC_LOCATION) { - return general_log_.debug(loc); + return generalLog.debug(loc); } /** @@ -313,7 +315,7 @@ public: [[nodiscard]] static Logger::Pump info(SourceLocationType const& loc = CURRENT_SRC_LOCATION) { - return general_log_.info(loc); + return generalLog.info(loc); } /** @@ -325,7 +327,7 @@ public: [[nodiscard]] static Logger::Pump warn(SourceLocationType const& loc = CURRENT_SRC_LOCATION) { - return general_log_.warn(loc); + return generalLog.warn(loc); } /** @@ -337,7 +339,7 @@ public: [[nodiscard]] static Logger::Pump error(SourceLocationType const& loc = CURRENT_SRC_LOCATION) { - return general_log_.error(loc); + return generalLog.error(loc); } /** @@ -349,7 +351,7 @@ public: [[nodiscard]] static Logger::Pump fatal(SourceLocationType const& loc = CURRENT_SRC_LOCATION) { - return general_log_.fatal(loc); + return generalLog.fatal(loc); } /** @@ -361,7 +363,7 @@ public: [[nodiscard]] static Logger::Pump alert(SourceLocationType const& loc = CURRENT_SRC_LOCATION) { - return alert_log_.warn(loc); + return alertLog.warn(loc); } }; diff --git a/src/util/newconfig/ConfigConstraints.cpp b/src/util/newconfig/ConfigConstraints.cpp index 3c1507b0..66e91771 100644 --- a/src/util/newconfig/ConfigConstraints.cpp +++ b/src/util/newconfig/ConfigConstraints.cpp @@ -52,7 +52,7 @@ PortConstraint::checkValueImpl(Value const& port) const } else { p = static_cast(std::get(port)); } - if (p >= portMin && p <= portMax) + if (p >= kPORT_MIN && p <= kPORT_MAX) return std::nullopt; return Error{"Port does not satisfy the constraint bounds"}; } @@ -71,14 +71,14 @@ ValidIPConstraint::checkValueImpl(Value const& ip) const if (std::get(ip) == "localhost") return std::nullopt; - static std::regex const ipv4( + static std::regex const kIPV4( R"(^((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])$)" ); - static std::regex const ip_url( + static std::regex const kIP_URL( R"(^((http|https):\/\/)?((([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,6})|(((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])))(:\d{1,5})?(\/[^\s]*)?$)" ); - if (std::regex_match(std::get(ip), ipv4) || std::regex_match(std::get(ip), ip_url)) + if (std::regex_match(std::get(ip), kIPV4) || std::regex_match(std::get(ip), kIP_URL)) return std::nullopt; return Error{"Ip is not a valid ip address"}; diff --git a/src/util/newconfig/ConfigConstraints.hpp b/src/util/newconfig/ConfigConstraints.hpp index a7adc1f6..85d7b48e 100644 --- a/src/util/newconfig/ConfigConstraints.hpp +++ b/src/util/newconfig/ConfigConstraints.hpp @@ -44,7 +44,7 @@ class ConfigValue; /** * @brief specific values that are accepted for logger levels in config. */ -static constexpr std::array LOG_LEVELS = { +static constexpr std::array kLOG_LEVELS = { "trace", "debug", "info", @@ -57,7 +57,7 @@ static constexpr std::array LOG_LEVELS = { /** * @brief specific values that are accepted for logger tag style in config. */ -static constexpr std::array LOG_TAGS = { +static constexpr std::array kLOG_TAGS = { "int", "uint", "null", @@ -68,7 +68,7 @@ static constexpr std::array LOG_TAGS = { /** * @brief specific values that are accepted for cache loading in config. */ -static constexpr std::array LOAD_CACHE_MODE = { +static constexpr std::array kLOAD_CACHE_MODE = { "sync", "async", "none", @@ -77,12 +77,12 @@ static constexpr std::array LOAD_CACHE_MODE = { /** * @brief specific values that are accepted for database type in config. */ -static constexpr std::array DATABASE_TYPE = {"cassandra"}; +static constexpr std::array kDATABASE_TYPE = {"cassandra"}; /** * @brief specific values that are accepted for server's processing_policy in config. */ -static constexpr std::array PROCESSING_POLICY = {"parallel", "sequent"}; +static constexpr std::array kPROCESSING_POLICY = {"parallel", "sequent"}; /** * @brief An interface to enforce constraints on certain values within ClioConfigDefinition. @@ -116,9 +116,9 @@ protected: * @param arr The array with hard-coded values to add to error message * @return The error message specifying what the value of key must be */ - template + template constexpr std::string - makeErrorMsg(std::string_view key, Value const& value, std::array arr) const + makeErrorMsg(std::string_view key, Value const& value, std::array arr) const { // Extract the value from the variant auto const valueStr = std::visit([](auto const& v) { return fmt::format("{}", v); }, value); @@ -177,8 +177,8 @@ private: [[nodiscard]] std::optional checkValueImpl(Value const& port) const override; - static constexpr uint32_t portMin = 1; - static constexpr uint32_t portMax = 65535; + static constexpr uint32_t kPORT_MIN = 1; + static constexpr uint32_t kPORT_MAX = 65535; }; /** @@ -213,7 +213,7 @@ private: * * @tparam arrSize The size of the array containing the valid values for the constraint */ -template +template class OneOf final : public Constraint { public: /** @@ -222,7 +222,7 @@ public: * @param key The key of the ConfigValue that has this constraint * @param arr The value that has this constraint must be of the values in arr */ - constexpr OneOf(std::string_view key, std::array arr) : key_{key}, arr_{arr} + constexpr OneOf(std::string_view key, std::array arr) : key_{key}, arr_{arr} { } @@ -261,13 +261,13 @@ private: } std::string_view key_; - std::array arr_; + std::array arr_; }; /** * @brief A constraint class to ensure an integer value is between two numbers (inclusive) */ -template +template class NumberValueConstraint final : public Constraint { public: /** @@ -276,7 +276,7 @@ public: * @param min the minimum number it can be to satisfy this constraint * @param max the maximum number it can be to satisfy this constraint */ - constexpr NumberValueConstraint(numType min, numType max) : min_{min}, max_{max} + constexpr NumberValueConstraint(NumType min, NumType max) : min_{min}, max_{max} { } @@ -312,8 +312,8 @@ private: return Error{fmt::format("Number must be between {} and {}", min_, max_)}; } - numType min_; - numType max_; + NumType min_; + NumType max_; }; /** @@ -343,29 +343,29 @@ private: checkValueImpl(Value const& num) const override; }; -static constinit PortConstraint validatePort{}; -static constinit ValidIPConstraint validateIP{}; +static constinit PortConstraint gValidatePort{}; +static constinit ValidIPConstraint gValidateIp{}; -static constinit OneOf validateChannelName{"channel", Logger::CHANNELS}; -static constinit OneOf validateLogLevelName{"log_level", LOG_LEVELS}; -static constinit OneOf validateCassandraName{"database.type", DATABASE_TYPE}; -static constinit OneOf validateLoadMode{"cache.load", LOAD_CACHE_MODE}; -static constinit OneOf validateLogTag{"log_tag_style", LOG_TAGS}; -static constinit OneOf validateProcessingPolicy{"server.processing_policy", PROCESSING_POLICY}; +static constinit OneOf gValidateChannelName{"channel", Logger::kCHANNELS}; +static constinit OneOf gValidateLogLevelName{"log_level", kLOG_LEVELS}; +static constinit OneOf gValidateCassandraName{"database.type", kDATABASE_TYPE}; +static constinit OneOf gValidateLoadMode{"cache.load", kLOAD_CACHE_MODE}; +static constinit OneOf gValidateLogTag{"log_tag_style", kLOG_TAGS}; +static constinit OneOf gValidateProcessingPolicy{"server.processing_policy", kPROCESSING_POLICY}; -static constinit PositiveDouble validatePositiveDouble{}; +static constinit PositiveDouble gValidatePositiveDouble{}; -static constinit NumberValueConstraint validateNumMarkers{1, 256}; -static constinit NumberValueConstraint validateIOThreads{1, std::numeric_limits::max()}; +static constinit NumberValueConstraint gValidateNumMarkers{1, 256}; +static constinit NumberValueConstraint gValidateIOThreads{1, std::numeric_limits::max()}; -static constinit NumberValueConstraint validateUint16{ +static constinit NumberValueConstraint gValidateUint16{ std::numeric_limits::min(), std::numeric_limits::max() }; -static constinit NumberValueConstraint validateUint32{ +static constinit NumberValueConstraint gValidateUint32{ std::numeric_limits::min(), std::numeric_limits::max() }; -static constinit NumberValueConstraint validateApiVersion{rpc::API_VERSION_MIN, rpc::API_VERSION_MAX}; +static constinit NumberValueConstraint gValidateApiVersion{rpc::kAPI_VERSION_MIN, rpc::kAPI_VERSION_MAX}; } // namespace util::config diff --git a/src/util/newconfig/ConfigDefinition.cpp b/src/util/newconfig/ConfigDefinition.cpp index 921a6185..bad33717 100644 --- a/src/util/newconfig/ConfigDefinition.cpp +++ b/src/util/newconfig/ConfigDefinition.cpp @@ -121,7 +121,7 @@ std::chrono::milliseconds ClioConfigDefinition::toMilliseconds(float value) { ASSERT(value >= 0.0f, "Floating point value of seconds must be non-negative, got: {}", value); - return std::chrono::milliseconds{std::lroundf(value * static_cast(util::MILLISECONDS_PER_SECOND))}; + return std::chrono::milliseconds{std::lroundf(value * static_cast(util::kMILLISECONDS_PER_SECOND))}; } ValueView diff --git a/src/util/newconfig/ConfigDefinition.hpp b/src/util/newconfig/ConfigDefinition.hpp index cd20921e..2766e767 100644 --- a/src/util/newconfig/ConfigDefinition.hpp +++ b/src/util/newconfig/ConfigDefinition.hpp @@ -285,67 +285,71 @@ private: * Specifies which keys are valid in Clio Config and provides default values if user's do not specify one. Those * without default values must be present in the user's config file. */ -static ClioConfigDefinition ClioConfig = ClioConfigDefinition{ - {{"database.type", ConfigValue{ConfigType::String}.defaultValue("cassandra").withConstraint(validateCassandraName)}, +static ClioConfigDefinition gClioConfig = ClioConfigDefinition{ + {{"database.type", ConfigValue{ConfigType::String}.defaultValue("cassandra").withConstraint(gValidateCassandraName) + }, {"database.cassandra.contact_points", ConfigValue{ConfigType::String}.defaultValue("localhost")}, {"database.cassandra.secure_connect_bundle", ConfigValue{ConfigType::String}.optional()}, - {"database.cassandra.port", ConfigValue{ConfigType::Integer}.withConstraint(validatePort).optional()}, + {"database.cassandra.port", ConfigValue{ConfigType::Integer}.withConstraint(gValidatePort).optional()}, {"database.cassandra.keyspace", ConfigValue{ConfigType::String}.defaultValue("clio")}, {"database.cassandra.replication_factor", - ConfigValue{ConfigType::Integer}.defaultValue(3u).withConstraint(validateUint16)}, + ConfigValue{ConfigType::Integer}.defaultValue(3u).withConstraint(gValidateUint16)}, {"database.cassandra.table_prefix", ConfigValue{ConfigType::String}.optional()}, {"database.cassandra.max_write_requests_outstanding", - ConfigValue{ConfigType::Integer}.defaultValue(10'000).withConstraint(validateUint32)}, + ConfigValue{ConfigType::Integer}.defaultValue(10'000).withConstraint(gValidateUint32)}, {"database.cassandra.max_read_requests_outstanding", - ConfigValue{ConfigType::Integer}.defaultValue(100'000).withConstraint(validateUint32)}, + ConfigValue{ConfigType::Integer}.defaultValue(100'000).withConstraint(gValidateUint32)}, {"database.cassandra.threads", ConfigValue{ConfigType::Integer} .defaultValue(static_cast(std::thread::hardware_concurrency())) - .withConstraint(validateUint32)}, + .withConstraint(gValidateUint32)}, {"database.cassandra.core_connections_per_host", - ConfigValue{ConfigType::Integer}.defaultValue(1).withConstraint(validateUint16)}, - {"database.cassandra.queue_size_io", ConfigValue{ConfigType::Integer}.optional().withConstraint(validateUint16)}, + ConfigValue{ConfigType::Integer}.defaultValue(1).withConstraint(gValidateUint16)}, + {"database.cassandra.queue_size_io", ConfigValue{ConfigType::Integer}.optional().withConstraint(gValidateUint16)}, {"database.cassandra.write_batch_size", - ConfigValue{ConfigType::Integer}.defaultValue(20).withConstraint(validateUint16)}, - {"database.cassandra.connect_timeout", ConfigValue{ConfigType::Integer}.optional().withConstraint(validateUint32)}, - {"database.cassandra.request_timeout", ConfigValue{ConfigType::Integer}.optional().withConstraint(validateUint32)}, + ConfigValue{ConfigType::Integer}.defaultValue(20).withConstraint(gValidateUint16)}, + {"database.cassandra.connect_timeout", ConfigValue{ConfigType::Integer}.optional().withConstraint(gValidateUint32) + }, + {"database.cassandra.request_timeout", ConfigValue{ConfigType::Integer}.optional().withConstraint(gValidateUint32) + }, {"database.cassandra.username", ConfigValue{ConfigType::String}.optional()}, {"database.cassandra.password", ConfigValue{ConfigType::String}.optional()}, {"database.cassandra.certfile", ConfigValue{ConfigType::String}.optional()}, {"allow_no_etl", ConfigValue{ConfigType::Boolean}.defaultValue(false)}, - {"etl_sources.[].ip", Array{ConfigValue{ConfigType::String}.optional().withConstraint(validateIP)}}, - {"etl_sources.[].ws_port", Array{ConfigValue{ConfigType::String}.optional().withConstraint(validatePort)}}, - {"etl_sources.[].grpc_port", Array{ConfigValue{ConfigType::String}.optional().withConstraint(validatePort)}}, + {"etl_sources.[].ip", Array{ConfigValue{ConfigType::String}.optional().withConstraint(gValidateIp)}}, + {"etl_sources.[].ws_port", Array{ConfigValue{ConfigType::String}.optional().withConstraint(gValidatePort)}}, + {"etl_sources.[].grpc_port", Array{ConfigValue{ConfigType::String}.optional().withConstraint(gValidatePort)}}, {"forwarding.cache_timeout", - ConfigValue{ConfigType::Double}.defaultValue(0.0).withConstraint(validatePositiveDouble)}, + ConfigValue{ConfigType::Double}.defaultValue(0.0).withConstraint(gValidatePositiveDouble)}, {"forwarding.request_timeout", - ConfigValue{ConfigType::Double}.defaultValue(10.0).withConstraint(validatePositiveDouble)}, + ConfigValue{ConfigType::Double}.defaultValue(10.0).withConstraint(gValidatePositiveDouble)}, - {"rpc.cache_timeout", ConfigValue{ConfigType::Double}.defaultValue(0.0).withConstraint(validatePositiveDouble)}, + {"rpc.cache_timeout", ConfigValue{ConfigType::Double}.defaultValue(0.0).withConstraint(gValidatePositiveDouble)}, - {"num_markers", ConfigValue{ConfigType::Integer}.optional().withConstraint(validateNumMarkers)}, + {"num_markers", ConfigValue{ConfigType::Integer}.optional().withConstraint(gValidateNumMarkers)}, {"dos_guard.whitelist.[]", Array{ConfigValue{ConfigType::String}.optional()}}, - {"dos_guard.max_fetches", ConfigValue{ConfigType::Integer}.defaultValue(1000'000u).withConstraint(validateUint32)}, - {"dos_guard.max_connections", ConfigValue{ConfigType::Integer}.defaultValue(20u).withConstraint(validateUint32)}, - {"dos_guard.max_requests", ConfigValue{ConfigType::Integer}.defaultValue(20u).withConstraint(validateUint32)}, + {"dos_guard.max_fetches", ConfigValue{ConfigType::Integer}.defaultValue(1000'000u).withConstraint(gValidateUint32) + }, + {"dos_guard.max_connections", ConfigValue{ConfigType::Integer}.defaultValue(20u).withConstraint(gValidateUint32)}, + {"dos_guard.max_requests", ConfigValue{ConfigType::Integer}.defaultValue(20u).withConstraint(gValidateUint32)}, {"dos_guard.sweep_interval", - ConfigValue{ConfigType::Double}.defaultValue(1.0).withConstraint(validatePositiveDouble)}, + ConfigValue{ConfigType::Double}.defaultValue(1.0).withConstraint(gValidatePositiveDouble)}, {"workers", - ConfigValue{ConfigType::Integer}.defaultValue(std::thread::hardware_concurrency()).withConstraint(validateUint32) + ConfigValue{ConfigType::Integer}.defaultValue(std::thread::hardware_concurrency()).withConstraint(gValidateUint32) }, - {"server.ip", ConfigValue{ConfigType::String}.withConstraint(validateIP)}, - {"server.port", ConfigValue{ConfigType::Integer}.withConstraint(validatePort)}, - {"server.max_queue_size", ConfigValue{ConfigType::Integer}.defaultValue(0).withConstraint(validateUint32)}, + {"server.ip", ConfigValue{ConfigType::String}.withConstraint(gValidateIp)}, + {"server.port", ConfigValue{ConfigType::Integer}.withConstraint(gValidatePort)}, + {"server.max_queue_size", ConfigValue{ConfigType::Integer}.defaultValue(0).withConstraint(gValidateUint32)}, {"server.local_admin", ConfigValue{ConfigType::Boolean}.optional()}, {"server.admin_password", ConfigValue{ConfigType::String}.optional()}, {"server.processing_policy", - ConfigValue{ConfigType::String}.defaultValue("parallel").withConstraint(validateProcessingPolicy)}, + ConfigValue{ConfigType::String}.defaultValue("parallel").withConstraint(gValidateProcessingPolicy)}, {"server.parallel_requests_limit", ConfigValue{ConfigType::Integer}.optional()}, {"server.ws_max_sending_queue_size", ConfigValue{ConfigType::Integer}.defaultValue(1500)}, {"server.__ng_web_server", ConfigValue{ConfigType::Boolean}.defaultValue(false)}, @@ -353,25 +357,26 @@ static ClioConfigDefinition ClioConfig = ClioConfigDefinition{ {"prometheus.enabled", ConfigValue{ConfigType::Boolean}.defaultValue(true)}, {"prometheus.compress_reply", ConfigValue{ConfigType::Boolean}.defaultValue(true)}, - {"io_threads", ConfigValue{ConfigType::Integer}.defaultValue(2).withConstraint(validateIOThreads)}, + {"io_threads", ConfigValue{ConfigType::Integer}.defaultValue(2).withConstraint(gValidateIOThreads)}, - {"subscription_workers", ConfigValue{ConfigType::Integer}.defaultValue(1).withConstraint(validateUint32)}, + {"subscription_workers", ConfigValue{ConfigType::Integer}.defaultValue(1).withConstraint(gValidateUint32)}, - {"graceful_period", ConfigValue{ConfigType::Double}.defaultValue(10.0).withConstraint(validatePositiveDouble)}, + {"graceful_period", ConfigValue{ConfigType::Double}.defaultValue(10.0).withConstraint(gValidatePositiveDouble)}, - {"cache.num_diffs", ConfigValue{ConfigType::Integer}.defaultValue(32).withConstraint(validateUint16)}, - {"cache.num_markers", ConfigValue{ConfigType::Integer}.defaultValue(48).withConstraint(validateUint16)}, - {"cache.num_cursors_from_diff", ConfigValue{ConfigType::Integer}.defaultValue(0).withConstraint(validateUint16)}, - {"cache.num_cursors_from_account", ConfigValue{ConfigType::Integer}.defaultValue(0).withConstraint(validateUint16) + {"cache.num_diffs", ConfigValue{ConfigType::Integer}.defaultValue(32).withConstraint(gValidateUint16)}, + {"cache.num_markers", ConfigValue{ConfigType::Integer}.defaultValue(48).withConstraint(gValidateUint16)}, + {"cache.num_cursors_from_diff", ConfigValue{ConfigType::Integer}.defaultValue(0).withConstraint(gValidateUint16)}, + {"cache.num_cursors_from_account", ConfigValue{ConfigType::Integer}.defaultValue(0).withConstraint(gValidateUint16) }, - {"cache.page_fetch_size", ConfigValue{ConfigType::Integer}.defaultValue(512).withConstraint(validateUint16)}, - {"cache.load", ConfigValue{ConfigType::String}.defaultValue("async").withConstraint(validateLoadMode)}, + {"cache.page_fetch_size", ConfigValue{ConfigType::Integer}.defaultValue(512).withConstraint(gValidateUint16)}, + {"cache.load", ConfigValue{ConfigType::String}.defaultValue("async").withConstraint(gValidateLoadMode)}, - {"log_channels.[].channel", Array{ConfigValue{ConfigType::String}.optional().withConstraint(validateChannelName)}}, + {"log_channels.[].channel", Array{ConfigValue{ConfigType::String}.optional().withConstraint(gValidateChannelName)} + }, {"log_channels.[].log_level", - Array{ConfigValue{ConfigType::String}.optional().withConstraint(validateLogLevelName)}}, + Array{ConfigValue{ConfigType::String}.optional().withConstraint(gValidateLogLevelName)}}, - {"log_level", ConfigValue{ConfigType::String}.defaultValue("info").withConstraint(validateLogLevelName)}, + {"log_level", ConfigValue{ConfigType::String}.defaultValue("info").withConstraint(gValidateLogLevelName)}, {"log_format", ConfigValue{ConfigType::String}.defaultValue( @@ -382,38 +387,38 @@ static ClioConfigDefinition ClioConfig = ClioConfigDefinition{ {"log_directory", ConfigValue{ConfigType::String}.optional()}, - {"log_rotation_size", ConfigValue{ConfigType::Integer}.defaultValue(2048).withConstraint(validateUint32)}, + {"log_rotation_size", ConfigValue{ConfigType::Integer}.defaultValue(2048).withConstraint(gValidateUint32)}, - {"log_directory_max_size", ConfigValue{ConfigType::Integer}.defaultValue(50 * 1024).withConstraint(validateUint32) + {"log_directory_max_size", ConfigValue{ConfigType::Integer}.defaultValue(50 * 1024).withConstraint(gValidateUint32) }, - {"log_rotation_hour_interval", ConfigValue{ConfigType::Integer}.defaultValue(12).withConstraint(validateUint32)}, + {"log_rotation_hour_interval", ConfigValue{ConfigType::Integer}.defaultValue(12).withConstraint(gValidateUint32)}, - {"log_tag_style", ConfigValue{ConfigType::String}.defaultValue("none").withConstraint(validateLogTag)}, + {"log_tag_style", ConfigValue{ConfigType::String}.defaultValue("none").withConstraint(gValidateLogTag)}, - {"extractor_threads", ConfigValue{ConfigType::Integer}.defaultValue(1u).withConstraint(validateUint32)}, + {"extractor_threads", ConfigValue{ConfigType::Integer}.defaultValue(1u).withConstraint(gValidateUint32)}, {"read_only", ConfigValue{ConfigType::Boolean}.defaultValue(false)}, - {"txn_threshold", ConfigValue{ConfigType::Integer}.defaultValue(0).withConstraint(validateUint16)}, + {"txn_threshold", ConfigValue{ConfigType::Integer}.defaultValue(0).withConstraint(gValidateUint16)}, - {"start_sequence", ConfigValue{ConfigType::Integer}.optional().withConstraint(validateUint32)}, + {"start_sequence", ConfigValue{ConfigType::Integer}.optional().withConstraint(gValidateUint32)}, - {"finish_sequence", ConfigValue{ConfigType::Integer}.optional().withConstraint(validateUint32)}, + {"finish_sequence", ConfigValue{ConfigType::Integer}.optional().withConstraint(gValidateUint32)}, {"ssl_cert_file", ConfigValue{ConfigType::String}.optional()}, {"ssl_key_file", ConfigValue{ConfigType::String}.optional()}, {"api_version.default", - ConfigValue{ConfigType::Integer}.defaultValue(rpc::API_VERSION_DEFAULT).withConstraint(validateApiVersion)}, + ConfigValue{ConfigType::Integer}.defaultValue(rpc::kAPI_VERSION_DEFAULT).withConstraint(gValidateApiVersion)}, {"api_version.min", - ConfigValue{ConfigType::Integer}.defaultValue(rpc::API_VERSION_MIN).withConstraint(validateApiVersion)}, + ConfigValue{ConfigType::Integer}.defaultValue(rpc::kAPI_VERSION_MIN).withConstraint(gValidateApiVersion)}, {"api_version.max", - ConfigValue{ConfigType::Integer}.defaultValue(rpc::API_VERSION_MAX).withConstraint(validateApiVersion)}, - {"migration.full_scan_threads", ConfigValue{ConfigType::Integer}.defaultValue(2).withConstraint(validateUint32)}, - {"migration.full_scan_jobs", ConfigValue{ConfigType::Integer}.defaultValue(4).withConstraint(validateUint32)}, - {"migration.cursors_per_job", ConfigValue{ConfigType::Integer}.defaultValue(100).withConstraint(validateUint32)}}, + ConfigValue{ConfigType::Integer}.defaultValue(rpc::kAPI_VERSION_MAX).withConstraint(gValidateApiVersion)}, + {"migration.full_scan_threads", ConfigValue{ConfigType::Integer}.defaultValue(2).withConstraint(gValidateUint32)}, + {"migration.full_scan_jobs", ConfigValue{ConfigType::Integer}.defaultValue(4).withConstraint(gValidateUint32)}, + {"migration.cursors_per_job", ConfigValue{ConfigType::Integer}.defaultValue(100).withConstraint(gValidateUint32)}}, }; diff --git a/src/util/newconfig/ConfigDescription.hpp b/src/util/newconfig/ConfigDescription.hpp index 79b43dbf..71335a66 100644 --- a/src/util/newconfig/ConfigDescription.hpp +++ b/src/util/newconfig/ConfigDescription.hpp @@ -56,13 +56,13 @@ public: [[nodiscard]] static constexpr std::string_view get(std::string_view key) { - auto const itr = std::ranges::find_if(configDescription, [&](auto const& v) { return v.key == key; }); - ASSERT(itr != configDescription.end(), "Key {} doesn't exist in config", key); + auto const itr = std::ranges::find_if(kCONFIG_DESCRIPTION, [&](auto const& v) { return v.key == key; }); + ASSERT(itr != kCONFIG_DESCRIPTION.end(), "Key {} doesn't exist in config", key); return itr->value; } private: - static constexpr auto configDescription = std::array{ + static constexpr auto kCONFIG_DESCRIPTION = std::array{ KV{.key = "database.type", .value = "Type of database to use. Default is Scylladb."}, KV{.key = "database.cassandra.contact_points", .value = diff --git a/src/util/newconfig/ConfigFileJson.cpp b/src/util/newconfig/ConfigFileJson.cpp index 4bd5c6ef..ada59e09 100644 --- a/src/util/newconfig/ConfigFileJson.cpp +++ b/src/util/newconfig/ConfigFileJson.cpp @@ -82,7 +82,7 @@ ConfigFileJson::ConfigFileJson(boost::json::object jsonObj) } std::expected -ConfigFileJson::make_ConfigFileJson(boost::filesystem::path configFilePath) +ConfigFileJson::makeConfigFileJson(boost::filesystem::path configFilePath) { try { if (auto const in = std::ifstream(configFilePath.string(), std::ios::in | std::ios::binary); in) { diff --git a/src/util/newconfig/ConfigFileJson.hpp b/src/util/newconfig/ConfigFileJson.hpp index a2703754..83a3b658 100644 --- a/src/util/newconfig/ConfigFileJson.hpp +++ b/src/util/newconfig/ConfigFileJson.hpp @@ -79,7 +79,7 @@ public: * @return A ConfigFileJson object if parsing user file is successful. Error otherwise */ [[nodiscard]] static std::expected - make_ConfigFileJson(boost::filesystem::path configFilePath); + makeConfigFileJson(boost::filesystem::path configFilePath); private: /** diff --git a/src/util/newconfig/ConfigValue.hpp b/src/util/newconfig/ConfigValue.hpp index 8b80db47..d68daaa6 100644 --- a/src/util/newconfig/ConfigValue.hpp +++ b/src/util/newconfig/ConfigValue.hpp @@ -175,8 +175,7 @@ public: * * @return true if optional, false otherwise */ - [[nodiscard]] constexpr bool - isOptional() const + [[nodiscard]] bool constexpr isOptional() const { return optional_; } @@ -186,8 +185,7 @@ public: * * @return if value is optiona, false otherwise */ - [[nodiscard]] constexpr bool - hasValue() const + [[nodiscard]] bool constexpr hasValue() const { return value_.has_value(); } diff --git a/src/util/newconfig/ValueView.hpp b/src/util/newconfig/ValueView.hpp index 534b03f0..078296fa 100644 --- a/src/util/newconfig/ValueView.hpp +++ b/src/util/newconfig/ValueView.hpp @@ -126,8 +126,7 @@ public: * * @return true if exists, false otherwise */ - [[nodiscard]] constexpr bool - hasValue() const + [[nodiscard]] bool constexpr hasValue() const { return configVal_.get().hasValue(); } @@ -137,8 +136,7 @@ public: * * @return true if optional, false otherwise */ - [[nodiscard]] constexpr bool - isOptional() const + [[nodiscard]] bool constexpr isOptional() const { return configVal_.get().isOptional(); } diff --git a/src/util/prometheus/MetricBase.cpp b/src/util/prometheus/MetricBase.cpp index f7d99700..397df87a 100644 --- a/src/util/prometheus/MetricBase.cpp +++ b/src/util/prometheus/MetricBase.cpp @@ -43,19 +43,19 @@ char const* toString(MetricType type) { switch (type) { - case MetricType::COUNTER_INT: + case MetricType::CounterInt: [[fallthrough]]; - case MetricType::COUNTER_DOUBLE: + case MetricType::CounterDouble: return "counter"; - case MetricType::GAUGE_INT: + case MetricType::GaugeInt: [[fallthrough]]; - case MetricType::GAUGE_DOUBLE: + case MetricType::GaugeDouble: return "gauge"; - case MetricType::HISTOGRAM_INT: + case MetricType::HistogramInt: [[fallthrough]]; - case MetricType::HISTOGRAM_DOUBLE: + case MetricType::HistogramDouble: return "histogram"; - case MetricType::SUMMARY: + case MetricType::Summary: return "summary"; default: ASSERT(false, "Unknown metric {}.", static_cast(type)); diff --git a/src/util/prometheus/MetricBase.hpp b/src/util/prometheus/MetricBase.hpp index 5fc1d524..befc7777 100644 --- a/src/util/prometheus/MetricBase.hpp +++ b/src/util/prometheus/MetricBase.hpp @@ -83,15 +83,7 @@ private: std::string labelsString_; }; -enum class MetricType { - COUNTER_INT, - COUNTER_DOUBLE, - GAUGE_INT, - GAUGE_DOUBLE, - HISTOGRAM_INT, - HISTOGRAM_DOUBLE, - SUMMARY -}; +enum class MetricType { CounterInt, CounterDouble, GaugeInt, GaugeDouble, HistogramInt, HistogramDouble, Summary }; char const* toString(MetricType type); diff --git a/src/util/prometheus/MetricBuilder.cpp b/src/util/prometheus/MetricBuilder.cpp index 5dafb988..52dc7567 100644 --- a/src/util/prometheus/MetricBuilder.cpp +++ b/src/util/prometheus/MetricBuilder.cpp @@ -42,8 +42,8 @@ MetricBuilder::operator()( std::vector const& buckets ) { - ASSERT(type != MetricType::HISTOGRAM_DOUBLE, "Wrong metric type. Probably wrong bucket type was used."); - if (type == MetricType::HISTOGRAM_INT) { + ASSERT(type != MetricType::HistogramDouble, "Wrong metric type. Probably wrong bucket type was used."); + if (type == MetricType::HistogramInt) { return makeHistogram(std::move(name), std::move(labelsString), type, buckets); } ASSERT(buckets.empty(), "Buckets must be empty for non-histogram types."); @@ -58,7 +58,7 @@ MetricBuilder::operator()( std::vector const& buckets ) { - ASSERT(type == MetricType::HISTOGRAM_DOUBLE, "This method is for HISTOGRAM_DOUBLE only."); + ASSERT(type == MetricType::HistogramDouble, "This method is for HISTOGRAM_DOUBLE only."); return makeHistogram(std::move(name), std::move(labelsString), type, buckets); } @@ -66,19 +66,19 @@ std::unique_ptr MetricBuilder::makeMetric(std::string name, std::string labelsString, MetricType const type) { switch (type) { - case MetricType::COUNTER_INT: + case MetricType::CounterInt: return std::make_unique(name, labelsString); - case MetricType::COUNTER_DOUBLE: + case MetricType::CounterDouble: return std::make_unique(name, labelsString); - case MetricType::GAUGE_INT: + case MetricType::GaugeInt: return std::make_unique(name, labelsString); - case MetricType::GAUGE_DOUBLE: + case MetricType::GaugeDouble: return std::make_unique(name, labelsString); - case MetricType::HISTOGRAM_INT: + case MetricType::HistogramInt: [[fallthrough]]; - case MetricType::HISTOGRAM_DOUBLE: + case MetricType::HistogramDouble: [[fallthrough]]; - case MetricType::SUMMARY: + case MetricType::Summary: [[fallthrough]]; default: ASSERT(false, "Unknown metric type: {}", static_cast(type)); @@ -97,7 +97,7 @@ MetricBuilder::makeHistogram( ) { switch (type) { - case MetricType::HISTOGRAM_INT: { + case MetricType::HistogramInt: { if constexpr (std::same_as) { return std::make_unique(std::move(name), std::move(labelsString), buckets); } else { @@ -105,22 +105,22 @@ MetricBuilder::makeHistogram( break; } } - case MetricType::HISTOGRAM_DOUBLE: + case MetricType::HistogramDouble: if constexpr (std::same_as) { return std::make_unique(std::move(name), std::move(labelsString), buckets); } else { ASSERT(false, "Wrong bucket type for HISTOGRAM_DOUBLE."); break; } - case MetricType::COUNTER_INT: + case MetricType::CounterInt: [[fallthrough]]; - case MetricType::COUNTER_DOUBLE: + case MetricType::CounterDouble: [[fallthrough]]; - case MetricType::GAUGE_INT: + case MetricType::GaugeInt: [[fallthrough]]; - case MetricType::GAUGE_DOUBLE: + case MetricType::GaugeDouble: [[fallthrough]]; - case MetricType::SUMMARY: + case MetricType::Summary: [[fallthrough]]; default: ASSERT(false, "Unknown metric type: {}", static_cast(type)); diff --git a/src/util/prometheus/MetricsFamily.cpp b/src/util/prometheus/MetricsFamily.cpp index 34c42cf7..1c02f6fd 100644 --- a/src/util/prometheus/MetricsFamily.cpp +++ b/src/util/prometheus/MetricsFamily.cpp @@ -56,7 +56,7 @@ MetricsFamily::getMetric(Labels labels, std::vector const& buckets MetricBase& MetricsFamily::getMetric(Labels labels, std::vector const& buckets) { - ASSERT(type_ == MetricType::HISTOGRAM_DOUBLE, "This method is for HISTOGRAM_DOUBLE only."); + ASSERT(type_ == MetricType::HistogramDouble, "This method is for HistogramDouble only."); return getMetricImpl(std::move(labels), buckets); } diff --git a/src/util/prometheus/Prometheus.cpp b/src/util/prometheus/Prometheus.cpp index 8898f9a7..806e52a7 100644 --- a/src/util/prometheus/Prometheus.cpp +++ b/src/util/prometheus/Prometheus.cpp @@ -65,7 +65,7 @@ CounterInt& PrometheusImpl::counterInt(std::string name, Labels labels, std::optional description) { MetricBase& metricBase = - getMetric(std::move(name), std::move(labels), std::move(description), MetricType::COUNTER_INT); + getMetric(std::move(name), std::move(labels), std::move(description), MetricType::CounterInt); return convertBaseTo(metricBase); } @@ -73,7 +73,7 @@ CounterDouble& PrometheusImpl::counterDouble(std::string name, Labels labels, std::optional description) { MetricBase& metricBase = - getMetric(std::move(name), std::move(labels), std::move(description), MetricType::COUNTER_DOUBLE); + getMetric(std::move(name), std::move(labels), std::move(description), MetricType::CounterDouble); return convertBaseTo(metricBase); } @@ -81,7 +81,7 @@ GaugeInt& PrometheusImpl::gaugeInt(std::string name, Labels labels, std::optional description) { MetricBase& metricBase = - getMetric(std::move(name), std::move(labels), std::move(description), MetricType::GAUGE_INT); + getMetric(std::move(name), std::move(labels), std::move(description), MetricType::GaugeInt); return convertBaseTo(metricBase); } @@ -89,7 +89,7 @@ GaugeDouble& PrometheusImpl::gaugeDouble(std::string name, Labels labels, std::optional description) { MetricBase& metricBase = - getMetric(std::move(name), std::move(labels), std::move(description), MetricType::GAUGE_DOUBLE); + getMetric(std::move(name), std::move(labels), std::move(description), MetricType::GaugeDouble); return convertBaseTo(metricBase); } @@ -102,7 +102,7 @@ PrometheusImpl::histogramInt( ) { MetricBase& metricBase = - getMetric(std::move(name), std::move(labels), std::move(description), MetricType::HISTOGRAM_INT, buckets); + getMetric(std::move(name), std::move(labels), std::move(description), MetricType::HistogramInt, buckets); return convertBaseTo(metricBase); } @@ -115,7 +115,7 @@ PrometheusImpl::histogramDouble( ) { MetricBase& metricBase = - getMetric(std::move(name), std::move(labels), std::move(description), MetricType::HISTOGRAM_DOUBLE, buckets); + getMetric(std::move(name), std::move(labels), std::move(description), MetricType::HistogramDouble, buckets); return convertBaseTo(metricBase); } @@ -181,7 +181,7 @@ PrometheusService::init(util::config::ClioConfigDefinition const& config) bool const enabled = config.get("prometheus.enabled"); bool const compressReply = config.get("prometheus.compress_reply"); - instance_ = std::make_unique(enabled, compressReply); + impl = std::make_unique(enabled, compressReply); } util::prometheus::Bool @@ -263,16 +263,16 @@ PrometheusService::compressReplyEnabled() } void -PrometheusService::replaceInstance(std::unique_ptr instance) +PrometheusService::replaceInstance(std::unique_ptr inst) { - instance_ = std::move(instance); + PrometheusService::impl = std::move(inst); } util::prometheus::PrometheusInterface& PrometheusService::instance() { - ASSERT(instance_ != nullptr, "PrometheusService::instance() called before init()"); - return *instance_; + ASSERT(impl != nullptr, "PrometheusService::instance() called before init()"); + return *impl; } -std::unique_ptr PrometheusService::instance_; +std::unique_ptr PrometheusService::impl; diff --git a/src/util/prometheus/Prometheus.hpp b/src/util/prometheus/Prometheus.hpp index c1bc1d8a..d295d955 100644 --- a/src/util/prometheus/Prometheus.hpp +++ b/src/util/prometheus/Prometheus.hpp @@ -394,10 +394,10 @@ public: * * @note Be careful with this method because there could be hanging references to counters * - * @param instance The new prometheus object + * @param inst The new prometheus object */ static void - replaceInstance(std::unique_ptr instance); + replaceInstance(std::unique_ptr inst); /** * @brief Get the prometheus object stored in the singleton @@ -408,5 +408,5 @@ public: instance(); private: - static std::unique_ptr instance_; + static std::unique_ptr impl; }; diff --git a/src/util/prometheus/impl/AnyCounterBase.hpp b/src/util/prometheus/impl/AnyCounterBase.hpp index 98dc81e4..b09f001b 100644 --- a/src/util/prometheus/impl/AnyCounterBase.hpp +++ b/src/util/prometheus/impl/AnyCounterBase.hpp @@ -19,8 +19,10 @@ #pragma once +#include "util/Concepts.hpp" #include "util/prometheus/impl/CounterImpl.hpp" +#include #include #include @@ -54,29 +56,29 @@ protected: struct Model : Concept { template requires std::same_as - Model(SomeImplType&& impl) : impl_(std::forward(impl)) + Model(SomeImplType&& impl) : impl(std::forward(impl)) { } void add(ValueType value) override { - impl_.add(value); + impl.add(value); } void set(ValueType v) override { - impl_.set(v); + impl.set(v); } ValueType value() const override { - return impl_.value(); + return impl.value(); } - ImplType impl_; + ImplType impl; }; std::unique_ptr pimpl_; diff --git a/src/util/requests/RequestBuilder.cpp b/src/util/requests/RequestBuilder.cpp index 922c5316..df4ba4e9 100644 --- a/src/util/requests/RequestBuilder.cpp +++ b/src/util/requests/RequestBuilder.cpp @@ -199,7 +199,7 @@ RequestBuilder::doRequestImpl(StreamDataType&& streamData, asio::yield_context y request_.method(method); - if constexpr (StreamDataType::sslEnabled) { + if constexpr (StreamDataType::kSSL_ENABLED) { beast::get_lowest_layer(stream).expires_after(timeout_); stream.async_handshake(asio::ssl::stream_base::client, yield[errorCode]); if (errorCode) diff --git a/src/util/requests/RequestBuilder.hpp b/src/util/requests/RequestBuilder.hpp index e1aeeed5..ef7cc61e 100644 --- a/src/util/requests/RequestBuilder.hpp +++ b/src/util/requests/RequestBuilder.hpp @@ -46,7 +46,7 @@ class RequestBuilder { util::Logger log_{"RequestBuilder"}; std::string host_; std::string port_; - std::chrono::milliseconds timeout_{DEFAULT_TIMEOUT}; + std::chrono::milliseconds timeout_{kDEFAULT_TIMEOUT}; boost::beast::http::request request_; public: @@ -181,7 +181,7 @@ public: std::expected post(boost::asio::yield_context yield); - static constexpr std::chrono::milliseconds DEFAULT_TIMEOUT{30000}; /**< Default timeout for requests */ + static constexpr std::chrono::milliseconds kDEFAULT_TIMEOUT{30000}; /**< Default timeout for requests */ private: std::expected diff --git a/src/util/requests/WsConnection.cpp b/src/util/requests/WsConnection.cpp index aca8ac50..1491844e 100644 --- a/src/util/requests/WsConnection.cpp +++ b/src/util/requests/WsConnection.cpp @@ -156,7 +156,7 @@ WsConnectionBuilder::connectImpl(StreamDataType&& streamData, asio::yield_contex if (errorCode) return std::unexpected{RequestError{"Connect error", errorCode}}; - if constexpr (StreamDataType::sslEnabled) { + if constexpr (StreamDataType::kSSL_ENABLED) { beast::get_lowest_layer(ws).expires_after(connectionTimeout_); ws.next_layer().async_handshake(asio::ssl::stream_base::client, yield[errorCode]); if (errorCode) @@ -179,7 +179,7 @@ WsConnectionBuilder::connectImpl(StreamDataType&& streamData, asio::yield_contex if (errorCode) return std::unexpected{RequestError{"Handshake error", errorCode}}; - if constexpr (StreamDataType::sslEnabled) { + if constexpr (StreamDataType::kSSL_ENABLED) { return std::make_unique(std::move(ws)); } else { return std::make_unique(std::move(ws)); diff --git a/src/util/requests/WsConnection.hpp b/src/util/requests/WsConnection.hpp index 5f232053..ddcf3cc5 100644 --- a/src/util/requests/WsConnection.hpp +++ b/src/util/requests/WsConnection.hpp @@ -85,9 +85,9 @@ public: * @return Error if any */ virtual std::optional - close(boost::asio::yield_context yield, std::chrono::steady_clock::duration timeout = DEFAULT_TIMEOUT) = 0; + close(boost::asio::yield_context yield, std::chrono::steady_clock::duration timeout = kDEFAULT_TIMEOUT) = 0; - static constexpr std::chrono::seconds DEFAULT_TIMEOUT{5}; /**< Default timeout for connecting */ + static constexpr std::chrono::seconds kDEFAULT_TIMEOUT{5}; /**< Default timeout for connecting */ }; using WsConnectionPtr = std::unique_ptr; @@ -99,8 +99,8 @@ class WsConnectionBuilder { std::string host_; std::string port_; std::vector headers_; - std::chrono::steady_clock::duration connectionTimeout_{DEFAULT_TIMEOUT}; - std::chrono::steady_clock::duration wsHandshakeTimeout_{DEFAULT_TIMEOUT}; + std::chrono::steady_clock::duration connectionTimeout_{kDEFAULT_TIMEOUT}; + std::chrono::steady_clock::duration wsHandshakeTimeout_{kDEFAULT_TIMEOUT}; std::string target_{"/"}; public: @@ -184,7 +184,7 @@ public: std::expected connect(boost::asio::yield_context yield) const; - static constexpr std::chrono::seconds DEFAULT_TIMEOUT{5}; /**< Default timeout for connecting */ + static constexpr std::chrono::seconds kDEFAULT_TIMEOUT{5}; /**< Default timeout for connecting */ private: template diff --git a/src/util/requests/impl/SslContext.cpp b/src/util/requests/impl/SslContext.cpp index d982c100..5825ed20 100644 --- a/src/util/requests/impl/SslContext.cpp +++ b/src/util/requests/impl/SslContext.cpp @@ -50,7 +50,7 @@ namespace { // Taken from https://go.dev/src/crypto/x509/root_linux.go -constexpr std::array CERT_FILE_PATHS{ +constexpr std::array kCERT_FILE_PATHS{ "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu/Gentoo etc. "/etc/pki/tls/certs/ca-bundle.crt", // Fedora/RHEL 6 "/etc/ssl/ca-bundle.pem", // OpenSUSE @@ -65,7 +65,7 @@ constexpr std::array CERT_FILE_PATHS{ std::expected getRootCertificate() { - for (auto const& path : CERT_FILE_PATHS) { + for (auto const& path : kCERT_FILE_PATHS) { if (std::filesystem::exists(path)) { std::ifstream const fileStream{path, std::ios::in}; if (not fileStream.is_open()) { @@ -106,8 +106,8 @@ sslErrorToString(boost::beast::error_code const& error) boost::lexical_cast(ERR_GET_REASON(error.value())) ); - static constexpr size_t BUFFER_SIZE = 128; - char buf[BUFFER_SIZE]; + static constexpr size_t kBUFFER_SIZE = 128; + char buf[kBUFFER_SIZE]; ::ERR_error_string_n(error.value(), buf, sizeof(buf)); errorString += buf; diff --git a/src/util/requests/impl/StreamData.hpp b/src/util/requests/impl/StreamData.hpp index 571960e1..a976871c 100644 --- a/src/util/requests/impl/StreamData.hpp +++ b/src/util/requests/impl/StreamData.hpp @@ -39,7 +39,7 @@ namespace util::requests::impl { template struct PlainStreamData { - static constexpr bool sslEnabled = false; + static constexpr bool kSSL_ENABLED = false; explicit PlainStreamData(boost::asio::yield_context yield) : stream(boost::asio::get_associated_executor(yield)) { @@ -56,7 +56,7 @@ class SslStreamData { boost::asio::ssl::context sslContext_; public: - static constexpr bool sslEnabled = true; + static constexpr bool kSSL_ENABLED = true; static std::expected create(boost::asio::yield_context yield) diff --git a/src/util/requests/impl/WsConnectionImpl.hpp b/src/util/requests/impl/WsConnectionImpl.hpp index b588e5d0..581d3870 100644 --- a/src/util/requests/impl/WsConnectionImpl.hpp +++ b/src/util/requests/impl/WsConnectionImpl.hpp @@ -101,7 +101,7 @@ public: } std::optional - close(boost::asio::yield_context yield, std::chrono::steady_clock::duration const timeout = DEFAULT_TIMEOUT) + close(boost::asio::yield_context yield, std::chrono::steady_clock::duration const timeout = kDEFAULT_TIMEOUT) override { // Set the timeout for closing the connection diff --git a/src/web/AdminVerificationStrategy.cpp b/src/web/AdminVerificationStrategy.cpp index 84265eb9..f3b22af6 100644 --- a/src/web/AdminVerificationStrategy.cpp +++ b/src/web/AdminVerificationStrategy.cpp @@ -62,17 +62,17 @@ PasswordAdminVerificationStrategy::isAdmin(RequestHeader const& request, std::st return false; } auto userAuth = it->value(); - if (!userAuth.starts_with(passwordPrefix)) { + if (!userAuth.starts_with(kPASSWORD_PREFIX)) { // Invalid Authorization header return false; } - userAuth.remove_prefix(passwordPrefix.size()); + userAuth.remove_prefix(kPASSWORD_PREFIX.size()); return passwordSha256_ == util::toUpper(userAuth); } std::shared_ptr -make_AdminVerificationStrategy(std::optional password) +makeAdminVerificationStrategy(std::optional password) { if (password.has_value()) { return std::make_shared(std::move(*password)); @@ -81,7 +81,7 @@ make_AdminVerificationStrategy(std::optional password) } std::expected, std::string> -make_AdminVerificationStrategy(util::config::ClioConfigDefinition const& config) +makeAdminVerificationStrategy(util::config::ClioConfigDefinition const& config) { auto adminPassword = config.maybeValue("server.admin_password"); auto const localAdmin = config.maybeValue("server.local_admin"); @@ -95,7 +95,7 @@ make_AdminVerificationStrategy(util::config::ClioConfigDefinition const& config) }; } - return make_AdminVerificationStrategy(std::move(adminPassword)); + return makeAdminVerificationStrategy(std::move(adminPassword)); } } // namespace web diff --git a/src/web/AdminVerificationStrategy.hpp b/src/web/AdminVerificationStrategy.hpp index 6a6b1abc..a2920eea 100644 --- a/src/web/AdminVerificationStrategy.hpp +++ b/src/web/AdminVerificationStrategy.hpp @@ -79,7 +79,7 @@ public: /** * @brief The prefix for the password in the request header. */ - static constexpr std::string_view passwordPrefix = "Password "; + static constexpr std::string_view kPASSWORD_PREFIX = "Password "; /** * @brief Construct a new PasswordAdminVerificationStrategy object @@ -107,7 +107,7 @@ public: * Otherwise, it will be IPAdminVerificationStrategy. */ std::shared_ptr -make_AdminVerificationStrategy(std::optional password); +makeAdminVerificationStrategy(std::optional password); /** * @brief Factory function for creating an admin verification strategy from server config. @@ -116,6 +116,6 @@ make_AdminVerificationStrategy(std::optional password); * @return Admin verification strategy according to the config or an error message. */ std::expected, std::string> -make_AdminVerificationStrategy(util::config::ClioConfigDefinition const& serverConfig); +makeAdminVerificationStrategy(util::config::ClioConfigDefinition const& serverConfig); } // namespace web diff --git a/src/web/Context.hpp b/src/web/Context.hpp index 8ca16b7c..21978f17 100644 --- a/src/web/Context.hpp +++ b/src/web/Context.hpp @@ -81,8 +81,8 @@ struct Context : util::Taggable { , clientIp(std::move(clientIp)) , isAdmin(isAdmin) { - static util::Logger const perfLog{"Performance"}; - LOG(perfLog.debug()) << tag() << "new Context created"; + static util::Logger const log{"Performance"}; // NOLINT(readability-identifier-naming) + LOG(log.debug()) << tag() << "new Context created"; } Context(Context&&) = default; diff --git a/src/web/PlainWsSession.hpp b/src/web/PlainWsSession.hpp index 91e294da..6066765a 100644 --- a/src/web/PlainWsSession.hpp +++ b/src/web/PlainWsSession.hpp @@ -171,8 +171,8 @@ private: { parser_.emplace(); - constexpr static auto maxBodySize = 10000; - parser_->body_limit(maxBodySize); + static constexpr auto kMAX_BODY_SIZE = 10000; + parser_->body_limit(kMAX_BODY_SIZE); boost::beast::get_lowest_layer(http_).expires_after(std::chrono::seconds(30)); onUpgrade(); diff --git a/src/web/RPCServerHandler.hpp b/src/web/RPCServerHandler.hpp index 963643a3..632d9551 100644 --- a/src/web/RPCServerHandler.hpp +++ b/src/web/RPCServerHandler.hpp @@ -158,7 +158,7 @@ private: auto const context = [&] { if (connection->upgraded) { - return rpc::make_WsContext( + return rpc::makeWsContext( yield, request, connection->makeSubscriptionContext(tagFactory_), @@ -169,7 +169,7 @@ private: connection->isAdmin() ); } - return rpc::make_HttpContext( + return rpc::makeHttpContext( yield, request, tagFactory_.with(connection->tag()), @@ -253,10 +253,10 @@ private: } boost::json::array warnings = std::move(result.warnings); - warnings.emplace_back(rpc::makeWarning(rpc::warnRPC_CLIO)); + warnings.emplace_back(rpc::makeWarning(rpc::WarnRpcClio)); if (etl_->lastCloseAgeSeconds() >= 60) - warnings.emplace_back(rpc::makeWarning(rpc::warnRPC_OUTDATED)); + warnings.emplace_back(rpc::makeWarning(rpc::WarnRpcOutdated)); response["warnings"] = warnings; connection->send(boost::json::serialize(response)); diff --git a/src/web/Server.hpp b/src/web/Server.hpp index efdb3675..0b2fee4f 100644 --- a/src/web/Server.hpp +++ b/src/web/Server.hpp @@ -335,14 +335,14 @@ using HttpServer = Server; */ template static std::shared_ptr> -make_HttpServer( +makeHttpServer( util::config::ClioConfigDefinition const& config, boost::asio::io_context& ioc, dosguard::DOSGuardInterface& dosGuard, std::shared_ptr const& handler ) { - static util::Logger const log{"WebServer"}; + static util::Logger const log{"WebServer"}; // NOLINT(readability-identifier-naming) auto expectedSslContext = ng::impl::makeServerSslContext(config); if (not expectedSslContext) { @@ -354,7 +354,7 @@ make_HttpServer( auto const address = boost::asio::ip::make_address(serverConfig.get("ip")); auto const port = serverConfig.get("port"); - auto expectedAdminVerification = make_AdminVerificationStrategy(config); + auto expectedAdminVerification = makeAdminVerificationStrategy(config); if (not expectedAdminVerification.has_value()) { LOG(log.error()) << expectedAdminVerification.error(); throw std::logic_error{expectedAdminVerification.error()}; diff --git a/src/web/SslWsSession.hpp b/src/web/SslWsSession.hpp index ee39e34c..d5b317db 100644 --- a/src/web/SslWsSession.hpp +++ b/src/web/SslWsSession.hpp @@ -176,8 +176,8 @@ private: parser_.emplace(); // Apply a reasonable limit to the allowed size of the body in bytes to prevent abuse. - constexpr static auto maxBodySize = 10000; - parser_->body_limit(maxBodySize); + static constexpr auto kMAX_BODY_SIZE = 10000; + parser_->body_limit(kMAX_BODY_SIZE); boost::beast::get_lowest_layer(https_).expires_after(std::chrono::seconds(30)); onUpgrade(); diff --git a/src/web/dosguard/WhitelistHandler.cpp b/src/web/dosguard/WhitelistHandler.cpp index e8c808c7..661d58e6 100644 --- a/src/web/dosguard/WhitelistHandler.cpp +++ b/src/web/dosguard/WhitelistHandler.cpp @@ -94,15 +94,15 @@ Whitelist::isInV6Subnet(boost::asio::ip::address const& addr, boost::asio::ip::n bool Whitelist::isV4(std::string_view net) { - static std::regex const ipv4CidrRegex(R"(^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/\d{1,2}$)"); - return std::regex_match(std::string(net), ipv4CidrRegex); + static std::regex const kIPV4_CIDR_REGEX(R"(^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/\d{1,2}$)"); + return std::regex_match(std::string(net), kIPV4_CIDR_REGEX); } bool Whitelist::isV6(std::string_view net) { - static std::regex const ipv6CidrRegex(R"(^([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}/\d{1,3}$)"); - return std::regex_match(std::string(net), ipv6CidrRegex); + static std::regex const kIPV6_CIDR_REGEX(R"(^([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}/\d{1,3}$)"); + return std::regex_match(std::string(net), kIPV6_CIDR_REGEX); } bool diff --git a/src/web/impl/ErrorHandling.hpp b/src/web/impl/ErrorHandling.hpp index bc3fdf0b..5ffbbaa0 100644 --- a/src/web/impl/ErrorHandling.hpp +++ b/src/web/impl/ErrorHandling.hpp @@ -64,38 +64,38 @@ public: // Note: a collection of crutches to match rippled output follows if (auto const clioCode = std::get_if(&err.code)) { switch (*clioCode) { - case rpc::ClioError::rpcINVALID_API_VERSION: + case rpc::ClioError::RpcInvalidApiVersion: connection_->send( std::string{rpc::getErrorInfo(*clioCode).error}, boost::beast::http::status::bad_request ); break; - case rpc::ClioError::rpcCOMMAND_IS_MISSING: + case rpc::ClioError::RpcCommandIsMissing: connection_->send("Null method", boost::beast::http::status::bad_request); break; - case rpc::ClioError::rpcCOMMAND_IS_EMPTY: + case rpc::ClioError::RpcCommandIsEmpty: connection_->send("method is empty", boost::beast::http::status::bad_request); break; - case rpc::ClioError::rpcCOMMAND_NOT_STRING: + case rpc::ClioError::RpcCommandNotString: connection_->send("method is not string", boost::beast::http::status::bad_request); break; - case rpc::ClioError::rpcPARAMS_UNPARSEABLE: + case rpc::ClioError::RpcParamsUnparseable: connection_->send("params unparseable", boost::beast::http::status::bad_request); break; // others are not applicable but we want a compilation error next time we add one - case rpc::ClioError::rpcUNKNOWN_OPTION: - case rpc::ClioError::rpcMALFORMED_CURRENCY: - case rpc::ClioError::rpcMALFORMED_REQUEST: - case rpc::ClioError::rpcMALFORMED_OWNER: - case rpc::ClioError::rpcMALFORMED_ADDRESS: - case rpc::ClioError::rpcINVALID_HOT_WALLET: - case rpc::ClioError::rpcFIELD_NOT_FOUND_TRANSACTION: - case rpc::ClioError::rpcMALFORMED_ORACLE_DOCUMENT_ID: - case rpc::ClioError::rpcMALFORMED_AUTHORIZED_CREDENTIALS: - case rpc::ClioError::etlCONNECTION_ERROR: - case rpc::ClioError::etlREQUEST_ERROR: - case rpc::ClioError::etlREQUEST_TIMEOUT: - case rpc::ClioError::etlINVALID_RESPONSE: + case rpc::ClioError::RpcUnknownOption: + case rpc::ClioError::RpcMalformedCurrency: + case rpc::ClioError::RpcMalformedRequest: + case rpc::ClioError::RpcMalformedOwner: + case rpc::ClioError::RpcMalformedAddress: + case rpc::ClioError::RpcInvalidHotWallet: + case rpc::ClioError::RpcFieldNotFoundTransaction: + case rpc::ClioError::RpcMalformedOracleDocumentId: + case rpc::ClioError::RpcMalformedAuthorizedCredentials: + case rpc::ClioError::EtlConnectionError: + case rpc::ClioError::EtlRequestError: + case rpc::ClioError::EtlRequestTimeout: + case rpc::ClioError::EtlInvalidResponse: ASSERT( false, "Unknown rpc error code {}", static_cast(*clioCode) ); // this should never happen diff --git a/src/web/impl/HttpBase.hpp b/src/web/impl/HttpBase.hpp index 55a664bf..cfc257e8 100644 --- a/src/web/impl/HttpBase.hpp +++ b/src/web/impl/HttpBase.hpp @@ -62,7 +62,7 @@ namespace web::impl { -static auto constexpr HealthCheckHTML = R"html( +static auto constexpr kHEALTH_CHECK_HTML = R"html( Test page for Clio @@ -88,31 +88,31 @@ class HttpBase : public ConnectionBase { // TODO: this should be rewritten using http::message_generator instead struct SendLambda { - HttpBase& self_; + HttpBase& self; - explicit SendLambda(HttpBase& self) : self_(self) + explicit SendLambda(HttpBase& self) : self(self) { } - template + template void - operator()(http::message&& msg) const + operator()(http::message&& msg) const { - if (self_.dead()) + if (self.dead()) return; // The lifetime of the message has to extend for the duration of the async operation so we use a shared_ptr // to manage it. - auto sp = std::make_shared>(std::move(msg)); + auto sp = std::make_shared>(std::move(msg)); // Store a type-erased version of the shared pointer in the class to keep it alive. - self_.res_ = sp; + self.res_ = sp; // Write the response http::async_write( - self_.derived().stream(), + self.derived().stream(), *sp, - boost::beast::bind_front_handler(&HttpBase::onWrite, self_.derived().shared_from_this(), sp->need_eof()) + boost::beast::bind_front_handler(&HttpBase::onWrite, self.derived().shared_from_this(), sp->need_eof()) ); } }; @@ -207,7 +207,7 @@ public: } void - onRead(boost::beast::error_code ec, [[maybe_unused]] std::size_t bytes_transferred) + onRead(boost::beast::error_code ec, [[maybe_unused]] std::size_t bytesTransferred) { if (ec == http::error::end_of_stream) return derived().doClose(); @@ -216,7 +216,7 @@ public: return httpFail(ec, "read"); if (req_.method() == http::verb::get and req_.target() == "/health") - return sender_(httpResponse(http::status::ok, "text/html", HealthCheckHTML)); + return sender_(httpResponse(http::status::ok, "text/html", kHEALTH_CHECK_HTML)); // Update isAdmin property of the connection ConnectionBase::isAdmin_ = adminVerification_->isAdmin(req_, this->clientIp); @@ -277,9 +277,9 @@ public: auto jsonResponse = boost::json::parse(msg).as_object(); jsonResponse["warning"] = "load"; if (jsonResponse.contains("warnings") && jsonResponse["warnings"].is_array()) { - jsonResponse["warnings"].as_array().push_back(rpc::makeWarning(rpc::warnRPC_RATE_LIMIT)); + jsonResponse["warnings"].as_array().push_back(rpc::makeWarning(rpc::WarnRpcRateLimit)); } else { - jsonResponse["warnings"] = boost::json::array{rpc::makeWarning(rpc::warnRPC_RATE_LIMIT)}; + jsonResponse["warnings"] = boost::json::array{rpc::makeWarning(rpc::WarnRpcRateLimit)}; } // Reserialize when we need to include this warning @@ -296,9 +296,9 @@ public: } void - onWrite(bool close, boost::beast::error_code ec, std::size_t bytes_transferred) + onWrite(bool close, boost::beast::error_code ec, std::size_t bytesTransferred) { - boost::ignore_unused(bytes_transferred); + boost::ignore_unused(bytesTransferred); if (ec) return httpFail(ec, "write"); @@ -314,11 +314,11 @@ public: private: http::response - httpResponse(http::status status, std::string content_type, std::string message) const + httpResponse(http::status status, std::string contentType, std::string message) const { http::response res{status, req_.version()}; res.set(http::field::server, "clio-server-" + util::build::getClioVersionString()); - res.set(http::field::content_type, content_type); + res.set(http::field::content_type, contentType); res.keep_alive(req_.keep_alive()); res.body() = std::move(message); res.prepare_payload(); diff --git a/src/web/impl/WsBase.hpp b/src/web/impl/WsBase.hpp index 003ec029..9be6b334 100644 --- a/src/web/impl/WsBase.hpp +++ b/src/web/impl/WsBase.hpp @@ -216,9 +216,9 @@ public: jsonResponse["warning"] = "load"; if (jsonResponse.contains("warnings") && jsonResponse["warnings"].is_array()) { - jsonResponse["warnings"].as_array().push_back(rpc::makeWarning(rpc::warnRPC_RATE_LIMIT)); + jsonResponse["warnings"].as_array().push_back(rpc::makeWarning(rpc::WarnRpcRateLimit)); } else { - jsonResponse["warnings"] = boost::json::array{rpc::makeWarning(rpc::warnRPC_RATE_LIMIT)}; + jsonResponse["warnings"] = boost::json::array{rpc::makeWarning(rpc::WarnRpcRateLimit)}; } // Reserialize when we need to include this warning @@ -270,9 +270,9 @@ public: } void - onRead(boost::beast::error_code ec, std::size_t bytes_transferred) + onRead(boost::beast::error_code ec, std::size_t bytesTransferred) { - boost::ignore_unused(bytes_transferred); + boost::ignore_unused(bytesTransferred); if (ec) return wsFail(ec, "read"); diff --git a/src/web/ng/Connection.hpp b/src/web/ng/Connection.hpp index 3ff06cd2..9283e964 100644 --- a/src/web/ng/Connection.hpp +++ b/src/web/ng/Connection.hpp @@ -106,7 +106,7 @@ public: * @brief The default timeout for send, receive, and close operations. * @note This value should be higher than forwarding timeout to not disconnect clients if rippled is slow. */ - static constexpr std::chrono::steady_clock::duration DEFAULT_TIMEOUT = std::chrono::seconds{11}; + static constexpr std::chrono::steady_clock::duration kDEFAULT_TIMEOUT = std::chrono::seconds{11}; /** * @brief Construct a new Connection object diff --git a/src/web/ng/RPCServerHandler.hpp b/src/web/ng/RPCServerHandler.hpp index bc076b5a..5865748f 100644 --- a/src/web/ng/RPCServerHandler.hpp +++ b/src/web/ng/RPCServerHandler.hpp @@ -199,7 +199,7 @@ private: auto const context = [&] { if (connectionMetadata.wasUpgraded()) { ASSERT(subscriptionContext != nullptr, "Subscription context must exist for a WS connecton"); - return rpc::make_WsContext( + return rpc::makeWsContext( yield, request, std::move(subscriptionContext), @@ -210,7 +210,7 @@ private: connectionMetadata.isAdmin() ); } - return rpc::make_HttpContext( + return rpc::makeHttpContext( yield, request, tagFactory_.with(connectionMetadata.tag()), @@ -292,10 +292,10 @@ private: } boost::json::array warnings = std::move(result.warnings); - warnings.emplace_back(rpc::makeWarning(rpc::warnRPC_CLIO)); + warnings.emplace_back(rpc::makeWarning(rpc::WarnRpcClio)); if (etl_->lastCloseAgeSeconds() >= 60) - warnings.emplace_back(rpc::makeWarning(rpc::warnRPC_OUTDATED)); + warnings.emplace_back(rpc::makeWarning(rpc::WarnRpcOutdated)); response["warnings"] = warnings; return Response{boost::beast::http::status::ok, response, rawRequest}; diff --git a/src/web/ng/Response.cpp b/src/web/ng/Response.cpp index 6407f4e8..94f40278 100644 --- a/src/web/ng/Response.cpp +++ b/src/web/ng/Response.cpp @@ -109,29 +109,29 @@ makeData(http::status status, MessageType message, Connection const& connection) } // namespace Response::Response(boost::beast::http::status status, std::string message, Request const& request) - : data_{makeData(status, std::move(message), request)} + : data{makeData(status, std::move(message), request)} { } Response::Response(boost::beast::http::status status, boost::json::object const& message, Request const& request) - : data_{makeData(status, message, request)} + : data{makeData(status, message, request)} { } Response::Response(boost::beast::http::status status, boost::json::object const& message, Connection const& connection) - : data_{makeData(status, message, connection)} + : data{makeData(status, message, connection)} { } Response::Response(boost::beast::http::status status, std::string message, Connection const& connection) - : data_{makeData(status, std::move(message), connection)} + : data{makeData(status, std::move(message), connection)} { } Response::Response(boost::beast::http::response response, Request const& request) { ASSERT(request.isHttp(), "Request must be HTTP to construct response from HTTP response"); - data_ = prepareResponse(std::move(response), request.asHttpRequest()->get().keep_alive()); + data = prepareResponse(std::move(response), request.asHttpRequest()->get().keep_alive()); } std::string const& @@ -144,20 +144,20 @@ Response::message() const return message; // NOLINT(bugprone-return-const-ref-from-parameter) }, }, - data_ + data ); } void Response::setMessage(std::string newMessage) { - if (std::holds_alternative(data_)) { - std::get(data_) = std::move(newMessage); + if (std::holds_alternative(data)) { + std::get(data) = std::move(newMessage); return; } MessageData messageData{std::move(newMessage)}; - auto const& oldHttpResponse = std::get>(data_); - data_ = makeHttpData( + auto const& oldHttpResponse = std::get>(data); + data = makeHttpData( std::move(messageData), oldHttpResponse.result(), oldHttpResponse.version(), oldHttpResponse.keep_alive() ); } @@ -166,12 +166,12 @@ void Response::setMessage(boost::json::object const& newMessage) { MessageData messageData{newMessage}; - if (std::holds_alternative(data_)) { - std::get(data_) = std::move(messageData).body; + if (std::holds_alternative(data)) { + std::get(data) = std::move(messageData).body; return; } - auto const& oldHttpResponse = std::get>(data_); - data_ = makeHttpData( + auto const& oldHttpResponse = std::get>(data); + data = makeHttpData( std::move(messageData), oldHttpResponse.result(), oldHttpResponse.version(), oldHttpResponse.keep_alive() ); } @@ -179,16 +179,17 @@ Response::setMessage(boost::json::object const& newMessage) http::response Response::intoHttpResponse() && { - ASSERT(std::holds_alternative>(data_), "Response must contain HTTP data"); + ASSERT(std::holds_alternative>(data), "Response must contain HTTP data"); - return std::move(std::get>(data_)); + return std::move(std::get>(data)); } boost::asio::const_buffer Response::asWsResponse() const& { - ASSERT(std::holds_alternative(data_), "Response must contain WebSocket data"); - auto const& message = std::get(data_); + ASSERT(std::holds_alternative(data), "Response must contain WebSocket data"); + auto const& message = std::get(data); + return boost::asio::buffer(message.data(), message.size()); } diff --git a/src/web/ng/Response.hpp b/src/web/ng/Response.hpp index 3657021b..06324951 100644 --- a/src/web/ng/Response.hpp +++ b/src/web/ng/Response.hpp @@ -39,7 +39,7 @@ class Connection; */ class Response { public: - std::variant, std::string> data_; + std::variant, std::string> data; public: /** diff --git a/src/web/ng/Server.cpp b/src/web/ng/Server.cpp index a1ab1246..11f78c17 100644 --- a/src/web/ng/Server.cpp +++ b/src/web/ng/Server.cpp @@ -303,7 +303,7 @@ Server::handleConnection(boost::asio::ip::tcp::socket socket, boost::asio::yield } std::expected -make_Server( +makeServer( util::config::ClioConfigDefinition const& config, Server::OnConnectCheck onConnectCheck, Server::OnDisconnectHook onDisconnectHook, diff --git a/src/web/ng/Server.hpp b/src/web/ng/Server.hpp index cbf3ca79..220ebd29 100644 --- a/src/web/ng/Server.hpp +++ b/src/web/ng/Server.hpp @@ -169,7 +169,7 @@ private: * @return The Server or an error message. */ std::expected -make_Server( +makeServer( util::config::ClioConfigDefinition const& config, Server::OnConnectCheck onConnectCheck, Server::OnDisconnectHook onDisconnectHook, diff --git a/src/web/ng/impl/ErrorHandling.cpp b/src/web/ng/impl/ErrorHandling.cpp index 49416d9b..ec6ca4bf 100644 --- a/src/web/ng/impl/ErrorHandling.cpp +++ b/src/web/ng/impl/ErrorHandling.cpp @@ -83,33 +83,33 @@ ErrorHelper::makeError(rpc::Status const& err) const // Note: a collection of crutches to match rippled output follows if (auto const clioCode = std::get_if(&err.code)) { switch (*clioCode) { - case rpc::ClioError::rpcINVALID_API_VERSION: + case rpc::ClioError::RpcInvalidApiVersion: return Response{ http::status::bad_request, std::string{rpc::getErrorInfo(*clioCode).error}, rawRequest_ }; - case rpc::ClioError::rpcCOMMAND_IS_MISSING: + case rpc::ClioError::RpcCommandIsMissing: return Response{http::status::bad_request, "Null method", rawRequest_}; - case rpc::ClioError::rpcCOMMAND_IS_EMPTY: + case rpc::ClioError::RpcCommandIsEmpty: return Response{http::status::bad_request, "method is empty", rawRequest_}; - case rpc::ClioError::rpcCOMMAND_NOT_STRING: + case rpc::ClioError::RpcCommandNotString: return Response{http::status::bad_request, "method is not string", rawRequest_}; - case rpc::ClioError::rpcPARAMS_UNPARSEABLE: + case rpc::ClioError::RpcParamsUnparseable: return Response{http::status::bad_request, "params unparseable", rawRequest_}; // others are not applicable but we want a compilation error next time we add one - case rpc::ClioError::rpcUNKNOWN_OPTION: - case rpc::ClioError::rpcMALFORMED_CURRENCY: - case rpc::ClioError::rpcMALFORMED_REQUEST: - case rpc::ClioError::rpcMALFORMED_OWNER: - case rpc::ClioError::rpcMALFORMED_ADDRESS: - case rpc::ClioError::rpcINVALID_HOT_WALLET: - case rpc::ClioError::rpcFIELD_NOT_FOUND_TRANSACTION: - case rpc::ClioError::rpcMALFORMED_ORACLE_DOCUMENT_ID: - case rpc::ClioError::rpcMALFORMED_AUTHORIZED_CREDENTIALS: - case rpc::ClioError::etlCONNECTION_ERROR: - case rpc::ClioError::etlREQUEST_ERROR: - case rpc::ClioError::etlREQUEST_TIMEOUT: - case rpc::ClioError::etlINVALID_RESPONSE: + case rpc::ClioError::RpcUnknownOption: + case rpc::ClioError::RpcMalformedCurrency: + case rpc::ClioError::RpcMalformedRequest: + case rpc::ClioError::RpcMalformedOwner: + case rpc::ClioError::RpcMalformedAddress: + case rpc::ClioError::RpcInvalidHotWallet: + case rpc::ClioError::RpcFieldNotFoundTransaction: + case rpc::ClioError::RpcMalformedOracleDocumentId: + case rpc::ClioError::RpcMalformedAuthorizedCredentials: + case rpc::ClioError::EtlConnectionError: + case rpc::ClioError::EtlRequestError: + case rpc::ClioError::EtlRequestTimeout: + case rpc::ClioError::EtlInvalidResponse: ASSERT(false, "Unknown rpc error code {}", static_cast(*clioCode)); // this should never happen break; } diff --git a/src/web/ng/impl/HttpConnection.hpp b/src/web/ng/impl/HttpConnection.hpp index 13daea5b..6773ed20 100644 --- a/src/web/ng/impl/HttpConnection.hpp +++ b/src/web/ng/impl/HttpConnection.hpp @@ -76,7 +76,7 @@ template class HttpConnection : public UpgradableConnection { StreamType stream_; std::optional> request_; - std::chrono::steady_clock::duration timeout_{DEFAULT_TIMEOUT}; + std::chrono::steady_clock::duration timeout_{kDEFAULT_TIMEOUT}; public: HttpConnection( @@ -185,7 +185,7 @@ public: if constexpr (IsSslTcpStream) { ASSERT(sslContext.has_value(), "SSL context must be present to upgrade the connection"); - return make_SslWsConnection( + return makeSslWsConnection( boost::beast::get_lowest_layer(stream_).release_socket(), std::move(ip_), std::move(buffer_), @@ -195,7 +195,7 @@ public: yield ); } else { - return make_PlainWsConnection( + return makePlainWsConnection( stream_.release_socket(), std::move(ip_), std::move(buffer_), diff --git a/src/web/ng/impl/WsConnection.cpp b/src/web/ng/impl/WsConnection.cpp index 5ea6a976..89c47ba0 100644 --- a/src/web/ng/impl/WsConnection.cpp +++ b/src/web/ng/impl/WsConnection.cpp @@ -36,7 +36,7 @@ namespace web::ng::impl { std::expected, Error> -make_PlainWsConnection( +makePlainWsConnection( boost::asio::ip::tcp::socket socket, std::string ip, boost::beast::flat_buffer buffer, @@ -55,7 +55,7 @@ make_PlainWsConnection( } std::expected, Error> -make_SslWsConnection( +makeSslWsConnection( boost::asio::ip::tcp::socket socket, std::string ip, boost::beast::flat_buffer buffer, diff --git a/src/web/ng/impl/WsConnection.hpp b/src/web/ng/impl/WsConnection.hpp index 9d2b1711..b921c037 100644 --- a/src/web/ng/impl/WsConnection.hpp +++ b/src/web/ng/impl/WsConnection.hpp @@ -169,7 +169,7 @@ private: { // Disable the timeout. The websocket::stream uses its own timeout settings. boost::beast::get_lowest_layer(stream_).expires_never(); - setTimeout(DEFAULT_TIMEOUT); + setTimeout(kDEFAULT_TIMEOUT); stream_.set_option( boost::beast::websocket::stream_base::decorator([](boost::beast::websocket::response_type& res) { res.set(boost::beast::http::field::server, util::build::getClioFullVersionString()); @@ -182,7 +182,7 @@ using PlainWsConnection = WsConnection; using SslWsConnection = WsConnection>; std::expected, Error> -make_PlainWsConnection( +makePlainWsConnection( boost::asio::ip::tcp::socket socket, std::string ip, boost::beast::flat_buffer buffer, @@ -192,7 +192,7 @@ make_PlainWsConnection( ); std::expected, Error> -make_SslWsConnection( +makeSslWsConnection( boost::asio::ip::tcp::socket socket, std::string ip, boost::beast::flat_buffer buffer, diff --git a/tests/common/etl/FakeDiffProvider.hpp b/tests/common/etl/FakeDiffProvider.hpp index 3bfec904..c44ef13f 100644 --- a/tests/common/etl/FakeDiffProvider.hpp +++ b/tests/common/etl/FakeDiffProvider.hpp @@ -57,14 +57,14 @@ struct DiffProvider { nextKey(std::size_t keysSize) { // mock the result from doFetchSuccessorKey, be aware this function will be called from multiple threads - std::lock_guard const guard(keysMutex); - threadKeysMap[std::this_thread::get_id()]++; + std::lock_guard const guard(keysMutex_); + threadKeysMap_[std::this_thread::get_id()]++; - if (threadKeysMap[std::this_thread::get_id()] == keysSize - 1) { - return data::lastKey; + if (threadKeysMap_[std::this_thread::get_id()] == keysSize - 1) { + return data::kLAST_KEY; } - if (threadKeysMap[std::this_thread::get_id()] == keysSize) { - threadKeysMap[std::this_thread::get_id()] = 0; + if (threadKeysMap_[std::this_thread::get_id()] == keysSize) { + threadKeysMap_[std::this_thread::get_id()] = 0; return std::nullopt; } @@ -72,6 +72,6 @@ struct DiffProvider { } private: - std::mutex keysMutex; - std::map threadKeysMap; + std::mutex keysMutex_; + std::map threadKeysMap_; }; diff --git a/tests/common/feed/FeedTestUtil.hpp b/tests/common/feed/FeedTestUtil.hpp index 4de08b88..320c2d59 100644 --- a/tests/common/feed/FeedTestUtil.hpp +++ b/tests/common/feed/FeedTestUtil.hpp @@ -34,11 +34,14 @@ #include // Base class for feed tests, providing easy way to access the received feed +// The interface for matchers is from gtest so we don't want to change the casing +// NOLINTBEGIN(readability-identifier-naming) + template struct FeedBaseTest : util::prometheus::WithPrometheus, MockBackendTest, SyncExecutionCtxFixture { protected: web::SubscriptionContextPtr sessionPtr = std::make_shared(); - std::shared_ptr testFeedPtr = std::make_shared(ctx); + std::shared_ptr testFeedPtr = std::make_shared(ctx_); MockSession* mockSessionPtr = dynamic_cast(sessionPtr.get()); }; @@ -73,8 +76,10 @@ public: }; } // namespace impl +// NOLINTEND(readability-identifier-naming) + inline ::testing::Matcher> -SharedStringJsonEq(std::string const& expected) +sharedStringJsonEq(std::string const& expected) { return impl::SharedStringJsonEqMatcher(expected); } diff --git a/tests/common/migration/TestMigrators.hpp b/tests/common/migration/TestMigrators.hpp index 1144b8db..38131d50 100644 --- a/tests/common/migration/TestMigrators.hpp +++ b/tests/common/migration/TestMigrators.hpp @@ -24,8 +24,8 @@ struct SimpleTestMigrator { using Backend = MockMigrationBackend; - static constexpr auto name = "SimpleTestMigrator"; - static constexpr auto description = "The migrator for version 0 -> 1"; + static constexpr auto kNAME = "SimpleTestMigrator"; + static constexpr auto kDESCRIPTION = "The migrator for version 0 -> 1"; static void runMigration(std::shared_ptr, util::config::ObjectView const&) { @@ -39,8 +39,8 @@ struct SimpleTestMigrator { struct SimpleTestMigrator2 { using Backend = MockMigrationBackend; - static constexpr auto name = "SimpleTestMigrator2"; - static constexpr auto description = "The migrator for version 1 -> 2"; + static constexpr auto kNAME = "SimpleTestMigrator2"; + static constexpr auto kDESCRIPTION = "The migrator for version 1 -> 2"; static void runMigration(std::shared_ptr, util::config::ObjectView const&) { diff --git a/tests/common/rpc/FakesAndMocks.hpp b/tests/common/rpc/FakesAndMocks.hpp index 8518392a..d31f1fde 100644 --- a/tests/common/rpc/FakesAndMocks.hpp +++ b/tests/common/rpc/FakesAndMocks.hpp @@ -77,12 +77,12 @@ public: { using namespace rpc::validation; - static auto const rpcSpec = rpc::RpcSpec{ + static auto const kRPC_SPEC = rpc::RpcSpec{ {"hello", Required{}, Type{}, EqualTo{"world"}}, {"limit", Type{}, Between{0, 100}}, // optional field }; - return rpcSpec; + return kRPC_SPEC; } static Result @@ -116,12 +116,12 @@ public: { using namespace rpc::validation; - static auto const rpcSpec = rpc::RpcSpec{ + static auto const kRPC_SPEC = rpc::RpcSpec{ {"hello", Required{}, Type{}, EqualTo{"world"}}, {"limit", Type{}, Between{0u, 100u}}, // optional field }; - return rpcSpec; + return kRPC_SPEC; } static Result diff --git a/tests/common/util/AsioContextTestFixture.hpp b/tests/common/util/AsioContextTestFixture.hpp index 97958ab8..715a53dd 100644 --- a/tests/common/util/AsioContextTestFixture.hpp +++ b/tests/common/util/AsioContextTestFixture.hpp @@ -38,33 +38,33 @@ struct AsyncAsioContextTest : virtual public NoLoggerFixture { AsyncAsioContextTest() { - work.emplace(ctx); // make sure ctx does not stop on its own - runner.emplace([&] { ctx.run(); }); + work_.emplace(ctx_); // make sure ctx does not stop on its own + runner_.emplace([&] { ctx_.run(); }); } ~AsyncAsioContextTest() override { - work.reset(); - if (runner->joinable()) - runner->join(); - ctx.stop(); + work_.reset(); + if (runner_->joinable()) + runner_->join(); + ctx_.stop(); } void stop() { - work.reset(); - if (runner->joinable()) - runner->join(); - ctx.stop(); + work_.reset(); + if (runner_->joinable()) + runner_->join(); + ctx_.stop(); } protected: - boost::asio::io_context ctx; + boost::asio::io_context ctx_; private: - std::optional work; - std::optional runner; + std::optional work_; + std::optional runner_; }; /** @@ -85,7 +85,7 @@ struct SyncAsioContextTest : virtual public NoLoggerFixture { if (allowMockLeak) testing::Mock::AllowLeak(&call); - spawn(ctx, [&, _ = make_work_guard(ctx)](yield_context yield) { + spawn(ctx_, [&, _ = make_work_guard(ctx_)](yield_context yield) { f(yield); call.Call(); }); @@ -97,17 +97,17 @@ struct SyncAsioContextTest : virtual public NoLoggerFixture { void runContext() { - ctx.run(); - ctx.reset(); + ctx_.run(); + ctx_.reset(); } void runContextFor(std::chrono::milliseconds duration) { - ctx.run_for(duration); - ctx.reset(); + ctx_.run_for(duration); + ctx_.reset(); } protected: - boost::asio::io_context ctx; + boost::asio::io_context ctx_; }; diff --git a/tests/common/util/AssignRandomPort.cpp b/tests/common/util/AssignRandomPort.cpp index ae3a8149..aebd1711 100644 --- a/tests/common/util/AssignRandomPort.cpp +++ b/tests/common/util/AssignRandomPort.cpp @@ -31,8 +31,8 @@ namespace tests::util { uint32_t generateFreePort() { - boost::asio::io_context io_context; - tcp::acceptor acceptor(io_context); + boost::asio::io_context ioContext; + tcp::acceptor acceptor(ioContext); tcp::endpoint const endpoint(tcp::v4(), 0); acceptor.open(endpoint.protocol()); diff --git a/tests/common/util/BinaryTestObject.cpp b/tests/common/util/BinaryTestObject.cpp index c0941a2a..b25c0f59 100644 --- a/tests/common/util/BinaryTestObject.cpp +++ b/tests/common/util/BinaryTestObject.cpp @@ -37,9 +37,9 @@ namespace { -constinit auto const Seq = 30; +constinit auto const kSEQ = 30; -constinit auto const TxnHex = +constinit auto const kTXN_HEX = "1200192200000008240011CC9B201B001F71D6202A0000000168400000" "000000000C7321ED475D1452031E8F9641AF1631519A58F7B8681E172E" "4838AA0E59408ADA1727DD74406960041F34F10E0CBB39444B4D4E577F" @@ -48,7 +48,7 @@ constinit auto const TxnHex = "677265677765697362726F642E636F6D81146203F49C21D5D6E022CB16" "DE3538F248662FC73C"; -constinit auto const TxnMeta = +constinit auto const kTXN_META = "201C00000001F8E511005025001F71B3556ED9C9459001E4F4A9121F4E" "07AB6D14898A5BBEF13D85C25D743540DB59F3CF566203F49C21D5D6E0" "22CB16DE3538F248662FC73CFFFFFFFFFFFFFFFFFFFFFFFFE6FAEC5A00" @@ -147,7 +147,7 @@ constinit auto const TxnMeta = "066240000002540BE3E081146203F49C21D5D6E022CB16DE3538F24866" "2FC73CE1E1F1031000"; -constinit auto const RawHeader = +constinit auto const kRAW_HEADER = "03C3141A01633CD656F91B4EBB5EB89B791BD34DBC8A04BB6F407C5335BC54351E" "DD733898497E809E04074D14D271E4832D7888754F9230800761563A292FA2315A" "6DB6FE30CC5909B285080FCD6773CC883F9FE0EE4D439340AC592AADB973ED3CF5" @@ -159,27 +159,27 @@ constinit auto const RawHeader = namespace util { std::pair -CreateNftTxAndMetaBlobs() +createNftTxAndMetaBlobs() { - return {hexStringToBinaryString(TxnMeta), hexStringToBinaryString(TxnHex)}; + return {hexStringToBinaryString(kTXN_META), hexStringToBinaryString(kTXN_HEX)}; } std::pair -CreateNftTxAndMeta() +createNftTxAndMeta() { ripple::uint256 hash; EXPECT_TRUE(hash.parseHex("6C7F69A6D25A13AC4A2E9145999F45D4674F939900017A96885FDC2757E9284E")); - auto const [metaBlob, txnBlob] = CreateNftTxAndMetaBlobs(); + auto const [metaBlob, txnBlob] = createNftTxAndMetaBlobs(); ripple::SerialIter it{txnBlob.data(), txnBlob.size()}; - return {ripple::STTx{it}, ripple::TxMeta{hash, Seq, metaBlob}}; + return {ripple::STTx{it}, ripple::TxMeta{hash, kSEQ, metaBlob}}; } etlng::model::Transaction -CreateTransaction(ripple::TxType type) +createTransaction(ripple::TxType type) { - auto const [sttx, meta] = CreateNftTxAndMeta(); + auto const [sttx, meta] = createNftTxAndMeta(); return { .raw = "", .metaRaw = "", @@ -192,13 +192,13 @@ CreateTransaction(ripple::TxType type) } etlng::model::Object -CreateObject() +createObject() { // random object taken from initial ledger load - static constinit auto const objKey = "B00AA769C00726371689ED66A7CF57C2502F1BF4BDFF2ACADF67A2A7B5E8960D"; - static constinit auto const objPred = "B00AA769C00726371689ED66A7CF57C2502F1BF4BDFF2ACADF67A2A7B5E8960A"; - static constinit auto const objSucc = "B00AA769C00726371689ED66A7CF57C2502F1BF4BDFF2ACADF67A2A7B5E8960F"; - static constinit auto const objBlob = + static constinit auto const kOBJ_KEY = "B00AA769C00726371689ED66A7CF57C2502F1BF4BDFF2ACADF67A2A7B5E8960D"; + static constinit auto const kOBJ_PRED = "B00AA769C00726371689ED66A7CF57C2502F1BF4BDFF2ACADF67A2A7B5E8960A"; + static constinit auto const kOBJ_SUCC = "B00AA769C00726371689ED66A7CF57C2502F1BF4BDFF2ACADF67A2A7B5E8960F"; + static constinit auto const kOBJ_BLOB = "11007222002200002504270918370000000000000C4538000000000000000A554D94799200CC37EFAF45DA76704ED3CBEDBB4B4FCD" "56E9CBA5399EB40A7B3BEC629546DD24CDB4C0004C4A50590000000000000000000000000000000000000000000000000000000000" "000000000000016680000000000000004C4A505900000000000000000000000000000000368480B7780E3DCF5D062A7BB54129F42F" @@ -206,17 +206,17 @@ CreateObject() return { .key = {}, - .keyRaw = hexStringToBinaryString(objKey), + .keyRaw = hexStringToBinaryString(kOBJ_KEY), .data = {}, - .dataRaw = hexStringToBinaryString(objBlob), - .successor = hexStringToBinaryString(objSucc), - .predecessor = hexStringToBinaryString(objPred), + .dataRaw = hexStringToBinaryString(kOBJ_BLOB), + .successor = hexStringToBinaryString(kOBJ_SUCC), + .predecessor = hexStringToBinaryString(kOBJ_PRED), .type = {}, }; } etlng::model::BookSuccessor -CreateSuccessor() +createSuccessor() { return { .firstBook = "A000000000000000000000000000000000000000000000000000000000000000", @@ -225,9 +225,9 @@ CreateSuccessor() } etlng::impl::PBLedgerResponseType -CreateDataAndDiff() +createDataAndDiff() { - auto const rawHeaderBlob = hexStringToBinaryString(RawHeader); + auto const rawHeaderBlob = hexStringToBinaryString(kRAW_HEADER); auto res = etlng::impl::PBLedgerResponseType(); res.set_ledger_header(rawHeaderBlob); @@ -236,7 +236,7 @@ CreateDataAndDiff() { auto original = org::xrpl::rpc::v1::TransactionAndMetadata(); - auto const [metaRaw, txRaw] = CreateNftTxAndMetaBlobs(); + auto const [metaRaw, txRaw] = createNftTxAndMetaBlobs(); original.set_transaction_blob(txRaw); original.set_metadata_blob(metaRaw); for (int i = 0; i < 10; ++i) { @@ -245,7 +245,7 @@ CreateDataAndDiff() } } { - auto expected = CreateObject(); + auto expected = createObject(); auto original = org::xrpl::rpc::v1::RawLedgerObject(); original.set_data(expected.dataRaw); original.set_key(expected.keyRaw); @@ -255,7 +255,7 @@ CreateDataAndDiff() } } { - auto expected = CreateSuccessor(); + auto expected = createSuccessor(); auto original = org::xrpl::rpc::v1::BookSuccessor(); original.set_first_book(expected.firstBook); original.set_book_base(expected.bookBase); @@ -271,9 +271,9 @@ CreateDataAndDiff() } etlng::impl::PBLedgerResponseType -CreateData() +createData() { - auto const rawHeaderBlob = hexStringToBinaryString(RawHeader); + auto const rawHeaderBlob = hexStringToBinaryString(kRAW_HEADER); auto res = etlng::impl::PBLedgerResponseType(); res.set_ledger_header(rawHeaderBlob); @@ -282,7 +282,7 @@ CreateData() { auto original = org::xrpl::rpc::v1::TransactionAndMetadata(); - auto const [metaRaw, txRaw] = CreateNftTxAndMetaBlobs(); + auto const [metaRaw, txRaw] = createNftTxAndMetaBlobs(); original.set_transaction_blob(txRaw); original.set_metadata_blob(metaRaw); for (int i = 0; i < 10; ++i) { diff --git a/tests/common/util/BinaryTestObject.hpp b/tests/common/util/BinaryTestObject.hpp index 8bda7ce6..ad5fba05 100644 --- a/tests/common/util/BinaryTestObject.hpp +++ b/tests/common/util/BinaryTestObject.hpp @@ -33,24 +33,24 @@ namespace util { [[maybe_unused, nodiscard]] std::pair -CreateNftTxAndMetaBlobs(); +createNftTxAndMetaBlobs(); [[maybe_unused, nodiscard]] std::pair -CreateNftTxAndMeta(); +createNftTxAndMeta(); [[maybe_unused, nodiscard]] etlng::model::Transaction -CreateTransaction(ripple::TxType type); +createTransaction(ripple::TxType type); [[maybe_unused, nodiscard]] etlng::model::Object -CreateObject(); +createObject(); [[maybe_unused, nodiscard]] etlng::model::BookSuccessor -CreateSuccessor(); +createSuccessor(); [[maybe_unused, nodiscard]] etlng::impl::PBLedgerResponseType -CreateDataAndDiff(); +createDataAndDiff(); [[maybe_unused, nodiscard]] etlng::impl::PBLedgerResponseType -CreateData(); +createData(); } // namespace util diff --git a/tests/common/util/FakeFetchResponse.hpp b/tests/common/util/FakeFetchResponse.hpp index 100ec669..24eac04e 100644 --- a/tests/common/util/FakeFetchResponse.hpp +++ b/tests/common/util/FakeFetchResponse.hpp @@ -25,6 +25,9 @@ #include #include +// Note: we don't control gRPC models so let's keep the fakes compatible +// NOLINTBEGIN(readability-identifier-naming) + class FakeBook { std::string base_; std::string first_; @@ -122,13 +125,13 @@ public: }; class FakeLedgerObjects { - std::vector objects; + std::vector objects_; public: std::vector* mutable_objects() { - return &objects; + return &objects_; } }; @@ -219,3 +222,5 @@ struct FakeFetchResponse { return &bookSuccessors; } }; + +// NOLINTEND(readability-identifier-naming) diff --git a/tests/common/util/LoggerFixtures.hpp b/tests/common/util/LoggerFixtures.hpp index dcaa6d81..e19a2393 100644 --- a/tests/common/util/LoggerFixtures.hpp +++ b/tests/common/util/LoggerFixtures.hpp @@ -61,8 +61,8 @@ public: // Simulates the `util::Logger::init(config)` call LoggerFixture() { - static std::once_flag once_; - std::call_once(once_, [] { + static std::once_flag kONCE; + std::call_once(kONCE, [] { boost::log::add_common_attributes(); boost::log::register_simple_formatter_factory("Severity"); }); @@ -73,16 +73,16 @@ public: core->remove_all_sinks(); boost::log::add_console_log(stream_, keywords::format = "%Channel%:%Severity% %Message%"); - auto min_severity = expr::channel_severity_filter(util::log_channel, util::log_severity); + auto minSeverity = expr::channel_severity_filter(util::LogChannel, util::LogSeverity); - std::ranges::for_each(util::Logger::CHANNELS, [&min_severity](char const* channel) { - min_severity[channel] = util::Severity::TRC; + std::ranges::for_each(util::Logger::kCHANNELS, [&minSeverity](char const* channel) { + minSeverity[channel] = util::Severity::TRC; }); - min_severity["General"] = util::Severity::DBG; - min_severity["Trace"] = util::Severity::TRC; + minSeverity["General"] = util::Severity::DBG; + minSeverity["Trace"] = util::Severity::TRC; - core->set_filter(min_severity); + core->set_filter(minSeverity); core->set_logging_enabled(true); } diff --git a/tests/common/util/MockAmendmentCenter.hpp b/tests/common/util/MockAmendmentCenter.hpp index af02daba..c47b527f 100644 --- a/tests/common/util/MockAmendmentCenter.hpp +++ b/tests/common/util/MockAmendmentCenter.hpp @@ -55,12 +55,12 @@ struct MockAmendmentCenter : public data::AmendmentCenterInterface { MOCK_METHOD(data::Amendment const&, getAmendment, (data::AmendmentKey const&), (const, override)); - MOCK_METHOD(data::Amendment const&, IndexOperator, (data::AmendmentKey const&), (const)); + MOCK_METHOD(data::Amendment const&, indexOperator, (data::AmendmentKey const&), (const)); data::Amendment const& operator[](data::AmendmentKey const& key) const override { - return IndexOperator(key); + return indexOperator(key); } }; diff --git a/tests/common/util/MockBackendTestFixture.hpp b/tests/common/util/MockBackendTestFixture.hpp index 97f90f9d..25777459 100644 --- a/tests/common/util/MockBackendTestFixture.hpp +++ b/tests/common/util/MockBackendTestFixture.hpp @@ -31,35 +31,35 @@ template