From 244abf9b7ac54305d0d87f06f71153c46c118bfd Mon Sep 17 00:00:00 2001 From: Alex Kremer Date: Mon, 25 Nov 2024 21:16:13 +0000 Subject: [PATCH 01/22] Add clang-tidy case checks to src --- .clang-tidy | 12 ++ src/data/AmendmentCenter.hpp | 2 + src/data/cassandra/impl/Cluster.hpp | 18 +-- src/data/cassandra/impl/Collection.hpp | 2 +- src/data/cassandra/impl/Session.hpp | 2 +- src/data/cassandra/impl/Statement.hpp | 4 +- src/data/cassandra/impl/Tuple.hpp | 2 +- src/etl/ETLService.cpp | 4 +- src/etl/LoadBalancer.cpp | 6 +- src/etl/LoadBalancer.hpp | 8 +- src/etl/impl/ExtractionDataPipe.hpp | 4 +- src/etl/impl/ForwardingSource.cpp | 10 +- src/etl/impl/ForwardingSource.hpp | 4 +- src/etl/impl/SubscriptionSource.cpp | 2 +- src/etl/impl/SubscriptionSource.hpp | 13 +- src/etlng/Models.hpp | 2 +- src/etlng/impl/Registry.hpp | 2 +- src/rpc/Errors.cpp | 46 +++---- src/rpc/Errors.hpp | 60 +++++----- src/rpc/Factories.cpp | 16 +-- src/rpc/common/Checkers.hpp | 4 +- src/rpc/common/MetaProcessors.cpp | 2 +- src/rpc/common/MetaProcessors.hpp | 23 ++-- src/rpc/common/Validators.cpp | 62 +++++----- src/rpc/common/Validators.hpp | 28 ++--- src/rpc/common/impl/ForwardingProxy.hpp | 6 +- src/rpc/handlers/AMMInfo.cpp | 12 +- src/rpc/handlers/AccountChannels.hpp | 24 ++-- src/rpc/handlers/AccountCurrencies.hpp | 6 +- src/rpc/handlers/AccountInfo.hpp | 8 +- src/rpc/handlers/AccountLines.hpp | 25 ++-- src/rpc/handlers/AccountNFTs.hpp | 22 ++-- src/rpc/handlers/AccountObjects.hpp | 22 ++-- src/rpc/handlers/AccountOffers.hpp | 22 ++-- src/rpc/handlers/AccountTx.cpp | 2 +- src/rpc/handlers/AccountTx.hpp | 12 +- src/rpc/handlers/BookChanges.hpp | 4 +- src/rpc/handlers/BookOffers.hpp | 28 ++--- src/rpc/handlers/DepositAuthorized.hpp | 8 +- src/rpc/handlers/Feature.cpp | 4 +- src/rpc/handlers/GatewayBalances.cpp | 2 +- src/rpc/handlers/GatewayBalances.hpp | 6 +- src/rpc/handlers/GetAggregatePrice.hpp | 10 +- src/rpc/handlers/Ledger.hpp | 4 +- src/rpc/handlers/LedgerData.cpp | 4 +- src/rpc/handlers/LedgerData.hpp | 12 +- src/rpc/handlers/LedgerEntry.cpp | 10 +- src/rpc/handlers/LedgerEntry.hpp | 112 +++++++++--------- src/rpc/handlers/LedgerIndex.cpp | 2 +- src/rpc/handlers/LedgerIndex.hpp | 4 +- src/rpc/handlers/MPTHolders.cpp | 2 +- src/rpc/handlers/MPTHolders.hpp | 30 +++-- src/rpc/handlers/NFTHistory.cpp | 2 +- src/rpc/handlers/NFTHistory.hpp | 18 ++- src/rpc/handlers/NFTInfo.hpp | 6 +- src/rpc/handlers/NFTOffersCommon.hpp | 22 ++-- src/rpc/handlers/NFTsByIssuer.cpp | 2 +- src/rpc/handlers/NFTsByIssuer.hpp | 20 ++-- src/rpc/handlers/NoRippleCheck.hpp | 20 ++-- src/rpc/handlers/ServerInfo.hpp | 8 +- src/rpc/handlers/Subscribe.cpp | 8 +- src/rpc/handlers/TransactionEntry.hpp | 8 +- src/rpc/handlers/Tx.hpp | 2 +- src/rpc/handlers/Unsubscribe.cpp | 6 +- src/util/LedgerUtils.cpp | 4 +- src/util/LedgerUtils.hpp | 39 +++--- src/util/Random.cpp | 4 +- src/util/Random.hpp | 6 +- src/util/SignalsHandler.cpp | 20 ++-- src/util/SignalsHandler.hpp | 6 +- src/util/async/Operation.hpp | 17 +-- .../async/context/SyncExecutionContext.hpp | 2 +- src/util/async/context/impl/Utils.hpp | 2 +- src/util/async/impl/ErrorHandling.hpp | 2 +- src/util/config/Config.cpp | 4 +- src/util/config/Config.hpp | 2 +- src/util/log/Logger.cpp | 22 ++-- src/util/log/Logger.hpp | 26 ++-- src/util/newconfig/ConfigConstraints.hpp | 2 +- src/util/newconfig/ConfigDescription.hpp | 2 +- src/util/prometheus/MetricBase.cpp | 12 +- src/util/prometheus/MetricBase.hpp | 10 +- src/util/prometheus/MetricBuilder.cpp | 30 ++--- src/util/prometheus/MetricsFamily.cpp | 2 +- src/util/prometheus/Prometheus.cpp | 24 ++-- src/util/prometheus/Prometheus.hpp | 6 +- src/util/prometheus/impl/AnyCounterBase.hpp | 12 +- src/util/requests/RequestBuilder.hpp | 4 +- src/util/requests/WsConnection.hpp | 10 +- src/util/requests/impl/WsConnectionImpl.hpp | 3 +- src/web/RPCServerHandler.hpp | 4 +- src/web/dosguard/DOSGuard.cpp | 6 +- src/web/dosguard/DOSGuard.hpp | 6 +- src/web/impl/ErrorHandling.hpp | 36 +++--- src/web/impl/HttpBase.hpp | 16 +-- src/web/impl/WsBase.hpp | 4 +- src/web/ng/Connection.hpp | 8 +- src/web/ng/RPCServerHandler.hpp | 4 +- src/web/ng/Response.cpp | 19 +-- src/web/ng/Response.hpp | 2 +- src/web/ng/impl/ErrorHandling.cpp | 36 +++--- src/web/ng/impl/HttpConnection.hpp | 10 +- src/web/ng/impl/WsConnection.hpp | 10 +- 103 files changed, 650 insertions(+), 647 deletions(-) diff --git a/.clang-tidy b/.clang-tidy index 86d494a10..0b49617eb 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -123,6 +123,7 @@ Checks: '-*, readability-else-after-return, readability-implicit-bool-conversion, readability-inconsistent-declaration-parameter-name, + readability-identifier-naming, readability-make-member-function-const, readability-misleading-indentation, readability-non-const-parameter, @@ -140,6 +141,17 @@ 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.ClassMemberCase: camelBack + readability-identifier-naming.ClassConstantCase: camelBack + readability-identifier-naming.PrivateMemberSuffix: _ + readability-identifier-naming.PublicMemberSuffix: '' 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/src/data/AmendmentCenter.hpp b/src/data/AmendmentCenter.hpp index f6b8d8fd1..0413f009a 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/cassandra/impl/Cluster.hpp b/src/data/cassandra/impl/Cluster.hpp index bd82ceeb7..27fbc9eda 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 defaultConnectionTimeout = 10000; + static constexpr uint32_t defaultMaxWriteRequestsOutstanding = 10'000; + static constexpr uint32_t defaultMaxReadRequestsOutstanding = 100'000; + static constexpr std::size_t defaultBatchSize = 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{defaultConnectionTimeout}; /** @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 = defaultMaxWriteRequestsOutstanding; /** @brief The maximum number of outstanding read requests at any given moment */ - uint32_t maxReadRequestsOutstanding = DEFAULT_MAX_READ_REQUESTS_OUTSTANDING; + uint32_t maxReadRequestsOutstanding = defaultMaxReadRequestsOutstanding; /** @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 = defaultBatchSize; /** @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 b4a927510..16bb07f13 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); }; + constexpr static auto deleter = [](CassCollection* ptr) { cass_collection_free(ptr); }; static void throwErrorIfNeeded(CassError const rc, std::string_view const label) diff --git a/src/data/cassandra/impl/Session.hpp b/src/data/cassandra/impl/Session.hpp index af9ec8375..a1f81b245 100644 --- a/src/data/cassandra/impl/Session.hpp +++ b/src/data/cassandra/impl/Session.hpp @@ -26,7 +26,7 @@ namespace data::cassandra::impl { class Session : public ManagedObject { - static constexpr auto deleter = [](CassSession* ptr) { cass_session_free(ptr); }; + constexpr static auto deleter = [](CassSession* ptr) { cass_session_free(ptr); }; public: Session() : ManagedObject{cass_session_new(), deleter} diff --git a/src/data/cassandra/impl/Statement.hpp b/src/data/cassandra/impl/Statement.hpp index 8aa5ae253..f79f734c2 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); }; + constexpr static auto deleter = [](CassStatement* ptr) { cass_statement_free(ptr); }; public: /** @@ -150,7 +150,7 @@ class Statement : public ManagedObject { * 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); }; + constexpr static auto deleter = [](CassPrepared const* ptr) { cass_prepared_free(ptr); }; public: /* implicit */ PreparedStatement(CassPrepared const* ptr) : ManagedObject{ptr, deleter} diff --git a/src/data/cassandra/impl/Tuple.hpp b/src/data/cassandra/impl/Tuple.hpp index 72224d13d..2288c42f7 100644 --- a/src/data/cassandra/impl/Tuple.hpp +++ b/src/data/cassandra/impl/Tuple.hpp @@ -37,7 +37,7 @@ namespace data::cassandra::impl { class Tuple : public ManagedObject { - static constexpr auto deleter = [](CassTuple* ptr) { cass_tuple_free(ptr); }; + constexpr static auto deleter = [](CassTuple* ptr) { cass_tuple_free(ptr); }; public: /* implicit */ Tuple(CassTuple* ptr); diff --git a/src/etl/ETLService.cpp b/src/etl/ETLService.cpp index 3017e417f..63688598c 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; + constexpr static auto NanosecondsPerSecond = 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()) / NanosecondsPerSecond; state_.isWriting = false; diff --git a/src/etl/LoadBalancer.cpp b/src/etl/LoadBalancer.cpp index 4edda00aa..6e6e8c933 100644 --- a/src/etl/LoadBalancer.cpp +++ b/src/etl/LoadBalancer.cpp @@ -230,7 +230,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_) { @@ -244,10 +244,10 @@ LoadBalancer::forwardToRippled( auto numAttempts = 0u; - auto xUserValue = isAdmin ? ADMIN_FORWARDING_X_USER_VALUE : USER_FORWARDING_X_USER_VALUE; + auto xUserValue = isAdmin ? adminForwardingXUserValue : userForwardingXUserValue; 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 aa7e70c29..4689b3aba 100644 --- a/src/etl/LoadBalancer.hpp +++ b/src/etl/LoadBalancer.hpp @@ -65,7 +65,7 @@ class LoadBalancer { using OptionalGetLedgerResponseType = std::optional; private: - static constexpr std::uint32_t DEFAULT_DOWNLOAD_RANGES = 16; + static constexpr std::uint32_t defaultDownloadRanges = 16; util::Logger log_{"ETL"}; // Forwarding cache must be destroyed after sources because sources have a callback to invalidate cache @@ -75,7 +75,7 @@ class LoadBalancer { std::vector sources_; std::optional etlState_; std::uint32_t downloadRanges_ = - DEFAULT_DOWNLOAD_RANGES; /*< The number of markers to use when downloading initial ledger */ + defaultDownloadRanges; /*< 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 @@ class LoadBalancer { /** * @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 adminForwardingXUserValue = "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 userForwardingXUserValue = "clio_user"; /** * @brief Create an instance of the load balancer. diff --git a/src/etl/impl/ExtractionDataPipe.hpp b/src/etl/impl/ExtractionDataPipe.hpp index fcb1a5f7f..6a6b80ea6 100644 --- a/src/etl/impl/ExtractionDataPipe.hpp +++ b/src/etl/impl/ExtractionDataPipe.hpp @@ -39,7 +39,7 @@ class ExtractionDataPipe { using DataType = std::optional; using QueueType = ThreadSafeQueue; // TODO: probably should use boost::lockfree::queue instead? - constexpr static auto TOTAL_MAX_IN_QUEUE = 1000u; + constexpr static auto totalMaxInQueue = 1000u; private: util::Logger log_{"ETL"}; @@ -58,7 +58,7 @@ class ExtractionDataPipe { */ ExtractionDataPipe(uint32_t stride, uint32_t startSequence) : stride_{stride}, startSequence_{startSequence} { - auto const maxQueueSize = TOTAL_MAX_IN_QUEUE / stride; + auto const maxQueueSize = totalMaxInQueue / 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 ebda3a155..79f3afad9 100644 --- a/src/etl/impl/ForwardingSource.cpp +++ b/src/etl/impl/ForwardingSource.cpp @@ -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 efdb425fa..03946be1f 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 connectionTimeout{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 connectionTimeout = ForwardingSource::connectionTimeout ); /** diff --git a/src/etl/impl/SubscriptionSource.cpp b/src/etl/impl/SubscriptionSource.cpp index a6494c798..b133bc99d 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, retryMaxDelay, strand_)) , onConnect_(std::move(onConnect)) , onDisconnect_(std::move(onDisconnect)) , onLedgerClosed_(std::move(onLedgerClosed)) diff --git a/src/etl/impl/SubscriptionSource.hpp b/src/etl/impl/SubscriptionSource.hpp index 83b69d82f..bcfb67fd3 100644 --- a/src/etl/impl/SubscriptionSource.hpp +++ b/src/etl/impl/SubscriptionSource.hpp @@ -91,9 +91,9 @@ class SubscriptionSource { 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 wsTimeout{30}; + static constexpr std::chrono::seconds retryMaxDelay{30}; + static constexpr std::chrono::seconds retryDelay{1}; public: /** @@ -107,8 +107,7 @@ class SubscriptionSource { * @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 @@ class SubscriptionSource { 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::wsTimeout, + std::chrono::steady_clock::duration const retryDelay = SubscriptionSource::retryDelay ); /** diff --git a/src/etlng/Models.hpp b/src/etlng/Models.hpp index 1b7597e56..b44f88c31 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 specTag = true; /** * @brief Checks if the transaction type was requested. diff --git a/src/etlng/impl/Registry.hpp b/src/etlng/impl/Registry.hpp index 9e720b687..7f949da4f 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::specTag; template concept ContainsValidHook = HasLedgerDataHook or HasInitialDataHook or diff --git a/src/rpc/Errors.cpp b/src/rpc/Errors.cpp index b63d77b43..86d593b13 100644 --- a/src/rpc/Errors.cpp +++ b/src/rpc/Errors.cpp @@ -43,13 +43,13 @@ WarningInfo const& getWarningInfo(WarningCode code) { constexpr static WarningInfo infos[]{ - {warnUNKNOWN, "Unknown warning"}, - {warnRPC_CLIO, + {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."} }; @@ -75,28 +75,28 @@ ClioErrorInfo const& getErrorInfo(ClioError code) { constexpr static ClioErrorInfo infos[]{ - {ClioError::rpcMALFORMED_CURRENCY, "malformedCurrency", "Malformed currency."}, - {ClioError::rpcMALFORMED_REQUEST, "malformedRequest", "Malformed request."}, - {ClioError::rpcMALFORMED_OWNER, "malformedOwner", "Malformed owner."}, - {ClioError::rpcMALFORMED_ADDRESS, "malformedAddress", "Malformed address."}, - {ClioError::rpcINVALID_HOT_WALLET, "invalidHotWallet", "Invalid hot wallet."}, - {ClioError::rpcUNKNOWN_OPTION, "unknownOption", "Unknown option."}, - {ClioError::rpcFIELD_NOT_FOUND_TRANSACTION, "fieldNotFoundTransaction", "Missing field."}, - {ClioError::rpcMALFORMED_ORACLE_DOCUMENT_ID, "malformedDocumentID", "Malformed oracle_document_id."}, - {ClioError::rpcMALFORMED_AUTHORIZED_CREDENTIALS, + {ClioError::RpcMalformedCurrency, "malformedCurrency", "Malformed currency."}, + {ClioError::RpcMalformedRequest, "malformedRequest", "Malformed request."}, + {ClioError::RpcMalformedOwner, "malformedOwner", "Malformed owner."}, + {ClioError::RpcMalformedAddress, "malformedAddress", "Malformed address."}, + {ClioError::RpcInvalidHotWallet, "invalidHotWallet", "Invalid hot wallet."}, + {ClioError::RpcUnknownOption, "unknownOption", "Unknown option."}, + {ClioError::RpcFieldNotFoundTransaction, "fieldNotFoundTransaction", "Missing field."}, + {ClioError::RpcMalformedOracleDocumentId, "malformedDocumentID", "Malformed oracle_document_id."}, + {ClioError::RpcMalformedAuthorizedCredentials, "malformedAuthorizedCredentials", "Malformed authorized credentials."}, // special system errors - {ClioError::rpcINVALID_API_VERSION, JS(invalid_API_version), "Invalid API version."}, - {ClioError::rpcCOMMAND_IS_MISSING, JS(missingCommand), "Method is not specified or is not a string."}, - {ClioError::rpcCOMMAND_NOT_STRING, "commandNotString", "Method is not a string."}, - {ClioError::rpcCOMMAND_IS_EMPTY, "emptyCommand", "Method is an empty string."}, - {ClioError::rpcPARAMS_UNPARSEABLE, "paramsUnparseable", "Params must be an array holding exactly one object."}, + {ClioError::RpcInvalidApiVersion, JS(invalid_API_version), "Invalid API version."}, + {ClioError::RpcCommandIsMissing, JS(missingCommand), "Method is not specified or is not a string."}, + {ClioError::RpcCommandNotString, "commandNotString", "Method is not a string."}, + {ClioError::RpcCommandIsEmpty, "emptyCommand", "Method is an empty string."}, + {ClioError::RpcParamsUnparseable, "paramsUnparseable", "Params must be an array holding exactly one object."}, // etl related errors - {ClioError::etlCONNECTION_ERROR, "connectionError", "Couldn't connect to rippled."}, - {ClioError::etlREQUEST_ERROR, "requestError", "Error sending request to rippled."}, - {ClioError::etlREQUEST_TIMEOUT, "timeout", "Request to rippled timed out."}, - {ClioError::etlINVALID_RESPONSE, "invalidResponse", "Rippled returned an invalid response."} + {ClioError::EtlConnectionError, "connectionError", "Couldn't connect to rippled."}, + {ClioError::EtlRequestError, "requestError", "Error sending request to rippled."}, + {ClioError::EtlRequestTimeout, "timeout", "Request to rippled timed out."}, + {ClioError::EtlInvalidResponse, "invalidResponse", "Rippled returned an invalid response."} }; auto matchByCode = [code](auto const& info) { return info.code == code; }; diff --git a/src/rpc/Errors.hpp b/src/rpc/Errors.hpp index e177b6304..13ed00419 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 @@ class InvalidParamsError : public std::exception { * * @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 @@ class InvalidParamsError : public std::exception { 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 @@ class AccountNotFoundError : public std::exception { * * @param acct The account */ - explicit AccountNotFoundError(std::string acct) : account(std::move(acct)) + explicit AccountNotFoundError(std::string acct) : account_(std::move(acct)) { } @@ -259,7 +259,7 @@ class AccountNotFoundError : public std::exception { char const* what() const throw() override { - return account.c_str(); + return account_.c_str(); } }; diff --git a/src/rpc/Factories.cpp b/src/rpc/Factories.cpp index c90c0b48d..f5cd6e3e6 100644 --- a/src/rpc/Factories.cpp +++ b/src/rpc/Factories.cpp @@ -63,11 +63,11 @@ 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); @@ -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/common/Checkers.hpp b/src/rpc/common/Checkers.hpp index d25076c79..75297d524 100644 --- a/src/rpc/common/Checkers.hpp +++ b/src/rpc/common/Checkers.hpp @@ -78,7 +78,7 @@ class Deprecated<> final { 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 @@ class Deprecated final { 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 8cf28c799..661dc7577 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 a411f7858..3a488fbfa 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 @@ class Section final { * * @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 @@ class IfType final { template requires SomeRequirement or SomeModifier class WithCustomError final { - RequirementOrModifierType reqOrModifier; - Status error; + RequirementOrModifierType reqOrModifier_; + Status error_; public: /** @@ -175,7 +176,7 @@ class WithCustomError final { * @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 @@ class WithCustomError final { 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 @@ class WithCustomError final { 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 @@ class WithCustomError final { 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/Validators.cpp b/src/rpc/common/Validators.cpp index 063b0008a..db7e0bb0b 100644 --- a/src/rpc/common/Validators.cpp +++ b/src/rpc/common/Validators.cpp @@ -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,7 +196,7 @@ 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"}}; @@ -220,7 +220,7 @@ CustomValidator CustomValidators::SubscribeStreamValidator = 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 36e499ada..6f3b1976e 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/ForwardingProxy.hpp b/src/rpc/common/impl/ForwardingProxy.hpp index cb69d04db..5a18eeef6 100644 --- a/src/rpc/common/impl/ForwardingProxy.hpp +++ b/src/rpc/common/impl/ForwardingProxy.hpp @@ -145,9 +145,9 @@ class ForwardingProxy { 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(); + constexpr static auto ForceForward = "force_forward"; + return ctx.isAdmin and ctx.params.contains(ForceForward) and ctx.params.at(ForceForward).is_bool() and + ctx.params.at(ForceForward).as_bool(); } }; diff --git a/src/rpc/handlers/AMMInfo.cpp b/src/rpc/handlers/AMMInfo.cpp index 8fc1196a3..c79dfe156 100644 --- a/src/rpc/handlers/AMMInfo.cpp +++ b/src/rpc/handlers/AMMInfo.cpp @@ -231,8 +231,8 @@ AMMInfoHandler::spec([[maybe_unused]] uint32_t apiVersion) }}; static auto const rpcSpec = RpcSpec{ - {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(asset), meta::WithCustomError{ validation::Type{}, Status(RippledError::rpcISSUE_MALFORMED) @@ -240,7 +240,7 @@ AMMInfoHandler::spec([[maybe_unused]] uint32_t apiVersion) meta::IfType{stringIssueValidator}, meta::IfType{ meta::WithCustomError{ - validation::CustomValidators::CurrencyIssueValidator, Status(RippledError::rpcISSUE_MALFORMED) + validation::CustomValidators::currencyIssueValidator, Status(RippledError::rpcISSUE_MALFORMED) }, }}, {JS(asset2), @@ -250,13 +250,13 @@ AMMInfoHandler::spec([[maybe_unused]] uint32_t apiVersion) meta::IfType{stringIssueValidator}, 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; diff --git a/src/rpc/handlers/AccountChannels.hpp b/src/rpc/handlers/AccountChannels.hpp index 792efbdc0..8c104b87c 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; + constexpr static auto limitMin = 10; + constexpr static auto limitMax = 400; + constexpr static auto limitDefault = 200; /** * @brief A struct to hold data for one channel response @@ -97,7 +97,7 @@ class AccountChannelsHandler { std::optional destinationAccount; std::optional ledgerHash; std::optional ledgerIndex; - uint32_t limit = LIMIT_DEFAULT; + uint32_t limit = limitDefault; std::optional marker; }; @@ -123,15 +123,13 @@ class AccountChannelsHandler { 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}, - {JS(limit), - validation::Type{}, - validation::Min(1u), - modifiers::Clamp{LIMIT_MIN, LIMIT_MAX}}, - {JS(ledger_index), validation::CustomValidators::LedgerIndexValidator}, - {JS(marker), validation::CustomValidators::AccountMarkerValidator}, + {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{limitMin, limitMax} + }, + {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, + {JS(marker), validation::CustomValidators::accountMarkerValidator}, }; return rpcSpec; diff --git a/src/rpc/handlers/AccountCurrencies.hpp b/src/rpc/handlers/AccountCurrencies.hpp index 0db03fd3b..726415201 100644 --- a/src/rpc/handlers/AccountCurrencies.hpp +++ b/src/rpc/handlers/AccountCurrencies.hpp @@ -92,9 +92,9 @@ class AccountCurrenciesHandler { 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(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{}} }; diff --git a/src/rpc/handlers/AccountInfo.hpp b/src/rpc/handlers/AccountInfo.hpp index bf37a2024..bd2b92fba 100644 --- a/src/rpc/handlers/AccountInfo.hpp +++ b/src/rpc/handlers/AccountInfo.hpp @@ -137,11 +137,11 @@ class AccountInfoHandler { spec([[maybe_unused]] uint32_t apiVersion) { static auto const rpcSpecV1 = RpcSpec{ - {JS(account), validation::CustomValidators::AccountValidator}, - {JS(ident), validation::CustomValidators::AccountValidator}, + {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{}} }; diff --git a/src/rpc/handlers/AccountLines.hpp b/src/rpc/handlers/AccountLines.hpp index 3165d9761..7a627548c 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 auto constexpr limitMin = 10; + static auto constexpr limitMax = 400; + static auto constexpr limitDefault = 200; /** * @brief A struct to hold data for one line response @@ -100,7 +101,7 @@ class AccountLinesHandler { 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 = limitDefault; std::optional marker; }; @@ -128,20 +129,18 @@ class AccountLinesHandler { {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(limit), - validation::Type{}, - validation::Min(1u), - modifiers::Clamp{LIMIT_MIN, LIMIT_MAX}}, - {JS(ledger_index), validation::CustomValidators::LedgerIndexValidator}, - {JS(marker), validation::CustomValidators::AccountMarkerValidator}, + {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, + {JS(limit), validation::Type{}, validation::Min(1u), modifiers::Clamp{limitMin, limitMax} + }, + {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, + {JS(marker), validation::CustomValidators::accountMarkerValidator}, {JS(ledger), check::Deprecated{}}, {"peer_index", check::Deprecated{}}, }; diff --git a/src/rpc/handlers/AccountNFTs.hpp b/src/rpc/handlers/AccountNFTs.hpp index a5ebe6ad5..e42ebac80 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 auto constexpr limitMin = 20; + static auto constexpr limitMax = 400; + static auto constexpr limitDefault = 100; /** * @brief A struct to hold the output data of the command @@ -72,7 +72,7 @@ class AccountNFTsHandler { 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 = limitDefault; // Limit the number of token pages to retrieve. [20,400] std::optional marker; }; @@ -97,14 +97,12 @@ class AccountNFTsHandler { 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}, - {JS(limit), - validation::Type{}, - validation::Min(1u), - modifiers::Clamp{LIMIT_MIN, LIMIT_MAX}}, + {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{limitMin, limitMax} + }, }; return rpcSpec; diff --git a/src/rpc/handlers/AccountObjects.hpp b/src/rpc/handlers/AccountObjects.hpp index c52f94f97..b1a4afe95 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 auto constexpr limitMin = 10; + static auto constexpr limitMax = 400; + static auto constexpr limitDefault = 200; /** * @brief A struct to hold the output data of the command @@ -80,7 +80,7 @@ class AccountObjectsHandler { std::string account; std::optional ledgerHash; std::optional ledgerIndex; - uint32_t limit = LIMIT_DEFAULT; // [10,400] + uint32_t limit = limitDefault; // [10,400] std::optional marker; std::optional type; bool deletionBlockersOnly = false; @@ -109,17 +109,15 @@ class AccountObjectsHandler { { 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}, - {JS(limit), - validation::Type{}, - validation::Min(1u), - modifiers::Clamp(LIMIT_MIN, LIMIT_MAX)}, + {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(limitMin, limitMax) + }, {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{}}, }; diff --git a/src/rpc/handlers/AccountOffers.hpp b/src/rpc/handlers/AccountOffers.hpp index e86526492..4a767b512 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 auto constexpr limitMin = 10; + static auto constexpr limitMax = 400; + static auto constexpr limitDefault = 200; /** * @brief A struct to hold data for one offer response @@ -86,7 +86,7 @@ class AccountOffersHandler { std::string account; std::optional ledgerHash; std::optional ledgerIndex; - uint32_t limit = LIMIT_DEFAULT; + uint32_t limit = limitDefault; std::optional marker; }; @@ -112,14 +112,12 @@ class AccountOffersHandler { 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}, - {JS(limit), - validation::Type{}, - validation::Min(1u), - modifiers::Clamp{LIMIT_MIN, LIMIT_MAX}}, + {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{limitMin, limitMax} + }, {JS(ledger), check::Deprecated{}}, {JS(strict), check::Deprecated{}}, }; diff --git a/src/rpc/handlers/AccountTx.cpp b/src/rpc/handlers/AccountTx.cpp index f93508cd4..3fdec6560 100644 --- a/src/rpc/handlers/AccountTx.cpp +++ b/src/rpc/handlers/AccountTx.cpp @@ -117,7 +117,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(limitDefault); 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 2fdcda6a1..47fd9b3eb 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 auto constexpr limitMin = 1; + static auto constexpr limitDefault = 200; /** * @brief A struct to hold the marker data @@ -125,15 +125,15 @@ class AccountTxHandler { { 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}, + {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{limitMin, std::numeric_limits::max()}}, {JS(marker), meta::WithCustomError{ validation::Type{}, diff --git a/src/rpc/handlers/BookChanges.hpp b/src/rpc/handlers/BookChanges.hpp index d8db9580d..1b8ef4179 100644 --- a/src/rpc/handlers/BookChanges.hpp +++ b/src/rpc/handlers/BookChanges.hpp @@ -89,8 +89,8 @@ class BookChangesHandler { spec([[maybe_unused]] uint32_t apiVersion) { static auto const rpcSpec = RpcSpec{ - {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; diff --git a/src/rpc/handlers/BookOffers.hpp b/src/rpc/handlers/BookOffers.hpp index a5c186fdb..4a76cf3e6 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 auto constexpr limitMin = 1; + static auto constexpr limitMax = 100; + static auto constexpr limitDefault = 60; /** * @brief A struct to hold the output data of the command @@ -76,7 +76,7 @@ class BookOffersHandler { struct Input { std::optional ledgerHash; std::optional ledgerIndex; - uint32_t limit = LIMIT_DEFAULT; + uint32_t limit = limitDefault; std::optional taker; ripple::Currency paysCurrency; ripple::Currency getsCurrency; @@ -113,11 +113,11 @@ class BookOffersHandler { {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,25 +127,23 @@ class BookOffersHandler { {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}, + {JS(limit), validation::Type{}, validation::Min(1u), modifiers::Clamp{limitMin, limitMax} + }, + {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, + {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, }; return rpcSpec; diff --git a/src/rpc/handlers/DepositAuthorized.hpp b/src/rpc/handlers/DepositAuthorized.hpp index 5383962a3..4c5e07bec 100644 --- a/src/rpc/handlers/DepositAuthorized.hpp +++ b/src/rpc/handlers/DepositAuthorized.hpp @@ -100,10 +100,10 @@ class DepositAuthorizedHandler { 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}, + {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()} }; diff --git a/src/rpc/handlers/Feature.cpp b/src/rpc/handlers/Feature.cpp index 72a47910b..466ca8d53 100644 --- a/src/rpc/handlers/Feature.cpp +++ b/src/rpc/handlers/Feature.cpp @@ -116,8 +116,8 @@ FeatureHandler::spec([[maybe_unused]] uint32_t apiVersion) 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; } diff --git a/src/rpc/handlers/GatewayBalances.cpp b/src/rpc/handlers/GatewayBalances.cpp index 91155cece..29ef8577e 100644 --- a/src/rpc/handlers/GatewayBalances.cpp +++ b/src/rpc/handlers/GatewayBalances.cpp @@ -144,7 +144,7 @@ GatewayBalancesHandler::process(GatewayBalancesHandler::Input input, Context con auto inHotbalances = [&](auto const& hw) { return output.hotBalances.contains(hw); }; if (not std::all_of(input.hotWallets.begin(), input.hotWallets.end(), 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 adc9023ba..06192a8a4 100644 --- a/src/rpc/handlers/GatewayBalances.hpp +++ b/src/rpc/handlers/GatewayBalances.hpp @@ -139,9 +139,9 @@ class GatewayBalancesHandler { }}; 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(account), validation::Required{}, validation::CustomValidators::accountValidator}, + {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, + {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, {JS(hotwallet), hotWalletValidator} }; diff --git a/src/rpc/handlers/GetAggregatePrice.hpp b/src/rpc/handlers/GetAggregatePrice.hpp index 73a5d6f3f..7751b0ecb 100644 --- a/src/rpc/handlers/GetAggregatePrice.hpp +++ b/src/rpc/handlers/GetAggregatePrice.hpp @@ -153,7 +153,7 @@ class GetAggregatePriceHandler { 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}}; }; @@ -162,20 +162,20 @@ class GetAggregatePriceHandler { }}; static auto const rpcSpec = RpcSpec{ - {JS(ledger_hash), validation::CustomValidators::Uint256HexStringValidator}, - {JS(ledger_index), validation::CustomValidators::LedgerIndexValidator}, + {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}, // note: Unlike `rippled`, Clio only supports UInt as input, no string, no `null`, etc. diff --git a/src/rpc/handlers/Ledger.hpp b/src/rpc/handlers/Ledger.hpp index 13b833972..7cb9ff15d 100644 --- a/src/rpc/handlers/Ledger.hpp +++ b/src/rpc/handlers/Ledger.hpp @@ -110,8 +110,8 @@ class LedgerHandler { {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{}}, diff --git a/src/rpc/handlers/LedgerData.cpp b/src/rpc/handlers/LedgerData.cpp index 15287b40b..c325db09a 100644 --- a/src/rpc/handlers/LedgerData.cpp +++ b/src/rpc/handlers/LedgerData.cpp @@ -110,7 +110,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::limitBinary : LedgerDataHandler::limitJSON); auto page = sharedPtrBackend_->fetchLedgerPage(input.marker, lgrInfo.seq, limit, input.outOfOrder, ctx.yield); results = std::move(page.objects); @@ -186,7 +186,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::limitBinary : LedgerDataHandler::limitJSON; } if (jsonObject.contains(JS(limit))) diff --git a/src/rpc/handlers/LedgerData.hpp b/src/rpc/handlers/LedgerData.hpp index 1932f684f..702e7061e 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 uint32_t constexpr limitBinary = 2048; + static uint32_t constexpr limitJSON = 256; /** * @brief A struct to hold the output data of the command @@ -86,7 +86,7 @@ class LedgerDataHandler { 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::limitJSON; // max 256 for json ; 2048 for binary std::optional marker; std::optional diffMarker; bool outOfOrder = false; @@ -117,12 +117,12 @@ class LedgerDataHandler { static auto const rpcSpec = 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."} diff --git a/src/rpc/handlers/LedgerEntry.cpp b/src/rpc/handlers/LedgerEntry.cpp index d27a00458..162f88cc0 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}}; } diff --git a/src/rpc/handlers/LedgerEntry.hpp b/src/rpc/handlers/LedgerEntry.hpp index 87980b758..63ff020e2 100644 --- a/src/rpc/handlers/LedgerEntry.hpp +++ b/src/rpc/handlers/LedgerEntry.hpp @@ -151,43 +151,43 @@ class LedgerEntryHandler { ); 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) + validation::CustomValidators::uint256HexStringValidator, Status(ClioError::RpcMalformedRequest) }; static auto const malformedRequestIntValidator = - meta::WithCustomError{validation::Type{}, Status(ClioError::rpcMALFORMED_REQUEST)}; + meta::WithCustomError{validation::Type{}, Status(ClioError::RpcMalformedRequest)}; static auto const bridgeJsonValidator = 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{ {JS(binary), 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(index), malformedRequestHexStringValidator}, - {JS(account_root), validation::CustomValidators::AccountBase58Validator}, - {JS(did), validation::CustomValidators::AccountBase58Validator}, + {JS(account_root), validation::CustomValidators::accountBase58Validator}, + {JS(did), validation::CustomValidators::accountBase58Validator}, {JS(check), malformedRequestHexStringValidator}, {JS(deposit_preauth), validation::Type{}, @@ -197,18 +197,18 @@ class LedgerEntryHandler { {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{meta::Section{ - {JS(owner), validation::CustomValidators::AccountBase58Validator}, - {JS(dir_root), validation::CustomValidators::Uint256HexStringValidator}, + {JS(owner), validation::CustomValidators::accountBase58Validator}, + {JS(dir_root), validation::CustomValidators::uint256HexStringValidator}, {JS(sub_index), malformedRequestIntValidator} }}}, {JS(escrow), @@ -219,7 +219,7 @@ class LedgerEntryHandler { {JS(owner), validation::Required{}, meta::WithCustomError{ - validation::CustomValidators::AccountBase58Validator, Status(ClioError::rpcMALFORMED_OWNER) + validation::CustomValidators::accountBase58Validator, Status(ClioError::RpcMalformedOwner) }}, {JS(seq), validation::Required{}, malformedRequestIntValidator}, }, @@ -229,7 +229,7 @@ class LedgerEntryHandler { meta::IfType{malformedRequestHexStringValidator}, meta::IfType{ meta::Section{ - {JS(account), validation::Required{}, validation::CustomValidators::AccountBase58Validator}, + {JS(account), validation::Required{}, validation::CustomValidators::accountBase58Validator}, {JS(seq), validation::Required{}, malformedRequestIntValidator}, }, }}, @@ -238,14 +238,14 @@ class LedgerEntryHandler { validation::Type{}, meta::Section{ {JS(accounts), validation::Required{}, rippleStateAccountsCheck}, - {JS(currency), validation::Required{}, validation::CustomValidators::CurrencyValidator}, + {JS(currency), validation::Required{}, validation::CustomValidators::currencyValidator}, }}, {JS(ticket), validation::Type{}, meta::IfType{malformedRequestHexStringValidator}, meta::IfType{ meta::Section{ - {JS(account), validation::Required{}, validation::CustomValidators::AccountBase58Validator}, + {JS(account), validation::Required{}, validation::CustomValidators::accountBase58Validator}, {JS(ticket_seq), validation::Required{}, malformedRequestIntValidator}, }, }}, @@ -256,29 +256,29 @@ class LedgerEntryHandler { 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)}, + meta::WithCustomError{validation::Type{}, Status(ClioError::RpcMalformedRequest)}, bridgeJsonValidator}, {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, @@ -286,11 +286,11 @@ class LedgerEntryHandler { 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, @@ -298,78 +298,78 @@ class LedgerEntryHandler { 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{malformedRequestHexStringValidator, 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{malformedRequestHexStringValidator, 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{ 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) }, }, }, diff --git a/src/rpc/handlers/LedgerIndex.cpp b/src/rpc/handlers/LedgerIndex.cpp index 9796f0799..1fed5fe5d 100644 --- a/src/rpc/handlers/LedgerIndex.cpp +++ b/src/rpc/handlers/LedgerIndex.cpp @@ -58,7 +58,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, dateFormat); // systemTime must be valid after validation passed return systemTime->time_since_epoch().count(); }; diff --git a/src/rpc/handlers/LedgerIndex.hpp b/src/rpc/handlers/LedgerIndex.hpp index c67770287..a36fa8c2f 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"; + constexpr static auto dateFormat = "%Y-%m-%dT%TZ"; public: /** @@ -81,7 +81,7 @@ class LedgerIndexHandler { spec([[maybe_unused]] uint32_t apiVersion) { static auto const rpcSpec = RpcSpec{ - {JS(date), validation::Type{}, validation::TimeFormatValidator{DATE_FORMAT}}, + {JS(date), validation::Type{}, validation::TimeFormatValidator{dateFormat}}, }; return rpcSpec; } diff --git a/src/rpc/handlers/MPTHolders.cpp b/src/rpc/handlers/MPTHolders.cpp index e248297f1..6240117e1 100644 --- a/src/rpc/handlers/MPTHolders.cpp +++ b/src/rpc/handlers/MPTHolders.cpp @@ -56,7 +56,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::limitDefault); 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 1bc55a342..f25828956 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 auto constexpr limitMin = 1; + static auto constexpr limitMax = 100; + static auto constexpr limitDefault = 50; /** * @brief A struct to hold the output data of the command @@ -83,14 +93,12 @@ class MPTHoldersHandler { 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}, - {JS(limit), - validation::Type{}, - validation::Min(1u), - modifiers::Clamp{LIMIT_MIN, LIMIT_MAX}}, - {JS(marker), validation::CustomValidators::Uint160HexStringValidator}, + {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{limitMin, limitMax} + }, + {JS(marker), validation::CustomValidators::uint160HexStringValidator}, }; return rpcSpec; diff --git a/src/rpc/handlers/NFTHistory.cpp b/src/rpc/handlers/NFTHistory.cpp index f07e4925f..4ddac98cd 100644 --- a/src/rpc/handlers/NFTHistory.cpp +++ b/src/rpc/handlers/NFTHistory.cpp @@ -100,7 +100,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(limitDefault); 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 431159c62..14ce50f3f 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 auto constexpr limitMin = 1; + static auto constexpr limitMax = 100; + static auto constexpr limitDefault = 50; /** * @brief A struct to hold the marker data @@ -119,17 +119,15 @@ class NFTHistoryHandler { 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}, + {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{}}, {JS(forward), validation::Type{}}, - {JS(limit), - validation::Type{}, - validation::Min(1u), - modifiers::Clamp{LIMIT_MIN, LIMIT_MAX}}, + {JS(limit), validation::Type{}, validation::Min(1u), modifiers::Clamp{limitMin, limitMax} + }, {JS(marker), meta::WithCustomError{ validation::Type{}, Status{RippledError::rpcINVALID_PARAMS, "invalidMarker"} diff --git a/src/rpc/handlers/NFTInfo.hpp b/src/rpc/handlers/NFTInfo.hpp index e01c173db..ae5028301 100644 --- a/src/rpc/handlers/NFTInfo.hpp +++ b/src/rpc/handlers/NFTInfo.hpp @@ -95,9 +95,9 @@ class NFTInfoHandler { 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}, + {JS(nft_id), validation::Required{}, validation::CustomValidators::uint256HexStringValidator}, + {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, + {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, }; return rpcSpec; diff --git a/src/rpc/handlers/NFTOffersCommon.hpp b/src/rpc/handlers/NFTOffersCommon.hpp index be1e899e4..a5ae5cf82 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 auto constexpr limitMin = 50; + static auto constexpr limitMax = 500; + static auto constexpr limitDefault = 250; /** * @brief A struct to hold the output data of the command @@ -73,7 +73,7 @@ class NFTOffersHandlerBase { std::string nftID; std::optional ledgerHash; std::optional ledgerIndex; - uint32_t limit = LIMIT_DEFAULT; + uint32_t limit = limitDefault; std::optional marker; }; @@ -99,14 +99,12 @@ class NFTOffersHandlerBase { 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}, - {JS(limit), - validation::Type{}, - validation::Min(1u), - modifiers::Clamp{LIMIT_MIN, LIMIT_MAX}}, - {JS(marker), validation::CustomValidators::Uint256HexStringValidator}, + {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{limitMin, limitMax} + }, + {JS(marker), validation::CustomValidators::uint256HexStringValidator}, }; return rpcSpec; diff --git a/src/rpc/handlers/NFTsByIssuer.cpp b/src/rpc/handlers/NFTsByIssuer.cpp index 9f808f1a9..36de72656 100644 --- a/src/rpc/handlers/NFTsByIssuer.cpp +++ b/src/rpc/handlers/NFTsByIssuer.cpp @@ -56,7 +56,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::limitDefault); auto const issuer = accountFromStringStrict(input.issuer); auto const accountLedgerObject = diff --git a/src/rpc/handlers/NFTsByIssuer.hpp b/src/rpc/handlers/NFTsByIssuer.hpp index 60b32e3a8..b591201ef 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 auto constexpr limitMin = 1; + static auto constexpr limitMax = 100; + static auto constexpr limitDefault = 50; /** * @brief A struct to hold the output data of the command @@ -95,15 +95,13 @@ class NFTsByIssuerHandler { spec([[maybe_unused]] uint32_t apiVersion) { static auto const rpcSpec = RpcSpec{ - {JS(issuer), validation::Required{}, validation::CustomValidators::AccountValidator}, + {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(limit), - validation::Type{}, - validation::Min(1u), - modifiers::Clamp{LIMIT_MIN, LIMIT_MAX}}, - {JS(marker), validation::CustomValidators::Uint256HexStringValidator}, + {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, + {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, + {JS(limit), validation::Type{}, validation::Min(1u), modifiers::Clamp{limitMin, limitMax} + }, + {JS(marker), validation::CustomValidators::uint256HexStringValidator}, }; return rpcSpec; diff --git a/src/rpc/handlers/NoRippleCheck.hpp b/src/rpc/handlers/NoRippleCheck.hpp index 608a85588..610a1dee9 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 auto constexpr limitMin = 1; + static auto constexpr limitMax = 500; + static auto constexpr limitDefault = 300; /** * @brief A struct to hold the output data of the command @@ -79,7 +79,7 @@ class NoRippleCheckHandler { bool roleGateway = false; std::optional ledgerHash; std::optional ledgerIndex; - uint32_t limit = LIMIT_DEFAULT; + uint32_t limit = limitDefault; JsonBool transactions{false}; }; @@ -105,18 +105,16 @@ class NoRippleCheckHandler { spec([[maybe_unused]] uint32_t apiVersion) { static auto const rpcSpecV1 = RpcSpec{ - {JS(account), validation::Required{}, validation::CustomValidators::AccountValidator}, + {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(limit), - validation::Type(), - validation::Min(1u), - modifiers::Clamp{LIMIT_MIN, LIMIT_MAX}} + {JS(ledger_hash), validation::CustomValidators::uint256HexStringValidator}, + {JS(ledger_index), validation::CustomValidators::ledgerIndexValidator}, + {JS(limit), validation::Type(), validation::Min(1u), modifiers::Clamp{limitMin, limitMax} + } }; static auto const rpcSpec = RpcSpec{ diff --git a/src/rpc/handlers/ServerInfo.hpp b/src/rpc/handlers/ServerInfo.hpp index efbc26a66..7d3269961 100644 --- a/src/rpc/handlers/ServerInfo.hpp +++ b/src/rpc/handlers/ServerInfo.hpp @@ -67,7 +67,7 @@ namespace rpc { */ template class BaseServerInfoHandler { - static constexpr auto BACKEND_COUNTERS_KEY = "backend_counters"; + constexpr static auto backendCountersKey = "backend_counters"; std::shared_ptr backend_; std::shared_ptr subscriptions_; @@ -301,7 +301,7 @@ class BaseServerInfoHandler { 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()[backendCountersKey] = *info.adminSection->backendCounters; } } } @@ -337,8 +337,8 @@ class BaseServerInfoHandler { { 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(backendCountersKey) && jsonObject.at(backendCountersKey).is_bool()) + input.backendCounters = jv.at(backendCountersKey).as_bool(); return input; } }; diff --git a/src/rpc/handlers/Subscribe.cpp b/src/rpc/handlers/Subscribe.cpp index 367168eeb..9a8ae5ac3 100644 --- a/src/rpc/handlers/Subscribe.cpp +++ b/src/rpc/handlers/Subscribe.cpp @@ -80,7 +80,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,9 +97,9 @@ SubscribeHandler::spec([[maybe_unused]] uint32_t apiVersion) }}; static auto const rpcSpec = RpcSpec{ - {JS(streams), validation::CustomValidators::SubscribeStreamValidator}, - {JS(accounts), validation::CustomValidators::SubscribeAccountsValidator}, - {JS(accounts_proposed), validation::CustomValidators::SubscribeAccountsValidator}, + {JS(streams), validation::CustomValidators::subscribeStreamValidator}, + {JS(accounts), validation::CustomValidators::subscribeAccountsValidator}, + {JS(accounts_proposed), validation::CustomValidators::subscribeAccountsValidator}, {JS(books), booksValidator}, {"user", check::Deprecated{}}, {JS(password), check::Deprecated{}}, diff --git a/src/rpc/handlers/TransactionEntry.hpp b/src/rpc/handlers/TransactionEntry.hpp index 5fe627398..e9c930a0b 100644 --- a/src/rpc/handlers/TransactionEntry.hpp +++ b/src/rpc/handlers/TransactionEntry.hpp @@ -94,10 +94,10 @@ class TransactionEntryHandler { { static auto const rpcSpec = 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; diff --git a/src/rpc/handlers/Tx.hpp b/src/rpc/handlers/Tx.hpp index c453e7b8e..57734f8d2 100644 --- a/src/rpc/handlers/Tx.hpp +++ b/src/rpc/handlers/Tx.hpp @@ -117,7 +117,7 @@ class BaseTxHandler { spec(uint32_t apiVersion) { static RpcSpec const rpcSpecForV1 = { - {JS(transaction), validation::CustomValidators::Uint256HexStringValidator}, + {JS(transaction), validation::CustomValidators::uint256HexStringValidator}, {JS(min_ledger), validation::Type{}}, {JS(max_ledger), validation::Type{}}, {JS(ctid), validation::Type{}}, diff --git a/src/rpc/handlers/Unsubscribe.cpp b/src/rpc/handlers/Unsubscribe.cpp index 177b4d2e6..88fe599b4 100644 --- a/src/rpc/handlers/Unsubscribe.cpp +++ b/src/rpc/handlers/Unsubscribe.cpp @@ -78,9 +78,9 @@ UnsubscribeHandler::spec([[maybe_unused]] uint32_t apiVersion) }}; static auto const rpcSpec = RpcSpec{ - {JS(streams), validation::CustomValidators::SubscribeStreamValidator}, - {JS(accounts), validation::CustomValidators::SubscribeAccountsValidator}, - {JS(accounts_proposed), validation::CustomValidators::SubscribeAccountsValidator}, + {JS(streams), validation::CustomValidators::subscribeStreamValidator}, + {JS(accounts), validation::CustomValidators::subscribeAccountsValidator}, + {JS(accounts_proposed), validation::CustomValidators::subscribeAccountsValidator}, {JS(books), booksValidator}, {JS(url), check::Deprecated{}}, {JS(rt_accounts), check::Deprecated{}}, diff --git a/src/util/LedgerUtils.cpp b/src/util/LedgerUtils.cpp index e309964b5..c8468e69c 100644 --- a/src/util/LedgerUtils.cpp +++ b/src/util/LedgerUtils.cpp @@ -32,8 +32,8 @@ LedgerTypes::GetLedgerEntryTypeFromStr(std::string const& entryName) { static std::unordered_map typeMap = []() { std::unordered_map map; - std::for_each(std::begin(LEDGER_TYPES), std::end(LEDGER_TYPES), [&map](auto const& item) { - map[item.name] = item.type; + std::for_each(std::begin(ledgerTypes), std::end(ledgerTypes), [&map](auto const& item) { + map[item.name_] = item.type_; }); return map; }(); diff --git a/src/util/LedgerUtils.hpp b/src/util/LedgerUtils.hpp index 1a4b3ff04..8df2ecc3e 100644 --- a/src/util/LedgerUtils.hpp +++ b/src/util/LedgerUtils.hpp @@ -47,12 +47,13 @@ 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) { } @@ -86,7 +87,7 @@ class LedgerTypes { using LedgerTypeAttribute = impl::LedgerTypeAttribute; using LedgerTypeAttributeList = LedgerTypeAttribute[]; - static constexpr LedgerTypeAttributeList const LEDGER_TYPES{ + static constexpr LedgerTypeAttributeList const ledgerTypes{ LedgerTypeAttribute::AccountOwnedLedgerType(JS(account), ripple::ltACCOUNT_ROOT), LedgerTypeAttribute::ChainLedgerType(JS(amendments), ripple::ltAMENDMENTS), LedgerTypeAttribute::DeletionBlockerLedgerType(JS(check), ripple::ltCHECK), @@ -123,12 +124,12 @@ class LedgerTypes { * @brief Returns a list of all ledger entry type as string. * @return A list of all ledger entry type as string. */ - static constexpr auto + constexpr static auto GetLedgerEntryTypeStrList() { - std::array res{}; - std::transform(std::begin(LEDGER_TYPES), std::end(LEDGER_TYPES), std::begin(res), [](auto const& item) { - return item.name; + std::array res{}; + std::transform(std::begin(ledgerTypes), std::end(ledgerTypes), std::begin(res), [](auto const& item) { + return item.name_; }); return res; } @@ -138,19 +139,19 @@ class LedgerTypes { * * @return A list of all account owned ledger entry type as string. */ - static constexpr auto + constexpr static auto GetAccountOwnedLedgerTypeStrList() { auto constexpr filter = [](auto const& item) { - return item.category != LedgerTypeAttribute::LedgerCategory::Chain; + return item.category_ != LedgerTypeAttribute::LedgerCategory::Chain; }; - auto constexpr accountOwnedCount = std::count_if(std::begin(LEDGER_TYPES), std::end(LEDGER_TYPES), filter); + auto constexpr accountOwnedCount = std::count_if(std::begin(ledgerTypes), std::end(ledgerTypes), filter); std::array res{}; auto it = std::begin(res); - std::for_each(std::begin(LEDGER_TYPES), std::end(LEDGER_TYPES), [&](auto const& item) { + std::for_each(std::begin(ledgerTypes), std::end(ledgerTypes), [&](auto const& item) { if (filter(item)) { - *it = item.name; + *it = item.name_; ++it; } }); @@ -162,19 +163,19 @@ class LedgerTypes { * * @return A list of all account deletion blocker's type as string. */ - static constexpr auto + constexpr static auto GetDeletionBlockerLedgerTypes() { auto constexpr filter = [](auto const& item) { - return item.category == LedgerTypeAttribute::LedgerCategory::DeletionBlocker; + return item.category_ == LedgerTypeAttribute::LedgerCategory::DeletionBlocker; }; - auto constexpr deletionBlockersCount = std::count_if(std::begin(LEDGER_TYPES), std::end(LEDGER_TYPES), filter); + auto constexpr deletionBlockersCount = std::count_if(std::begin(ledgerTypes), std::end(ledgerTypes), filter); std::array res{}; auto it = std::begin(res); - std::for_each(std::begin(LEDGER_TYPES), std::end(LEDGER_TYPES), [&](auto const& item) { + std::for_each(std::begin(ledgerTypes), std::end(ledgerTypes), [&](auto const& item) { if (filter(item)) { - *it = item.type; + *it = item.type_; ++it; } }); diff --git a/src/util/Random.cpp b/src/util/Random.cpp index cba88c424..73feaf925 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 0a31833b4..3ce00d51f 100644 --- a/src/util/Random.hpp +++ b/src/util/Random.hpp @@ -45,10 +45,10 @@ class Random { 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 @@ class Random { 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 c4f212f5d..6ffcf4a76 100644 --- a/src/util/SignalsHandler.cpp +++ b/src/util/SignalsHandler.cpp @@ -35,38 +35,38 @@ namespace util { namespace impl { class SignalsHandlerStatic { - static SignalsHandler* handler_; + static SignalsHandler* handler; public: static void registerHandler(SignalsHandler& handler) { - ASSERT(handler_ == nullptr, "There could be only one instance of SignalsHandler"); - handler_ = &handler; + ASSERT(SignalsHandlerStatic::handler == nullptr, "There could be only one instance of SignalsHandler"); + SignalsHandlerStatic::handler = &handler; } static void resetHandler() { - handler_ = nullptr; + handler = nullptr; } static void handleSignal(int signal) { - ASSERT(handler_ != nullptr, "SignalsHandler is not initialized"); - handler_->stopHandler_(signal); + ASSERT(handler != nullptr, "SignalsHandler is not initialized"); + handler->stopHandler_(signal); } static void handleSecondSignal(int signal) { - ASSERT(handler_ != nullptr, "SignalsHandler is not initialized"); - handler_->secondSignalHandler_(signal); + ASSERT(handler != nullptr, "SignalsHandler is not initialized"); + handler->secondSignalHandler_(signal); } }; -SignalsHandler* SignalsHandlerStatic::handler_ = nullptr; +SignalsHandler* SignalsHandlerStatic::handler = nullptr; } // namespace impl @@ -122,7 +122,7 @@ SignalsHandler::cancelTimer() void SignalsHandler::setHandler(void (*handler)(int)) { - for (int const signal : HANDLED_SIGNALS) { + for (int const signal : handledSignals) { std::signal(signal, handler == nullptr ? SIG_DFL : handler); } } diff --git a/src/util/SignalsHandler.hpp b/src/util/SignalsHandler.hpp index 49f5b4f2b..9359cafb0 100644 --- a/src/util/SignalsHandler.hpp +++ b/src/util/SignalsHandler.hpp @@ -70,7 +70,7 @@ class SignalsHandler { * @param config The configuration. * @param forceExitHandler The handler for forced exit. */ - SignalsHandler(Config const& config, std::function forceExitHandler = defaultForceExitHandler_); + SignalsHandler(Config const& config, std::function forceExitHandler = defaultForceExitHandler); SignalsHandler(SignalsHandler const&) = delete; SignalsHandler(SignalsHandler&&) = delete; @@ -98,7 +98,7 @@ class SignalsHandler { stopSignal_.connect(static_cast(priority), std::forward(callback)); } - static constexpr auto HANDLED_SIGNALS = {SIGINT, SIGTERM}; + constexpr static auto handledSignals = {SIGINT, SIGTERM}; private: /** @@ -115,7 +115,7 @@ class SignalsHandler { static void setHandler(void (*handler)(int) = nullptr); - static auto constexpr defaultForceExitHandler_ = []() { std::exit(EXIT_FAILURE); }; + static auto constexpr defaultForceExitHandler = []() { std::exit(EXIT_FAILURE); }; }; } // namespace util diff --git a/src/util/async/Operation.hpp b/src/util/async/Operation.hpp index ae8b8a657..e7136b7f4 100644 --- a/src/util/async/Operation.hpp +++ b/src/util/async/Operation.hpp @@ -64,11 +64,12 @@ class BasicOperation { template struct BasicScheduledOperation { - struct State { + class State { std::mutex m_; std::condition_variable ready_; std::optional op_{std::nullopt}; + public: void emplace(auto&& op) { @@ -86,11 +87,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)); }) { @@ -99,26 +100,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/SyncExecutionContext.hpp b/src/util/async/context/SyncExecutionContext.hpp index 9b69b13e8..1a1a9a50d 100644 --- a/src/util/async/context/SyncExecutionContext.hpp +++ b/src/util/async/context/SyncExecutionContext.hpp @@ -83,7 +83,7 @@ struct SameThreadContext { struct SystemContextProvider { template - [[nodiscard]] static constexpr auto& + [[nodiscard]] constexpr static auto& getContext([[maybe_unused]] CtxType& self) noexcept { return SystemExecutionContext::instance(); diff --git a/src/util/async/context/impl/Utils.hpp b/src/util/async/context/impl/Utils.hpp index 2cd8045ae..1d14cc659 100644 --- a/src/util/async/context/impl/Utils.hpp +++ b/src/util/async/context/impl/Utils.hpp @@ -75,7 +75,7 @@ outcomeForHandler(auto&& fn) struct SelfContextProvider { template - [[nodiscard]] static constexpr auto& + [[nodiscard]] constexpr static auto& getContext(CtxType& self) noexcept { return self; diff --git a/src/util/async/impl/ErrorHandling.hpp b/src/util/async/impl/ErrorHandling.hpp index 9ab7694c5..6be373937 100644 --- a/src/util/async/impl/ErrorHandling.hpp +++ b/src/util/async/impl/ErrorHandling.hpp @@ -53,7 +53,7 @@ struct DefaultErrorHandler { }; struct NoErrorHandler { - [[nodiscard]] static constexpr auto + [[nodiscard]] constexpr static auto wrap(auto&& fn) { return std::forward(fn); diff --git a/src/util/config/Config.cpp b/src/util/config/Config.cpp index a54b94e3b..26ae02165 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 += separator; maybeSection = tokenized.next(); } diff --git a/src/util/config/Config.hpp b/src/util/config/Config.hpp index 64403f5cd..27322f480 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 separator = '.'; public: using KeyType = std::string; diff --git a/src/util/log/Logger.cpp b/src/util/log/Logger.cpp index 06a7782cd..84fc6d1f4 100644 --- a/src/util/log/Logger.cpp +++ b/src/util/log/Logger.cpp @@ -61,9 +61,9 @@ 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) @@ -118,12 +118,12 @@ LogService::init(util::Config const& config) if (config.valueOr("log_to_console", false)) { 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); if (auto logDir = config.maybeValue("log_directory"); logDir) { boost::filesystem::path dirPath{logDir.value()}; @@ -152,13 +152,13 @@ LogService::init(util::Config const& config) auto defaultSeverity = config.valueOr("log_level", Severity::NFO); std::unordered_map min_severity; - for (auto const& channel : Logger::CHANNELS) + for (auto const& channel : Logger::channels) min_severity[channel] = defaultSeverity; min_severity["Alert"] = Severity::WRN; // Channel for alerts, always warning severity for (auto const overrides = config.arrayOr("log_channels", {}); auto const& cfg : overrides) { auto name = cfg.valueOrThrow("channel", "Channel name is required"); - if (std::count(std::begin(Logger::CHANNELS), std::end(Logger::CHANNELS), name) == 0) + if (std::count(std::begin(Logger::channels), std::end(Logger::channels), name) == 0) throw std::runtime_error("Can't override settings for log channel " + name + ": invalid channel"); min_severity[name] = cfg.valueOr("log_level", defaultSeverity); @@ -166,8 +166,8 @@ LogService::init(util::Config const& config) 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 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()) @@ -175,8 +175,8 @@ LogService::init(util::Config const& config) 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(log_filter)}; + boost::log::core::get()->set_filter(filter); LOG(LogService::info()) << "Default log level = " << defaultSeverity; } diff --git a/src/util/log/Logger.hpp b/src/util/log/Logger.hpp index 46ecd4763..62a1a58ac 100644 --- a/src/util/log/Logger.hpp +++ b/src/util/log/Logger.hpp @@ -81,8 +81,8 @@ enum class Severity { }; /** @cond */ -BOOST_LOG_ATTRIBUTE_KEYWORD(log_severity, "Severity", Severity); -BOOST_LOG_ATTRIBUTE_KEYWORD(log_channel, "Channel", std::string); +BOOST_LOG_ATTRIBUTE_KEYWORD(LogSeverity, "Severity", Severity); +BOOST_LOG_ATTRIBUTE_KEYWORD(LogChannel, "Channel", std::string); /** @endcond */ /** @@ -177,7 +177,7 @@ class Logger final { }; public: - static constexpr std::array CHANNELS = { + static constexpr std::array channels = { "General", "WebServer", "Backend", @@ -272,9 +272,9 @@ class Logger final { * 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; @@ -296,7 +296,7 @@ class LogService { [[nodiscard]] static Logger::Pump trace(SourceLocationType const& loc = CURRENT_SRC_LOCATION) { - return general_log_.trace(loc); + return generalLog.trace(loc); } /** @@ -308,7 +308,7 @@ class LogService { [[nodiscard]] static Logger::Pump debug(SourceLocationType const& loc = CURRENT_SRC_LOCATION) { - return general_log_.debug(loc); + return generalLog.debug(loc); } /** @@ -320,7 +320,7 @@ class LogService { [[nodiscard]] static Logger::Pump info(SourceLocationType const& loc = CURRENT_SRC_LOCATION) { - return general_log_.info(loc); + return generalLog.info(loc); } /** @@ -332,7 +332,7 @@ class LogService { [[nodiscard]] static Logger::Pump warn(SourceLocationType const& loc = CURRENT_SRC_LOCATION) { - return general_log_.warn(loc); + return generalLog.warn(loc); } /** @@ -344,7 +344,7 @@ class LogService { [[nodiscard]] static Logger::Pump error(SourceLocationType const& loc = CURRENT_SRC_LOCATION) { - return general_log_.error(loc); + return generalLog.error(loc); } /** @@ -356,7 +356,7 @@ class LogService { [[nodiscard]] static Logger::Pump fatal(SourceLocationType const& loc = CURRENT_SRC_LOCATION) { - return general_log_.fatal(loc); + return generalLog.fatal(loc); } /** @@ -368,7 +368,7 @@ class LogService { [[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.hpp b/src/util/newconfig/ConfigConstraints.hpp index 79027d55a..95a46f5bf 100644 --- a/src/util/newconfig/ConfigConstraints.hpp +++ b/src/util/newconfig/ConfigConstraints.hpp @@ -341,7 +341,7 @@ class PositiveDouble final : public Constraint { static constinit PortConstraint validatePort{}; static constinit ValidIPConstraint validateIP{}; -static constinit OneOf validateChannelName{"channel", Logger::CHANNELS}; +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}; diff --git a/src/util/newconfig/ConfigDescription.hpp b/src/util/newconfig/ConfigDescription.hpp index 1fbb5406c..9412dc31d 100644 --- a/src/util/newconfig/ConfigDescription.hpp +++ b/src/util/newconfig/ConfigDescription.hpp @@ -62,7 +62,7 @@ struct ClioConfigDescription { } private: - static constexpr auto configDescription = std::array{ + constexpr static auto configDescription = std::array{ KV{"database.type", "Type of database to use."}, KV{"database.cassandra.contact_points", "Comma-separated list of contact points for Cassandra nodes."}, KV{"database.cassandra.port", "Port number to connect to Cassandra."}, diff --git a/src/util/prometheus/MetricBase.cpp b/src/util/prometheus/MetricBase.cpp index f7d997004..52f7c369b 100644 --- a/src/util/prometheus/MetricBase.cpp +++ b/src/util/prometheus/MetricBase.cpp @@ -43,17 +43,17 @@ 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: return "summary"; diff --git a/src/util/prometheus/MetricBase.hpp b/src/util/prometheus/MetricBase.hpp index 5fc1d5240..81a080561 100644 --- a/src/util/prometheus/MetricBase.hpp +++ b/src/util/prometheus/MetricBase.hpp @@ -83,15 +83,7 @@ class MetricBase { 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 5dafb9885..5fe3b55eb 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,17 +66,17 @@ 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: [[fallthrough]]; @@ -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,20 +105,20 @@ 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: [[fallthrough]]; diff --git a/src/util/prometheus/MetricsFamily.cpp b/src/util/prometheus/MetricsFamily.cpp index 34c42cf7a..1c02f6fd1 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 24ad51f86..b207e9905 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 const& config) bool const enabled = config.valueOr("prometheus.enabled", true); bool const compressReply = config.valueOr("prometheus.compress_reply", true); - 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 impl) { - instance_ = std::move(instance); + PrometheusService::impl = std::move(impl); } 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 fe9629bd9..74a8c6f6b 100644 --- a/src/util/prometheus/Prometheus.hpp +++ b/src/util/prometheus/Prometheus.hpp @@ -393,10 +393,10 @@ class PrometheusService { * * @note Be careful with this method because there could be hanging references to counters * - * @param instance The new prometheus object + * @param impl The new prometheus object */ static void - replaceInstance(std::unique_ptr instance); + replaceInstance(std::unique_ptr impl); /** * @brief Get the prometheus object stored in the singleton @@ -407,5 +407,5 @@ class PrometheusService { 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 98dc81e4b..b09f001be 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 @@ class AnyCounterBase { 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.hpp b/src/util/requests/RequestBuilder.hpp index e1aeeed59..52cfcf690 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_{defaultTimeout}; boost::beast::http::request request_; public: @@ -181,7 +181,7 @@ class RequestBuilder { 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 defaultTimeout{30000}; /**< Default timeout for requests */ private: std::expected diff --git a/src/util/requests/WsConnection.hpp b/src/util/requests/WsConnection.hpp index 5f2320539..fe22fccad 100644 --- a/src/util/requests/WsConnection.hpp +++ b/src/util/requests/WsConnection.hpp @@ -85,9 +85,9 @@ class WsConnection { * @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 = defaultTimeout) = 0; - static constexpr std::chrono::seconds DEFAULT_TIMEOUT{5}; /**< Default timeout for connecting */ + static constexpr std::chrono::seconds defaultTimeout{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_{defaultTimeout}; + std::chrono::steady_clock::duration wsHandshakeTimeout_{defaultTimeout}; std::string target_{"/"}; public: @@ -184,7 +184,7 @@ class WsConnectionBuilder { 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 defaultTimeout{5}; /**< Default timeout for connecting */ private: template diff --git a/src/util/requests/impl/WsConnectionImpl.hpp b/src/util/requests/impl/WsConnectionImpl.hpp index b588e5d01..da5f6ca13 100644 --- a/src/util/requests/impl/WsConnectionImpl.hpp +++ b/src/util/requests/impl/WsConnectionImpl.hpp @@ -101,8 +101,7 @@ class WsConnectionImpl : public WsConnection { } std::optional - close(boost::asio::yield_context yield, std::chrono::steady_clock::duration const timeout = DEFAULT_TIMEOUT) - override + close(boost::asio::yield_context yield, std::chrono::steady_clock::duration const timeout = defaultTimeout) override { // Set the timeout for closing the connection boost::beast::websocket::stream_base::timeout wsTimeout{}; diff --git a/src/web/RPCServerHandler.hpp b/src/web/RPCServerHandler.hpp index 46ee718ba..9842972cf 100644 --- a/src/web/RPCServerHandler.hpp +++ b/src/web/RPCServerHandler.hpp @@ -253,10 +253,10 @@ class RPCServerHandler { } 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/dosguard/DOSGuard.cpp b/src/web/dosguard/DOSGuard.cpp index f3b529611..e67e244d0 100644 --- a/src/web/dosguard/DOSGuard.cpp +++ b/src/web/dosguard/DOSGuard.cpp @@ -37,9 +37,9 @@ namespace web::dosguard { DOSGuard::DOSGuard(util::Config const& config, WhitelistHandlerInterface const& whitelistHandler) : whitelistHandler_{std::cref(whitelistHandler)} - , maxFetches_{config.valueOr("dos_guard.max_fetches", DEFAULT_MAX_FETCHES)} - , maxConnCount_{config.valueOr("dos_guard.max_connections", DEFAULT_MAX_CONNECTIONS)} - , maxRequestCount_{config.valueOr("dos_guard.max_requests", DEFAULT_MAX_REQUESTS)} + , maxFetches_{config.valueOr("dos_guard.max_fetches", defaultMaxFetches)} + , maxConnCount_{config.valueOr("dos_guard.max_connections", defaultMaxConnections)} + , maxRequestCount_{config.valueOr("dos_guard.max_requests", defaultMaxRequests)} { } diff --git a/src/web/dosguard/DOSGuard.hpp b/src/web/dosguard/DOSGuard.hpp index 79798f052..1c8579977 100644 --- a/src/web/dosguard/DOSGuard.hpp +++ b/src/web/dosguard/DOSGuard.hpp @@ -63,9 +63,9 @@ class DOSGuard : public DOSGuardInterface { util::Logger log_{"RPC"}; public: - static constexpr std::uint32_t DEFAULT_MAX_FETCHES = 1000'000u; /**< Default maximum fetches per sweep */ - static constexpr std::uint32_t DEFAULT_MAX_CONNECTIONS = 20u; /**< Default maximum concurrent connections */ - static constexpr std::uint32_t DEFAULT_MAX_REQUESTS = 20u; /**< Default maximum requests per sweep */ + static constexpr std::uint32_t defaultMaxFetches = 1000'000u; /**< Default maximum fetches per sweep */ + static constexpr std::uint32_t defaultMaxConnections = 20u; /**< Default maximum concurrent connections */ + static constexpr std::uint32_t defaultMaxRequests = 20u; /**< Default maximum requests per sweep */ /** * @brief Constructs a new DOS guard. diff --git a/src/web/impl/ErrorHandling.hpp b/src/web/impl/ErrorHandling.hpp index bc3fdf0b1..5ffbbaa0c 100644 --- a/src/web/impl/ErrorHandling.hpp +++ b/src/web/impl/ErrorHandling.hpp @@ -64,38 +64,38 @@ class ErrorHelper { // 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 609eb7e2d..b87c99e4a 100644 --- a/src/web/impl/HttpBase.hpp +++ b/src/web/impl/HttpBase.hpp @@ -80,9 +80,9 @@ 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) { } @@ -90,7 +90,7 @@ class HttpBase : public ConnectionBase { void 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 @@ -98,13 +98,13 @@ class HttpBase : public ConnectionBase { 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()) ); } }; @@ -266,9 +266,9 @@ class HttpBase : public ConnectionBase { 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 diff --git a/src/web/impl/WsBase.hpp b/src/web/impl/WsBase.hpp index 003ec029f..9f5e2381d 100644 --- a/src/web/impl/WsBase.hpp +++ b/src/web/impl/WsBase.hpp @@ -216,9 +216,9 @@ class WsBase : public ConnectionBase, public std::enable_shared_from_this - receive(boost::asio::yield_context yield, std::chrono::steady_clock::duration timeout = DEFAULT_TIMEOUT) = 0; + receive(boost::asio::yield_context yield, std::chrono::steady_clock::duration timeout = defaultTimeout) = 0; /** * @brief Gracefully close the connection. @@ -148,7 +148,7 @@ class Connection : public ConnectionMetadata { * @param timeout The timeout for the operation. */ virtual void - 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 = defaultTimeout) = 0; }; /** diff --git a/src/web/ng/RPCServerHandler.hpp b/src/web/ng/RPCServerHandler.hpp index 2774fa931..7baae3ef1 100644 --- a/src/web/ng/RPCServerHandler.hpp +++ b/src/web/ng/RPCServerHandler.hpp @@ -293,10 +293,10 @@ class RPCServerHandler { } 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 ac76f1ac8..5a17b79d0 100644 --- a/src/web/ng/Response.cpp +++ b/src/web/ng/Response.cpp @@ -58,6 +58,7 @@ prepareResponse(http::response response, http::request, std::string> makeData(http::status status, MessageType message, Request const& request) { std::string body; + if constexpr (isString()) { body = std::move(message); } else { @@ -86,19 +88,19 @@ makeData(http::status status, MessageType message, Request const& request) } // 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::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()); + data = prepareResponse(std::move(response), request.asHttpRequest()->get()); } std::string const& @@ -109,23 +111,24 @@ Response::message() const [](http::response const& response) -> std::string const& { return response.body(); }, [](std::string const& message) -> std::string const& { return message; }, }, - data_ + data ); } 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 b9d197283..791c7e709 100644 --- a/src/web/ng/Response.hpp +++ b/src/web/ng/Response.hpp @@ -37,7 +37,7 @@ namespace web::ng { */ class Response { public: - std::variant, std::string> data_; + std::variant, std::string> data; public: /** diff --git a/src/web/ng/impl/ErrorHandling.cpp b/src/web/ng/impl/ErrorHandling.cpp index 49416d9bd..ec6ca4bf6 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 3a598c38b..a3cf65024 100644 --- a/src/web/ng/impl/HttpConnection.hpp +++ b/src/web/ng/impl/HttpConnection.hpp @@ -56,7 +56,7 @@ class UpgradableConnection : public Connection { virtual std::expected isUpgradeRequested( boost::asio::yield_context yield, - std::chrono::steady_clock::duration timeout = DEFAULT_TIMEOUT + std::chrono::steady_clock::duration timeout = defaultTimeout ) = 0; virtual std::expected @@ -109,7 +109,7 @@ class HttpConnection : public UpgradableConnection { send( Response response, boost::asio::yield_context yield, - std::chrono::steady_clock::duration timeout = DEFAULT_TIMEOUT + std::chrono::steady_clock::duration timeout = defaultTimeout ) override { auto const httpResponse = std::move(response).intoHttpResponse(); @@ -122,7 +122,7 @@ class HttpConnection : public UpgradableConnection { } std::expected - receive(boost::asio::yield_context yield, std::chrono::steady_clock::duration timeout = DEFAULT_TIMEOUT) override + receive(boost::asio::yield_context yield, std::chrono::steady_clock::duration timeout = defaultTimeout) override { if (request_.has_value()) { Request result{std::move(request_).value()}; @@ -137,7 +137,7 @@ class HttpConnection : public UpgradableConnection { } void - close(boost::asio::yield_context yield, std::chrono::steady_clock::duration timeout = DEFAULT_TIMEOUT) override + close(boost::asio::yield_context yield, std::chrono::steady_clock::duration timeout = defaultTimeout) override { [[maybe_unused]] boost::system::error_code error; if constexpr (IsSslTcpStream) { @@ -154,7 +154,7 @@ class HttpConnection : public UpgradableConnection { } std::expected - isUpgradeRequested(boost::asio::yield_context yield, std::chrono::steady_clock::duration timeout = DEFAULT_TIMEOUT) + isUpgradeRequested(boost::asio::yield_context yield, std::chrono::steady_clock::duration timeout = defaultTimeout) override { auto expectedRequest = fetch(yield, timeout); diff --git a/src/web/ng/impl/WsConnection.hpp b/src/web/ng/impl/WsConnection.hpp index 26d1c4bf6..75590c11a 100644 --- a/src/web/ng/impl/WsConnection.hpp +++ b/src/web/ng/impl/WsConnection.hpp @@ -61,7 +61,7 @@ class WsConnectionBase : public Connection { sendBuffer( boost::asio::const_buffer buffer, boost::asio::yield_context yield, - std::chrono::steady_clock::duration timeout = Connection::DEFAULT_TIMEOUT + std::chrono::steady_clock::duration timeout = Connection::defaultTimeout ) = 0; }; @@ -128,7 +128,7 @@ class WsConnection : public WsConnectionBase { sendBuffer( boost::asio::const_buffer buffer, boost::asio::yield_context yield, - std::chrono::steady_clock::duration timeout = Connection::DEFAULT_TIMEOUT + std::chrono::steady_clock::duration timeout = Connection::defaultTimeout ) override { auto error = @@ -142,14 +142,14 @@ class WsConnection : public WsConnectionBase { send( Response response, boost::asio::yield_context yield, - std::chrono::steady_clock::duration timeout = DEFAULT_TIMEOUT + std::chrono::steady_clock::duration timeout = defaultTimeout ) override { return sendBuffer(response.asWsResponse(), yield, timeout); } std::expected - receive(boost::asio::yield_context yield, std::chrono::steady_clock::duration timeout = DEFAULT_TIMEOUT) override + receive(boost::asio::yield_context yield, std::chrono::steady_clock::duration timeout = defaultTimeout) override { auto error = util::withTimeout([this](auto&& yield) { stream_.async_read(buffer_, yield); }, yield, timeout); if (error) @@ -162,7 +162,7 @@ class WsConnection : public WsConnectionBase { } void - close(boost::asio::yield_context yield, std::chrono::steady_clock::duration timeout = DEFAULT_TIMEOUT) override + close(boost::asio::yield_context yield, std::chrono::steady_clock::duration timeout = defaultTimeout) override { boost::beast::websocket::stream_base::timeout wsTimeout{}; stream_.get_option(wsTimeout); From d554256f1de31eb08ae22077f336ab072948931a Mon Sep 17 00:00:00 2001 From: Alex Kremer Date: Tue, 26 Nov 2024 00:29:23 +0000 Subject: [PATCH 02/22] Fix tests clang-tidy and compilation --- tests/common/etl/FakeDiffProvider.hpp | 14 +-- tests/common/util/AsioContextTestFixture.hpp | 20 ++--- tests/common/util/FakeFetchResponse.hpp | 4 +- tests/common/util/LoggerFixtures.hpp | 4 +- tests/common/util/MockBackendTestFixture.hpp | 15 ++-- tests/unit/data/BackendCountersTests.cpp | 10 +-- .../data/cassandra/ExecutionStrategyTests.cpp | 48 +++++----- tests/unit/etl/ETLStateTests.cpp | 2 +- tests/unit/etl/ExtractorTests.cpp | 11 +-- tests/unit/etl/ForwardingSourceTests.cpp | 37 ++++---- tests/unit/etl/GrpcSourceTests.cpp | 2 + tests/unit/etl/LoadBalancerTests.cpp | 84 ++++++++++-------- tests/unit/etl/SourceImplTests.cpp | 1 + tests/unit/etl/SubscriptionSourceTests.cpp | 43 ++++----- tests/unit/etl/TransformerTests.cpp | 17 ++-- tests/unit/etlng/GrpcSourceTests.cpp | 2 + tests/unit/rpc/BaseTests.cpp | 26 +++--- tests/unit/rpc/ErrorTests.cpp | 18 ++-- tests/unit/rpc/ForwardingProxyTests.cpp | 4 +- tests/unit/rpc/common/CheckersTests.cpp | 10 +-- tests/unit/rpc/common/SpecsTests.cpp | 39 ++++---- .../rpc/handlers/AccountChannelsTests.cpp | 8 +- .../rpc/handlers/AccountCurrenciesTests.cpp | 2 +- tests/unit/rpc/handlers/AccountInfoTests.cpp | 4 +- tests/unit/rpc/handlers/AccountLinesTests.cpp | 10 +-- tests/unit/rpc/handlers/AccountNFTsTests.cpp | 8 +- .../unit/rpc/handlers/AccountObjectsTests.cpp | 8 +- .../unit/rpc/handlers/AccountOffersTests.cpp | 22 ++--- tests/unit/rpc/handlers/BookOffersTests.cpp | 8 +- tests/unit/rpc/handlers/LedgerDataTests.cpp | 18 ++-- tests/unit/rpc/handlers/LedgerEntryTests.cpp | 2 +- tests/unit/rpc/handlers/LedgerTests.cpp | 14 +-- tests/unit/rpc/handlers/MPTHoldersTests.cpp | 8 +- tests/unit/rpc/handlers/NFTBuyOffersTests.cpp | 24 ++--- tests/unit/rpc/handlers/NFTHistoryTests.cpp | 4 +- .../unit/rpc/handlers/NFTSellOffersTests.cpp | 24 ++--- tests/unit/rpc/handlers/NFTsByIssuerTest.cpp | 4 +- .../unit/rpc/handlers/NoRippleCheckTests.cpp | 12 +-- tests/unit/rpc/handlers/ServerInfoTests.cpp | 41 ++++----- tests/unit/rpc/handlers/SubscribeTests.cpp | 57 ++++++------ tests/unit/rpc/handlers/UnsubscribeTests.cpp | 45 +++++----- tests/unit/util/CoroutineGroupTests.cpp | 1 + tests/unit/util/RetryTests.cpp | 2 + tests/unit/util/SignalsHandlerTests.cpp | 11 ++- tests/unit/util/async/AnyStopTokenTests.cpp | 5 +- .../unit/util/newconfig/ConfigValueTests.cpp | 4 +- tests/unit/util/prometheus/BoolTests.cpp | 2 + tests/unit/util/prometheus/GaugeTests.cpp | 24 ++--- .../util/prometheus/MetricBuilderTests.cpp | 28 +++--- .../util/prometheus/MetricsFamilyTests.cpp | 2 +- tests/unit/web/ServerTests.cpp | 14 +-- tests/unit/web/SubscriptionContextTests.cpp | 1 + tests/unit/web/dosguard/DOSGuardTests.cpp | 78 ++++++++-------- .../dosguard/IntervalSweepHandlerTests.cpp | 4 +- tests/unit/web/impl/ErrorHandlingTests.cpp | 11 +-- tests/unit/web/ng/RPCServerHandlerTests.cpp | 64 +++++++------- tests/unit/web/ng/RequestTests.cpp | 1 + tests/unit/web/ng/ResponseTests.cpp | 1 + tests/unit/web/ng/ServerTests.cpp | 2 + .../unit/web/ng/SubscriptionContextTests.cpp | 25 +++--- .../web/ng/impl/ConnectionHandlerTests.cpp | 1 + tests/unit/web/ng/impl/ErrorHandlingTests.cpp | 88 +++++++++---------- .../unit/web/ng/impl/HttpConnectionTests.cpp | 11 +-- tests/unit/web/ng/impl/WsConnectionTests.cpp | 31 +++---- 64 files changed, 596 insertions(+), 549 deletions(-) diff --git a/tests/common/etl/FakeDiffProvider.hpp b/tests/common/etl/FakeDiffProvider.hpp index 3bfec9046..868ed44ca 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) { + if (threadKeysMap_[std::this_thread::get_id()] == keysSize - 1) { return data::lastKey; } - 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/util/AsioContextTestFixture.hpp b/tests/common/util/AsioContextTestFixture.hpp index da00ad300..bf05d8852 100644 --- a/tests/common/util/AsioContextTestFixture.hpp +++ b/tests/common/util/AsioContextTestFixture.hpp @@ -38,24 +38,24 @@ 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(); + work_.reset(); + if (runner_->joinable()) + runner_->join(); ctx.stop(); } void stop() { - work.reset(); - if (runner->joinable()) - runner->join(); + work_.reset(); + if (runner_->joinable()) + runner_->join(); ctx.stop(); } @@ -63,8 +63,8 @@ struct AsyncAsioContextTest : virtual public NoLoggerFixture { boost::asio::io_context ctx; private: - std::optional work; - std::optional runner; + std::optional work_; + std::optional runner_; }; /** diff --git a/tests/common/util/FakeFetchResponse.hpp b/tests/common/util/FakeFetchResponse.hpp index 100ec6694..3d9e78d83 100644 --- a/tests/common/util/FakeFetchResponse.hpp +++ b/tests/common/util/FakeFetchResponse.hpp @@ -122,13 +122,13 @@ class FakeLedgerObject { }; class FakeLedgerObjects { - std::vector objects; + std::vector objects_; public: std::vector* mutable_objects() { - return &objects; + return &objects_; } }; diff --git a/tests/common/util/LoggerFixtures.hpp b/tests/common/util/LoggerFixtures.hpp index dcaa6d810..f87f69678 100644 --- a/tests/common/util/LoggerFixtures.hpp +++ b/tests/common/util/LoggerFixtures.hpp @@ -73,9 +73,9 @@ class LoggerFixture : virtual public ::testing::Test { 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 min_severity = expr::channel_severity_filter(util::LogChannel, util::LogSeverity); - std::ranges::for_each(util::Logger::CHANNELS, [&min_severity](char const* channel) { + std::ranges::for_each(util::Logger::channels, [&min_severity](char const* channel) { min_severity[channel] = util::Severity::TRC; }); diff --git a/tests/common/util/MockBackendTestFixture.hpp b/tests/common/util/MockBackendTestFixture.hpp index eee311459..32072c014 100644 --- a/tests/common/util/MockBackendTestFixture.hpp +++ b/tests/common/util/MockBackendTestFixture.hpp @@ -19,35 +19,40 @@ #pragma once +#include "data/BackendInterface.hpp" #include "util/LoggerFixtures.hpp" #include "util/MockBackend.hpp" +#include + +#include + template