From 94e9b549a2d4a59a34f807c94af2adeaaecb9e15 Mon Sep 17 00:00:00 2001 From: Mathias Stearn Date: Fri, 15 Nov 2024 15:32:08 +0100 Subject: [PATCH] SERVER-97062 No anon namespaces or function/variable definitions in headers (#29139) GitOrigin-RevId: 8c4bfe921c786a6575e1fbca26227097ca4a46ef --- .clang-tidy.in | 4 +- buildscripts/clang_tidy_vscode.py | 2 +- src/mongo/bson/bson_bin_util.h | 8 +-- .../db/commands/db_command_test_fixture.h | 5 +- src/mongo/db/exec/sbe/vm/vm_makeobj.h | 2 - src/mongo/db/exec/sbe/vm/vm_memory.h | 2 - .../db/exec/timeseries/bucket_unpacker.h | 6 +- .../db/pipeline/aggregation_context_fixture.h | 4 +- .../db/pipeline/initialize_auto_get_helper.h | 4 +- src/mongo/db/query/optimizer/containers.h | 4 +- .../projection_ast_path_tracking_visitor.h | 2 - .../query/query_shape/serialization_options.h | 12 ++-- .../query_stats/query_stats_store_test.cpp | 4 +- src/mongo/db/query/search/mongot_cursor.h | 4 +- .../query/stage_builder/sbe/sbexpr_helpers.h | 2 - src/mongo/db/query/write_ops/update_request.h | 10 ++-- src/mongo/db/repl/collection_cloner.h | 6 +- ...nalyze_shard_key_read_write_distribution.h | 2 - src/mongo/db/service_entry_point_bm_fixture.h | 11 ++-- .../service_entry_point_shard_role_helpers.h | 56 +++++++++---------- src/mongo/db/vector_clock_mongod.h | 2 - src/mongo/executor/async_rpc.h | 4 +- src/mongo/executor/mock_async_rpc.h | 4 +- .../task_executor_cursor_test_fixture.h | 15 ++--- src/mongo/s/async_rpc_shard_retry_policy.h | 4 +- .../commands/cluster_abort_transaction_cmd.h | 2 - .../commands/cluster_commit_transaction_cmd.h | 2 - .../internal_transactions_test_command.h | 4 -- .../s/commands/query_cmd/cluster_count_cmd.h | 12 ++-- .../s/commands/query_cmd/cluster_find_cmd.h | 4 +- .../commands/query_cmd/cluster_getmore_cmd.h | 5 +- .../commands/query_cmd/cluster_pipeline_cmd.h | 2 - src/mongo/util/dns_query_posix-impl.h | 4 +- 33 files changed, 81 insertions(+), 133 deletions(-) diff --git a/.clang-tidy.in b/.clang-tidy.in index a67625e4f29..ca915b6db40 100644 --- a/.clang-tidy.in +++ b/.clang-tidy.in @@ -57,8 +57,10 @@ Checks: '-*, bugprone-unused-return-value, bugprone-use-after-move, clang-diagnostic-*, + google-build-namespaces, hicpp-static-assert, hicpp-undelegated-constructor, + misc-definitions-in-headers, misc-new-delete-overloads, misc-static-assert, misc-unconventional-assign-operator, @@ -114,7 +116,6 @@ Checks: '-*, -cppcoreguidelines-interfaces-global-init, -cppcoreguidelines-narrowing-conversions, -google-build-explicit-make-pair, - -google-build-namespaces, -google-global-names-in-headers, -google-objc-avoid-throwing-exception, -google-objc-global-variable-declaration, @@ -130,7 +131,6 @@ Checks: '-*, -hicpp-use-equals-delete, -hicpp-use-noexcept, -hicpp-vararg, - -misc-definitions-in-headers, -misc-misplaced-const, -misc-non-copyable-objects, -misc-redundant-expression, diff --git a/buildscripts/clang_tidy_vscode.py b/buildscripts/clang_tidy_vscode.py index 92df61d0f3a..7b9aeb53f97 100755 --- a/buildscripts/clang_tidy_vscode.py +++ b/buildscripts/clang_tidy_vscode.py @@ -43,7 +43,7 @@ def main(): if os.path.isfile(arg): source_relative_path = os.path.relpath(arg, os.path.dirname(os.path.dirname(__file__))) if ( - arg.endswith(".cpp") + (arg.endswith(".cpp") or arg.endswith(".h")) and source_relative_path.startswith("src/mongo") # TODO: SERVER-79076 remove this condition when resolved and not source_relative_path.startswith( diff --git a/src/mongo/bson/bson_bin_util.h b/src/mongo/bson/bson_bin_util.h index 0408d465504..fa93b0a7c3b 100644 --- a/src/mongo/bson/bson_bin_util.h +++ b/src/mongo/bson/bson_bin_util.h @@ -42,7 +42,7 @@ namespace mongo { namespace bson_bin_util { -std::string toHex(const char* data, std::size_t len) { +inline std::string toHex(const char* data, std::size_t len) { auto rawString = mongo::StringData(data, len); std::ostringstream hexString; hexString << std::hex << std::uppercase; @@ -53,15 +53,15 @@ std::string toHex(const char* data, std::size_t len) { return hexString.str(); } -std::string toHex(const BufBuilder& bldr) { +inline std::string toHex(const BufBuilder& bldr) { return toHex(static_cast(bldr.buf()), static_cast(bldr.len())); } -std::string toHex(const BSONBinData& binData) { +inline std::string toHex(const BSONBinData& binData) { return toHex(static_cast(binData.data), static_cast(binData.length)); } -std::string toHex(const BSONObj& obj) { +inline std::string toHex(const BSONObj& obj) { return toHex(obj.objdata(), static_cast(obj.objsize())); } diff --git a/src/mongo/db/commands/db_command_test_fixture.h b/src/mongo/db/commands/db_command_test_fixture.h index fb82c714d94..5895dbb5c2e 100644 --- a/src/mongo/db/commands/db_command_test_fixture.h +++ b/src/mongo/db/commands/db_command_test_fixture.h @@ -36,8 +36,6 @@ #include "mongo/util/assert_util_core.h" namespace mongo { -namespace { - class DBCommandTestFixture : public ServiceContextMongoDTest { public: void setUp() override { @@ -65,8 +63,7 @@ public: static const DatabaseName kDatabaseName; }; -const DatabaseName DBCommandTestFixture::kDatabaseName = +inline const DatabaseName DBCommandTestFixture::kDatabaseName = DatabaseName::createDatabaseName_forTest(boost::none, "unittest_db"); -} // namespace } // namespace mongo diff --git a/src/mongo/db/exec/sbe/vm/vm_makeobj.h b/src/mongo/db/exec/sbe/vm/vm_makeobj.h index e74cd784896..b82c43ac4d1 100644 --- a/src/mongo/db/exec/sbe/vm/vm_makeobj.h +++ b/src/mongo/db/exec/sbe/vm/vm_makeobj.h @@ -41,7 +41,6 @@ #include "mongo/platform/compiler.h" namespace mongo::sbe::vm { -namespace { class MakeObjImpl : ByteCode::MakeObjImplBase { public: using BaseT = ByteCode::MakeObjImplBase; @@ -360,5 +359,4 @@ private: traverseAndProduceObj(spec, tag, val, fieldName, bob); } }; -} // namespace } // namespace mongo::sbe::vm diff --git a/src/mongo/db/exec/sbe/vm/vm_memory.h b/src/mongo/db/exec/sbe/vm/vm_memory.h index 06f0ed22406..941343c9184 100644 --- a/src/mongo/db/exec/sbe/vm/vm_memory.h +++ b/src/mongo/db/exec/sbe/vm/vm_memory.h @@ -32,7 +32,6 @@ namespace mongo { namespace sbe { namespace vm { -namespace { /** * Reads directly from memory for the ByteCode VM. */ @@ -56,7 +55,6 @@ size_t writeToMemory(uint8_t* ptr, const T val) noexcept { return sizeof(T); } -} // namespace } // namespace vm } // namespace sbe } // namespace mongo diff --git a/src/mongo/db/exec/timeseries/bucket_unpacker.h b/src/mongo/db/exec/timeseries/bucket_unpacker.h index 05d5f096baf..8ed10894bc8 100644 --- a/src/mongo/db/exec/timeseries/bucket_unpacker.h +++ b/src/mongo/db/exec/timeseries/bucket_unpacker.h @@ -54,7 +54,6 @@ #include "mongo/util/time_support.h" namespace mongo::timeseries { -namespace { // A table that is useful for interpolations between the number of measurements in a bucket and // the byte size of a bucket's data section timestamp column. Each table entry is a pair (b_i, // S_i), where b_i is the number of measurements in the bucket and S_i is the byte size of the @@ -62,7 +61,7 @@ namespace { // pairs of b_i and S_i for the lower bounds of the row key digit intervals [0, 9], [10, 99], // [100, 999], [1000, 9999] and so on. The last entry in the table, S7, is the first entry to // exceed the server BSON object limit of 16 MB. -static constexpr std::array, 8> kTimestampObjSizeTable{ +inline constexpr std::array, 8> kTimestampObjSizeTable{ {{0, BSONObj::kMinBSONLength}, {10, 115}, {100, 1195}, @@ -79,7 +78,7 @@ static constexpr std::array, 8> kTimestampObjSizeTab // pair such that 'targetTimestampObjSize' < S_i. Once the interval is found, the upper bound of the // pair for the interval is computed and then linear interpolation is used to compute the // measurement count corresponding to the 'targetTimestampObjSize' provided. -int computeElementCountFromTimestampObjSize(int targetTimestampObjSize) { +inline int computeElementCountFromTimestampObjSize(int targetTimestampObjSize) { auto currentInterval = std::find_if(std::begin(kTimestampObjSizeTable), std::end(kTimestampObjSizeTable), @@ -100,7 +99,6 @@ int computeElementCountFromTimestampObjSize(int targetTimestampObjSize) { return currentInterval->first + ((targetTimestampObjSize - currentInterval->second) / (10 + nDigitsInRowKey)); } -} // namespace /** * BucketUnpacker will unpack bucket fields for metadata and the provided fields. diff --git a/src/mongo/db/pipeline/aggregation_context_fixture.h b/src/mongo/db/pipeline/aggregation_context_fixture.h index e0d6856ab0c..d713f382d6c 100644 --- a/src/mongo/db/pipeline/aggregation_context_fixture.h +++ b/src/mongo/db/pipeline/aggregation_context_fixture.h @@ -245,9 +245,8 @@ struct DocumentSourceDeleter { } }; -namespace { // A utility function to convert pipeline (a vector of BSONObj) to a string. Helpful for debugging. -std::string to_string(const std::vector& objs) { +inline std::string to_string(const std::vector& objs) { std::stringstream sstrm; sstrm << "[" << std::endl; for (const auto& obj : objs) { @@ -256,5 +255,4 @@ std::string to_string(const std::vector& objs) { sstrm << "]" << std::endl; return sstrm.str(); } -} // namespace } // namespace mongo diff --git a/src/mongo/db/pipeline/initialize_auto_get_helper.h b/src/mongo/db/pipeline/initialize_auto_get_helper.h index 71d045ca8d5..e352962220a 100644 --- a/src/mongo/db/pipeline/initialize_auto_get_helper.h +++ b/src/mongo/db/pipeline/initialize_auto_get_helper.h @@ -36,12 +36,11 @@ #include "mongo/s/transaction_router.h" namespace mongo { -namespace { /** * Function which produces an vector of 'ScopedShardRole' objects for the namespaces in 'nssList' * using the routing information in 'criMap'. */ -std::vector createScopedShardRoles( +inline std::vector createScopedShardRoles( OperationContext* opCtx, const stdx::unordered_map& criMap, const std::vector& nssList) { @@ -72,7 +71,6 @@ std::vector createScopedShardRoles( } return scopedShardRoles; } -} // namespace /** * Helper that constructs an 'AutoGetCollectionForReadCommandMaybeLockFree' using 'initAutoGetFn'. diff --git a/src/mongo/db/query/optimizer/containers.h b/src/mongo/db/query/optimizer/containers.h index 5a9c11e9c12..6de7b920c36 100644 --- a/src/mongo/db/query/optimizer/containers.h +++ b/src/mongo/db/query/optimizer/containers.h @@ -38,11 +38,10 @@ namespace mongo::optimizer::opt { -namespace { enum class ContainerImpl { STD, STDX }; // For debugging, switch between STD and STDX containers. -static constexpr ContainerImpl kContainerImpl = ContainerImpl::STDX; +inline constexpr ContainerImpl kContainerImpl = ContainerImpl::STDX; template struct OptContainers {}; @@ -70,7 +69,6 @@ struct OptContainers { }; using ActiveContainers = OptContainers; -} // namespace template , typename... Args> using unordered_set = ActiveContainers::unordered_set; diff --git a/src/mongo/db/query/projection_ast_path_tracking_visitor.h b/src/mongo/db/query/projection_ast_path_tracking_visitor.h index b9d6b5a8b14..83de5e74791 100644 --- a/src/mongo/db/query/projection_ast_path_tracking_visitor.h +++ b/src/mongo/db/query/projection_ast_path_tracking_visitor.h @@ -103,7 +103,6 @@ private: boost::optional _basePath; }; -namespace { /** * A path tracking pre-visitor used for maintaining field names while traversing the AST. * @@ -190,7 +189,6 @@ public: private: PathTrackingVisitorContext* _context; }; -} // namespace /** * A general path tracking walker to be used with projection AST visitors which need to track diff --git a/src/mongo/db/query/query_shape/serialization_options.h b/src/mongo/db/query/query_shape/serialization_options.h index 58211d91f72..ce87886b86b 100644 --- a/src/mongo/db/query/query_shape/serialization_options.h +++ b/src/mongo/db/query/query_shape/serialization_options.h @@ -51,13 +51,6 @@ #include "mongo/util/assert_util.h" namespace mongo { -namespace { -// Should never be called, throw to ensure we catch this in tests. -std::string defaultHmacStrategy(StringData s) { - MONGO_UNREACHABLE_TASSERT(7332410); -} -} // namespace - /** * A policy enum for how to serialize literal values. */ @@ -210,6 +203,11 @@ struct SerializationOptions { Value serializeLiteral(const ImplicitValue& v, const boost::optional& representativeValue = boost::none) const; + // Should never be called, throw to ensure we catch this in tests. + static std::string defaultHmacStrategy(StringData s) { + MONGO_UNREACHABLE_TASSERT(7332410); + } + // 'literalPolicy' is an independent option to serialize in a general format with the aim of // similar "shaped" queries serializing to the same object. For example, if set to // 'kToDebugTypeString', then the serialization of {a: {$gt: 2}} should result in {a: {$gt: diff --git a/src/mongo/db/query/query_stats/query_stats_store_test.cpp b/src/mongo/db/query/query_stats/query_stats_store_test.cpp index dac8aad40ca..915072576ec 100644 --- a/src/mongo/db/query/query_stats/query_stats_store_test.cpp +++ b/src/mongo/db/query/query_stats/query_stats_store_test.cpp @@ -104,7 +104,7 @@ public: SerializationOptions opts = SerializationOptions::kDebugShapeAndMarkIdentifiers_FOR_TEST; if (!applyHmac) { opts.transformIdentifiers = false; - opts.transformIdentifiersCallback = defaultHmacStrategy; + opts.transformIdentifiersCallback = opts.defaultHmacStrategy; } return findKey.toBson( expCtx->getOperationContext(), opts, SerializationContext::stateDefault()); @@ -128,7 +128,7 @@ public: opts.literalPolicy = literalPolicy; if (!applyHmac) { opts.transformIdentifiers = false; - opts.transformIdentifiersCallback = defaultHmacStrategy; + opts.transformIdentifiersCallback = opts.defaultHmacStrategy; } return aggKey->toBson( expCtx->getOperationContext(), opts, SerializationContext::stateDefault()); diff --git a/src/mongo/db/query/search/mongot_cursor.h b/src/mongo/db/query/search/mongot_cursor.h index 8594bcdfd4d..5923c90c626 100644 --- a/src/mongo/db/query/search/mongot_cursor.h +++ b/src/mongo/db/query/search/mongot_cursor.h @@ -34,13 +34,11 @@ #include "mongo/executor/task_executor_cursor.h" namespace mongo::mongot_cursor { -namespace { -auto makeRetryOnNetworkErrorPolicy() { +inline auto makeRetryOnNetworkErrorPolicy() { return [retried = false](const Status& st) mutable { return std::exchange(retried, true) ? false : ErrorCodes::isNetworkError(st); }; } -} // namespace static constexpr StringData kSearchField = "search"_sd; static constexpr StringData kVectorSearchCmd = "vectorSearch"_sd; diff --git a/src/mongo/db/query/stage_builder/sbe/sbexpr_helpers.h b/src/mongo/db/query/stage_builder/sbe/sbexpr_helpers.h index a24efaaedc8..a28e192ca4e 100644 --- a/src/mongo/db/query/stage_builder/sbe/sbexpr_helpers.h +++ b/src/mongo/db/query/stage_builder/sbe/sbexpr_helpers.h @@ -38,7 +38,6 @@ #include "mongo/db/query/stage_builder/sbe/sbexpr.h" namespace mongo::stage_builder { -namespace { inline void makeSbExprOptSbSlotVecHelper(SbExprOptSbSlotVector& result) {} template @@ -79,7 +78,6 @@ inline void makeSbExprOptSbSlotVecHelper(SbExprOptSbSlotVector& result, result.emplace_back(std::move(p.first), p.second); makeSbExprOptSbSlotVecHelper(result, std::forward(rest)...); } -} // namespace template auto makeSbExprOptSbSlotVec(Ts&&... pack) { diff --git a/src/mongo/db/query/write_ops/update_request.h b/src/mongo/db/query/write_ops/update_request.h index bec02c3a64f..c08b230c00a 100644 --- a/src/mongo/db/query/write_ops/update_request.h +++ b/src/mongo/db/query/write_ops/update_request.h @@ -40,11 +40,6 @@ namespace mongo { -namespace { -const std::vector emptyArrayFilters{}; -const BSONObj emptyCollation{}; -const BSONObj emptySort{}; - template void appendArrayToString(const T& arr, StringBuilder* builder) { bool first = true; @@ -58,7 +53,6 @@ void appendArrayToString(const T& arr, StringBuilder* builder) { } *builder << "]"; } -} // namespace class FieldRef; @@ -361,6 +355,10 @@ public: } private: + inline static const std::vector emptyArrayFilters{}; + inline static const BSONObj emptyCollation{}; + inline static const BSONObj emptySort{}; + NamespaceString _nsString; write_ops::UpdateOpEntry _updateOp; diff --git a/src/mongo/db/repl/collection_cloner.h b/src/mongo/db/repl/collection_cloner.h index 7bb56ee1027..3afb394677d 100644 --- a/src/mongo/db/repl/collection_cloner.h +++ b/src/mongo/db/repl/collection_cloner.h @@ -65,10 +65,8 @@ namespace mongo { namespace repl { -namespace { -const int kProgressMeterSecondsBetween = 60; -const int kProgressMeterCheckInterval = 128; -} // namespace +inline const int kProgressMeterSecondsBetween = 60; +inline const int kProgressMeterCheckInterval = 128; class CollectionCloner final : public InitialSyncBaseCloner { public: diff --git a/src/mongo/db/s/analyze_shard_key_read_write_distribution.h b/src/mongo/db/s/analyze_shard_key_read_write_distribution.h index 414c0fdde33..01aad82bcce 100644 --- a/src/mongo/db/s/analyze_shard_key_read_write_distribution.h +++ b/src/mongo/db/s/analyze_shard_key_read_write_distribution.h @@ -68,9 +68,7 @@ namespace mongo { namespace analyze_shard_key { -namespace { using QueryTargetingInfo = shard_key_pattern_query_util::QueryTargetingInfo; -} /** * The utility class for calculating read or write distribution metrics for sampled queries against diff --git a/src/mongo/db/service_entry_point_bm_fixture.h b/src/mongo/db/service_entry_point_bm_fixture.h index 7be930fd008..1ec26920198 100644 --- a/src/mongo/db/service_entry_point_bm_fixture.h +++ b/src/mongo/db/service_entry_point_bm_fixture.h @@ -44,8 +44,6 @@ #include "mongo/util/processinfo.h" namespace mongo { -namespace { - class ServiceEntryPointBenchmarkFixture : public BenchmarkWithProfiler { public: void SetUp(benchmark::State& state) override { @@ -130,10 +128,13 @@ const auto kSEPBMMaxThreads = 2 * ProcessInfo::getNumLogicalCores(); /** * Required initializers, but this is a benchmark so nothing needs to be done. + * + * These should not be in a header file, but it works because it is only included in 2 files and + * they are never included into the same binary. If that changes, these should find a home in a new + * cpp file. */ -MONGO_INITIALIZER_GENERAL(ForkServer, ("EndStartupOptionHandling"), ("default")) +MONGO_INITIALIZER_GENERAL(ForkServer, ("EndStartupOptionHandling"), ("default")) // NOLINT (InitializerContext* context) {} -MONGO_INITIALIZER(ServerLogRedirection)(mongo::InitializerContext*) {} +MONGO_INITIALIZER(ServerLogRedirection)(mongo::InitializerContext*) {} // NOLINT -} // namespace } // namespace mongo diff --git a/src/mongo/db/service_entry_point_shard_role_helpers.h b/src/mongo/db/service_entry_point_shard_role_helpers.h index d5b480cd641..128d950c40b 100644 --- a/src/mongo/db/service_entry_point_shard_role_helpers.h +++ b/src/mongo/db/service_entry_point_shard_role_helpers.h @@ -93,7 +93,7 @@ namespace mongo { namespace service_entry_point_shard_role_helpers { -BSONObj getRedactedCopyForLogging(const Command* command, const BSONObj& cmdObj) { +inline BSONObj getRedactedCopyForLogging(const Command* command, const BSONObj& cmdObj) { mutablebson::Document cmdToLog(cmdObj, mutablebson::Document::kInPlaceDisabled); command->snipForLogging(&cmdToLog); BSONObjBuilder bob; @@ -101,12 +101,12 @@ BSONObj getRedactedCopyForLogging(const Command* command, const BSONObj& cmdObj) return bob.obj(); } -bool lockedForWriting() { +inline bool lockedForWriting() { return mongo::lockedForWriting(); } -void setPrepareConflictBehaviorForReadConcern(OperationContext* opCtx, - const CommandInvocation* invocation) { +inline void setPrepareConflictBehaviorForReadConcern(OperationContext* opCtx, + const CommandInvocation* invocation) { // Some read commands can safely ignore prepare conflicts by default because they do not // require snapshot isolation and do not conflict with concurrent writes. We also give these // operations permission to write, as this may be required for queries that spill using the @@ -119,9 +119,9 @@ void setPrepareConflictBehaviorForReadConcern(OperationContext* opCtx, opCtx, repl::ReadConcernArgs::get(opCtx), prepareConflictBehavior); } -void waitForReadConcern(OperationContext* opCtx, - const CommandInvocation* invocation, - const OpMsgRequest& request) { +inline void waitForReadConcern(OperationContext* opCtx, + const CommandInvocation* invocation, + const OpMsgRequest& request) { Status rcStatus = mongo::waitForReadConcern(opCtx, repl::ReadConcernArgs::get(opCtx), invocation->ns().dbName(), @@ -144,7 +144,7 @@ void waitForReadConcern(OperationContext* opCtx, } } -void waitForSpeculativeMajorityReadConcern(OperationContext* opCtx) { +inline void waitForSpeculativeMajorityReadConcern(OperationContext* opCtx) { auto speculativeReadInfo = repl::SpeculativeMajorityReadInfo::get(opCtx); if (!speculativeReadInfo.isSpeculativeRead()) { return; @@ -153,10 +153,10 @@ void waitForSpeculativeMajorityReadConcern(OperationContext* opCtx) { } -void waitForWriteConcern(OperationContext* opCtx, - const CommandInvocation* invocation, - const repl::OpTime& lastOpBeforeRun, - BSONObjBuilder& commandResponseBuilder) { +inline void waitForWriteConcern(OperationContext* opCtx, + const CommandInvocation* invocation, + const repl::OpTime& lastOpBeforeRun, + BSONObjBuilder& commandResponseBuilder) { // Prevent waiting for writeConcern if the command is changing only unreplicated namespaces. invariant(invocation); @@ -231,7 +231,7 @@ void waitForWriteConcern(OperationContext* opCtx, // operation then we skip waiting for writeConcern. } -void waitForLinearizableReadConcern(OperationContext* opCtx) { +inline void waitForLinearizableReadConcern(OperationContext* opCtx) { // When a linearizable read command is passed in, check to make sure we're reading from the // primary. if (repl::ReadConcernArgs::get(opCtx).getLevel() == @@ -240,19 +240,19 @@ void waitForLinearizableReadConcern(OperationContext* opCtx) { } } -void uassertCommandDoesNotSpecifyWriteConcern(const GenericArguments& requestArgs) { +inline void uassertCommandDoesNotSpecifyWriteConcern(const GenericArguments& requestArgs) { uassert(ErrorCodes::InvalidOptions, "Command does not support writeConcern", !commandSpecifiesWriteConcern(requestArgs)); } -void attachCurOpErrInfo(OperationContext* opCtx, const Status status) { +inline void attachCurOpErrInfo(OperationContext* opCtx, const Status status) { CurOp::get(opCtx)->debug().errInfo = std::move(status); } -void appendReplyMetadata(OperationContext* opCtx, - const GenericArguments& requestArgs, - BSONObjBuilder* metadataBob) { +inline void appendReplyMetadata(OperationContext* opCtx, + const GenericArguments& requestArgs, + BSONObjBuilder* metadataBob) { auto const replCoord = repl::ReplicationCoordinator::get(opCtx); const bool isReplSet = replCoord->getSettings().isReplSet(); @@ -289,26 +289,26 @@ void appendReplyMetadata(OperationContext* opCtx, } } -Status refreshDatabase(OperationContext* opCtx, const StaleDbRoutingVersion& se) noexcept { +inline Status refreshDatabase(OperationContext* opCtx, const StaleDbRoutingVersion& se) noexcept { return FilteringMetadataCache::get(opCtx)->onDbVersionMismatch( opCtx, se.getDb(), se.getVersionReceived()); } -Status refreshCollection(OperationContext* opCtx, const StaleConfigInfo& se) noexcept { +inline Status refreshCollection(OperationContext* opCtx, const StaleConfigInfo& se) noexcept { return FilteringMetadataCache::get(opCtx)->onCollectionPlacementVersionMismatch( opCtx, se.getNss(), se.getVersionReceived().placementVersion()); } -Status refreshCatalogCache(OperationContext* opCtx, - const ShardCannotRefreshDueToLocksHeldInfo& refreshInfo) noexcept { +inline Status refreshCatalogCache( + OperationContext* opCtx, const ShardCannotRefreshDueToLocksHeldInfo& refreshInfo) noexcept { return Grid::get(opCtx) ->catalogCache() ->getCollectionRoutingInfo(opCtx, refreshInfo.getNss()) .getStatus(); } -void handleReshardingCriticalSectionMetrics(OperationContext* opCtx, - const StaleConfigInfo& se) noexcept { +inline void handleReshardingCriticalSectionMetrics(OperationContext* opCtx, + const StaleConfigInfo& se) noexcept { resharding_metrics::onCriticalSectionError(opCtx, se); } @@ -317,16 +317,16 @@ void handleReshardingCriticalSectionMetrics(OperationContext* opCtx, // lock. This will cause mongod to perhaps erroneously check for write concern when no writes // were done, or unnecessarily kill a read operation. If we re-use the opCtx to retry command // execution, we must reset the locker state. -void resetLockerState(OperationContext* opCtx) noexcept { +inline void resetLockerState(OperationContext* opCtx) noexcept { // It is necessary to lock the client to change the Locker on the OperationContext. stdx::lock_guard lk(*opCtx->getClient()); invariant(!shard_role_details::getLocker(opCtx)->isLocked()); shard_role_details::swapLocker(opCtx, std::make_unique(opCtx->getServiceContext()), lk); } -void createTransactionCoordinator(OperationContext* opCtx, - TxnNumber clientTxnNumber, - boost::optional clientTxnRetryCounter) { +inline void createTransactionCoordinator(OperationContext* opCtx, + TxnNumber clientTxnNumber, + boost::optional clientTxnRetryCounter) { auto clientLsid = opCtx->getLogicalSessionId().value(); auto clockSource = opCtx->getServiceContext()->getFastClockSource(); diff --git a/src/mongo/db/vector_clock_mongod.h b/src/mongo/db/vector_clock_mongod.h index 61e1c563803..93aa7b5b6fa 100644 --- a/src/mongo/db/vector_clock_mongod.h +++ b/src/mongo/db/vector_clock_mongod.h @@ -43,7 +43,6 @@ namespace mongo { -namespace { class VectorClockMongoD : public VectorClockMutable, public ReplicaSetAwareService { @@ -146,5 +145,4 @@ private: WaitableAtomic _taskIsRunning{false}; }; -} // namespace } // namespace mongo diff --git a/src/mongo/executor/async_rpc.h b/src/mongo/executor/async_rpc.h index ebadcf350ac..62ac980cdb6 100644 --- a/src/mongo/executor/async_rpc.h +++ b/src/mongo/executor/async_rpc.h @@ -298,13 +298,11 @@ ExecutorFuture> sendCommandWithRun } } // namespace detail -namespace { -void createOperationKeyIfNeeded(GenericArguments& genericArgs) { +inline void createOperationKeyIfNeeded(GenericArguments& genericArgs) { if (!genericArgs.getClientOperationKey()) { genericArgs.setClientOperationKey(UUID::gen()); } } -} // namespace /** * Execute the command asynchronously on the given target with the provided executor. diff --git a/src/mongo/executor/mock_async_rpc.h b/src/mongo/executor/mock_async_rpc.h index 6d6a1322450..6ddde5f76ee 100644 --- a/src/mongo/executor/mock_async_rpc.h +++ b/src/mongo/executor/mock_async_rpc.h @@ -380,11 +380,11 @@ private: stdx::mutex _m; }; -std::ostream& operator<<(std::ostream& s, const AsyncMockAsyncRPCRunner::Request& o) { +inline std::ostream& operator<<(std::ostream& s, const AsyncMockAsyncRPCRunner::Request& o) { return s << o.toBSON(); } -std::ostream& operator<<(std::ostream& s, const AsyncMockAsyncRPCRunner::Expectation& o) { +inline std::ostream& operator<<(std::ostream& s, const AsyncMockAsyncRPCRunner::Expectation& o) { return s << o.name; } diff --git a/src/mongo/executor/task_executor_cursor_test_fixture.h b/src/mongo/executor/task_executor_cursor_test_fixture.h index 12d5ed05ba6..b3b10894d8e 100644 --- a/src/mongo/executor/task_executor_cursor_test_fixture.h +++ b/src/mongo/executor/task_executor_cursor_test_fixture.h @@ -56,8 +56,10 @@ */ namespace mongo { namespace executor { -namespace { -BSONObj buildCursorResponse(StringData fieldName, size_t start, size_t end, size_t cursorId) { +inline BSONObj buildCursorResponse(StringData fieldName, + size_t start, + size_t end, + size_t cursorId) { BSONObjBuilder bob; { BSONObjBuilder cursor(bob.subobjStart("cursor")); @@ -76,10 +78,10 @@ BSONObj buildCursorResponse(StringData fieldName, size_t start, size_t end, size return bob.obj(); } -BSONObj buildMultiCursorResponse(StringData fieldName, - size_t start, - size_t end, - std::vector cursorIds) { +inline BSONObj buildMultiCursorResponse(StringData fieldName, + size_t start, + size_t end, + std::vector cursorIds) { BSONObjBuilder bob; { BSONArrayBuilder cursors; @@ -103,7 +105,6 @@ BSONObj buildMultiCursorResponse(StringData fieldName, bob.append("ok", 1); return bob.obj(); } -} // namespace class NonPinningTaskExecutorCursorTestFixture : public ThreadPoolExecutorTest { public: diff --git a/src/mongo/s/async_rpc_shard_retry_policy.h b/src/mongo/s/async_rpc_shard_retry_policy.h index 4fca95f9d19..a34bfa8d59a 100644 --- a/src/mongo/s/async_rpc_shard_retry_policy.h +++ b/src/mongo/s/async_rpc_shard_retry_policy.h @@ -37,10 +37,8 @@ namespace mongo { namespace async_rpc { -namespace { // See ARS::kMaxNumFailedHostRetryAttempts and Shard::kOnErrorNumRetries -const int kOnErrorNumRetries = 3; -} // namespace +inline const int kOnErrorNumRetries = 3; class ShardRetryPolicy : public RetryPolicy { public: diff --git a/src/mongo/s/commands/cluster_abort_transaction_cmd.h b/src/mongo/s/commands/cluster_abort_transaction_cmd.h index 3c345b6a563..a785037fdf4 100644 --- a/src/mongo/s/commands/cluster_abort_transaction_cmd.h +++ b/src/mongo/s/commands/cluster_abort_transaction_cmd.h @@ -36,7 +36,6 @@ #include "mongo/s/transaction_router.h" namespace mongo { -namespace { /** * Implements the abortTransaction command for a router. @@ -136,5 +135,4 @@ public: } }; -} // namespace } // namespace mongo diff --git a/src/mongo/s/commands/cluster_commit_transaction_cmd.h b/src/mongo/s/commands/cluster_commit_transaction_cmd.h index 43cd6a1458b..1af6a01defc 100644 --- a/src/mongo/s/commands/cluster_commit_transaction_cmd.h +++ b/src/mongo/s/commands/cluster_commit_transaction_cmd.h @@ -35,7 +35,6 @@ #include "mongo/s/transaction_router.h" namespace mongo { -namespace { /** * Implements the commitTransaction command for a router. @@ -118,5 +117,4 @@ public: } }; -} // namespace } // namespace mongo diff --git a/src/mongo/s/commands/internal_transactions_test_command.h b/src/mongo/s/commands/internal_transactions_test_command.h index 9bed75e7c8d..a5d7d1339ef 100644 --- a/src/mongo/s/commands/internal_transactions_test_command.h +++ b/src/mongo/s/commands/internal_transactions_test_command.h @@ -39,8 +39,6 @@ namespace mongo { -namespace { - // TODO SERVER-86458 // RAII object that switches an OperationContext's service role to the router role if it isn't // already and if the OperationContext's ServiceContext has a router role Service, restoring the @@ -67,8 +65,6 @@ private: Service* _original; }; -} // namespace - template class InternalTransactionsTestCommandBase : public TypedCommand { public: diff --git a/src/mongo/s/commands/query_cmd/cluster_count_cmd.h b/src/mongo/s/commands/query_cmd/cluster_count_cmd.h index 28792004155..e1ffcdeb44b 100644 --- a/src/mongo/s/commands/query_cmd/cluster_count_cmd.h +++ b/src/mongo/s/commands/query_cmd/cluster_count_cmd.h @@ -57,12 +57,7 @@ namespace mongo { -namespace { - -// The # of documents returned is always 1 for the count command. -static constexpr long long kNReturned = 1; - -BSONObj prepareCountForPassthrough(const BSONObj& cmdObj, bool requestQueryStats) { +inline BSONObj prepareCountForPassthrough(const BSONObj& cmdObj, bool requestQueryStats) { if (!requestQueryStats) { return CommandHelpers::filterCommandRequestForPassthrough(cmdObj); } @@ -72,8 +67,6 @@ BSONObj prepareCountForPassthrough(const BSONObj& cmdObj, bool requestQueryStats return CommandHelpers::filterCommandRequestForPassthrough(bob.done()); } -} // namespace - /** * Implements the find command on mongos. */ @@ -283,6 +276,9 @@ public: total = applySkipLimit(total, cmdObj); result.appendNumber("n", total); + // The # of documents returned is always 1 for the count command. + static constexpr long long kNReturned = 1; + auto* curOp = CurOp::get(opCtx); curOp->setEndOfOpMetrics(kNReturned); diff --git a/src/mongo/s/commands/query_cmd/cluster_find_cmd.h b/src/mongo/s/commands/query_cmd/cluster_find_cmd.h index d033804aea9..f2f5e16941b 100644 --- a/src/mongo/s/commands/query_cmd/cluster_find_cmd.h +++ b/src/mongo/s/commands/query_cmd/cluster_find_cmd.h @@ -56,12 +56,11 @@ #include "mongo/s/query/planner/cluster_find.h" namespace mongo { -namespace { /** * Parses the command object to a FindCommandRequest and validates that no runtime * constants were supplied and that querySettings was not passed into the command. */ -std::unique_ptr parseCmdObjectToFindCommandRequest( +inline std::unique_ptr parseCmdObjectToFindCommandRequest( OperationContext* opCtx, const OpMsgRequest& request) { const auto& vts = auth::ValidatedTenancyScope::get(opCtx); auto findCommand = query_request_helper::makeFromFindCommand( @@ -85,7 +84,6 @@ std::unique_ptr parseCmdObjectToFindCommandRequest( return findCommand; } -} // namespace /** * Implements the find command for a router. diff --git a/src/mongo/s/commands/query_cmd/cluster_getmore_cmd.h b/src/mongo/s/commands/query_cmd/cluster_getmore_cmd.h index f05f698118b..0e72ab0559d 100644 --- a/src/mongo/s/commands/query_cmd/cluster_getmore_cmd.h +++ b/src/mongo/s/commands/query_cmd/cluster_getmore_cmd.h @@ -40,13 +40,12 @@ #include "mongo/s/query/planner/cluster_find.h" namespace mongo { -namespace { // getMore can run with any readConcern, because cursor-creating commands like find can run with any // readConcern. However, since getMore automatically uses the readConcern of the command that // created the cursor, it is not appropriate to apply the default readConcern (just as // client-specified readConcern isn't appropriate). -static const ReadConcernSupportResult kSupportsReadConcernResult{ +inline const ReadConcernSupportResult kSupportsReadConcernResult{ Status::OK(), {{ErrorCodes::InvalidOptions, "default read concern not permitted (getMore uses the cursor's read concern)"}}}; @@ -167,5 +166,5 @@ public: } }; -} // namespace + } // namespace mongo diff --git a/src/mongo/s/commands/query_cmd/cluster_pipeline_cmd.h b/src/mongo/s/commands/query_cmd/cluster_pipeline_cmd.h index 4a2bd913e4c..530d05e59da 100644 --- a/src/mongo/s/commands/query_cmd/cluster_pipeline_cmd.h +++ b/src/mongo/s/commands/query_cmd/cluster_pipeline_cmd.h @@ -39,7 +39,6 @@ #include "mongo/s/query/planner/cluster_aggregate.h" namespace mongo { -namespace { template class ClusterPipelineCommandBase final : public Command { @@ -223,5 +222,4 @@ public: } }; -} // namespace } // namespace mongo diff --git a/src/mongo/util/dns_query_posix-impl.h b/src/mongo/util/dns_query_posix-impl.h index 36be3b9dd8e..a2ea22d3b5c 100644 --- a/src/mongo/util/dns_query_posix-impl.h +++ b/src/mongo/util/dns_query_posix-impl.h @@ -61,7 +61,6 @@ namespace mongo { namespace dns { // The anonymous namespace is safe, in this header, as it is not really a header. It is only used // in the `dns_query.cpp` TU. -namespace { using std::begin; using std::end; @@ -377,8 +376,7 @@ private: static stdx::mutex _staticMutex; }; -stdx::mutex DNSQueryState::_staticMutex; +inline stdx::mutex DNSQueryState::_staticMutex; -} // namespace } // namespace dns } // namespace mongo