{"repo_name": "3FS", "file_name": "/3FS/src/meta/components/SessionManager.h", "inference_info": {"prefix_code": "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"client/mgmtd/IMgmtdClientForServer.h\"\n#include \"common/app/ClientId.h\"\n#include \"common/app/NodeId.h\"\n#include \"common/kv/IKVEngine.h\"\n#include \"common/kv/ITransaction.h\"\n#include \"common/kv/KeyPrefix.h\"\n#include \"common/serde/Serde.h\"\n#include \"common/utils/BackgroundRunner.h\"\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/CoroutinesPool.h\"\n#include \"common/utils/Duration.h\"\n#include \"common/utils/Result.h\"\n#include \"common/utils/String.h\"\n#include \"common/utils/UtcTime.h\"\n#include \"common/utils/Uuid.h\"\n#include \"fbs/meta/Common.h\"\n#include \"fbs/meta/Service.h\"\n#include \"meta/store/FileSession.h\"\n#include \"meta/store/Inode.h\"\n#include \"meta/store/Utils.h\"\n\nnamespace hf3fs::meta::server {\n\nclass FileHelper;\n\nclass SessionManager {\n public:\n class Config : public ConfigBase {\n CONFIG_HOT_UPDATED_ITEM(enable, true);\n CONFIG_HOT_UPDATED_ITEM(scan_interval, 5_min);\n CONFIG_HOT_UPDATED_ITEM(scan_batch, 1024u);\n CONFIG_HOT_UPDATED_ITEM(sync_on_prune_session, false);\n CONFIG_HOT_UPDATED_ITEM(session_timeout, 5_min);\n CONFIG_OBJ(scan_workers, CoroutinesPoolBase::Config, [](auto &c) {\n c.set_coroutines_num(8);\n c.set_queue_size(128);\n });\n CONFIG_OBJ(close_workers, CoroutinesPoolBase::Config, [](auto &c) {\n c.set_coroutines_num(32);\n c.set_queue_size(1024);\n });\n };\n\n SessionManager(const Config &cfg,\n flat::NodeId nodeId,\n std::shared_ptr kvEngine,\n std::shared_ptr mgmtd,\n std::shared_ptr fileHelper)\n : config_(cfg),\n nodeId_(nodeId),\n kvEngine_(kvEngine),\n mgmtd_(mgmtd),\n fileHelper_(fileHelper) {}\n ~SessionManager() { stopAndJoin(); }\n\n void start(CPUExecutorGroup &exec);\n void stopAndJoin();\n\n using CloseFunc = std::function(const meta::CloseReq &)>;\n void setCloseFunc(CloseFunc close) { close_ = close; }\n\n // for admin_cli\n CoTryTask> listSessions();\n CoTryTask> listSessions(InodeId inodeId);\n CoTryTask pruneManually();\n\n private:\n struct PruneSessions {\n std::atomic finished = 0;\n folly::Synchronized> sessions;\n };\n\n ", "suffix_code": ";\n\n // try to close and sync\n class CloseTask {\n public:\n CloseTask(FileSession session)\n : session_(std::move(session)) {}\n CoTryTask run(SessionManager &manager);\n\n private:\n FileSession session_;\n };\n\n CoTask scanTask();\n CoTryTask> loadPrune();\n\n const Config &config_;\n flat::NodeId nodeId_;\n std::shared_ptr kvEngine_;\n std::shared_ptr mgmtd_;\n std::shared_ptr fileHelper_;\n std::unique_ptr scanRunner_;\n std::unique_ptr>> scanWorkers_;\n std::unique_ptr>> closeWorkers_;\n CloseFunc close_;\n};\n\n} // namespace hf3fs::meta::server\n\nFMT_BEGIN_NAMESPACE\n\ntemplate <>\nstruct formatter : formatter {\n template \n auto format(const hf3fs::meta::server::FileSession &session, FormatContext &ctx) const {\n return fmt::format_to(ctx.out(),\n \"{{inodeId {}, client {}, session {}}}\",\n session.inodeId,\n session.clientId,\n session.sessionId);\n }\n};\n\nFMT_END_NAMESPACE", "middle_code": "class ScanTask {\n public:\n ScanTask(size_t shard, std::shared_ptr prune)\n : shard_(shard),\n prune_(prune) {}\n CoTryTask run(SessionManager &manager);\n private:\n size_t shard_ = -1;\n std::shared_ptr prune_;\n }", "code_description": null, "fill_type": "CLASS_TYPE", "language_type": "cpp", "sub_task_type": null}, "context_code": [["/3FS/src/client/meta/MetaClient.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"client/meta/ServerSelectionStrategy.h\"\n#include \"client/mgmtd/ICommonMgmtdClient.h\"\n#include \"client/storage/StorageClient.h\"\n#include \"common/app/ClientId.h\"\n#include \"common/app/NodeId.h\"\n#include \"common/serde/MessagePacket.h\"\n#include \"common/utils/BackgroundRunner.h\"\n#include \"common/utils/CPUExecutorGroup.h\"\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/CoroutinesPool.h\"\n#include \"common/utils/Duration.h\"\n#include \"common/utils/ExponentialBackoffRetry.h\"\n#include \"common/utils/Path.h\"\n#include \"common/utils/Result.h\"\n#include \"common/utils/Semaphore.h\"\n#include \"common/utils/StatusCode.h\"\n#include \"common/utils/UtcTime.h\"\n#include \"common/utils/Uuid.h\"\n#include \"fbs/meta/Common.h\"\n#include \"fbs/meta/Service.h\"\n#include \"stubs/MetaService/IMetaServiceStub.h\"\n#include \"stubs/MetaService/MetaServiceStub.h\"\n#include \"stubs/MetaService/MockMetaServiceStub.h\"\n#include \"stubs/common/StubFactory.h\"\n\nnamespace hf3fs::meta::client {\n\nusing SessionId = hf3fs::Uuid;\n\nusing hf3fs::client::ICommonMgmtdClient;\n\nclass MetaClient {\n public:\n using StubFactory = stubs::SerdeStubFactory;\n using Stub = StubFactory::Stub;\n\n class RetryConfig : public ConfigBase {\n CONFIG_HOT_UPDATED_ITEM(rpc_timeout, 5_s);\n CONFIG_HOT_UPDATED_ITEM(retry_send, 1u, ConfigCheckers::checkPositive);\n CONFIG_HOT_UPDATED_ITEM(retry_fast, 1_s);\n CONFIG_HOT_UPDATED_ITEM(retry_init_wait, 500_ms);\n CONFIG_HOT_UPDATED_ITEM(retry_max_wait, 5_s);\n CONFIG_HOT_UPDATED_ITEM(retry_total_time, 1_min);\n CONFIG_HOT_UPDATED_ITEM(max_failures_before_failover, 1u, ConfigCheckers::checkPositive);\n };\n\n class CloserConfig : public ConfigBase {\n CONFIG_HOT_UPDATED_ITEM(task_scan, 50_ms);\n CONFIG_HOT_UPDATED_ITEM(prune_session_batch_interval, 10_s);\n CONFIG_HOT_UPDATED_ITEM(prune_session_batch_count, 128);\n CONFIG_HOT_UPDATED_ITEM(retry_first_wait, 100_ms);\n CONFIG_HOT_UPDATED_ITEM(retry_max_wait, 10_s);\n CONFIG_OBJ(coroutine_pool, CoroutinesPoolBase::Config, [](CoroutinesPoolBase::Config &c) {\n c.set_coroutines_num(8);\n c.set_queue_size(128);\n });\n };\n\n struct Config : public ConfigBase {\n CONFIG_HOT_UPDATED_ITEM(selection_mode, ServerSelectionMode::RandomFollow);\n CONFIG_HOT_UPDATED_ITEM(network_type, net::Address::Type::RDMA);\n CONFIG_HOT_UPDATED_ITEM(check_server_interval, 5_s);\n CONFIG_HOT_UPDATED_ITEM(max_concurrent_requests, 128u, ConfigCheckers::checkPositive);\n CONFIG_HOT_UPDATED_ITEM(remove_chunks_batch_size, uint32_t(32), ConfigCheckers::checkPositive);\n CONFIG_HOT_UPDATED_ITEM(remove_chunks_max_iters, uint32_t(1024), ConfigCheckers::checkPositive); // deprecated\n\n CONFIG_HOT_UPDATED_ITEM(dynamic_stripe, false);\n\n CONFIG_OBJ(retry_default, RetryConfig);\n CONFIG_OBJ(background_closer, CloserConfig);\n };\n\n MetaClient(ClientId clientId,\n const Config &config,\n std::unique_ptr factory,\n std::shared_ptr mgmtd,\n std::shared_ptr storage,\n bool dynStripe);\n\n void start(CPUExecutorGroup &exec);\n void stop();\n\n CoTryTask authenticate(const UserInfo &userInfo);\n\n CoTryTask stat(const UserInfo &userInfo,\n InodeId inodeId,\n const std::optional &path,\n bool followLastSymlink);\n\n CoTryTask>> batchStat(const UserInfo &userInfo, std::vector inodeIds);\n\n CoTryTask>> batchStatByPath(const UserInfo &userInfo,\n std::vector paths,\n bool followLastSymlink);\n\n CoTryTask statFs(const UserInfo &userInfo);\n\n CoTryTask getRealPath(const UserInfo &userInfo, InodeId parent, const std::optional &path, bool absolute);\n\n CoTryTask open(const UserInfo &userInfo,\n InodeId inodeId,\n const std::optional &path,\n std::optional sessionId,\n int flags);\n\n CoTryTask close(const UserInfo &userInfo,\n InodeId inodeId,\n std::optional sessionId,\n bool read,\n bool written);\n CoTryTask close(const UserInfo &userInfo,\n InodeId inodeId,\n std::optional sessionId,\n bool updateLength,\n const std::optional atime,\n const std::optional mtime);\n\n CoTryTask setPermission(const UserInfo &userInfo,\n InodeId parent,\n const std::optional &path,\n bool followLastSymlink,\n std::optional uid,\n std::optional gid,\n std::optional perm,\n std::optional iflags = std::nullopt);\n\n CoTryTask setIFlags(const UserInfo &userInfo, InodeId inode, IFlags iflags);\n\n CoTryTask utimes(const UserInfo &userInfo,\n InodeId inodeId,\n const std::optional &path,\n bool followLastSymlink,\n std::optional atime,\n std::optional mtime);\n\n CoTryTask create(const UserInfo &userInfo,\n InodeId parent,\n const Path &path,\n std::optional sessionId,\n Permission perm,\n int flags,\n std::optional layout = std::nullopt);\n\n CoTryTask mkdirs(const UserInfo &userInfo,\n InodeId parent,\n const Path &path,\n Permission perm,\n bool recursive,\n std::optional layout = std::nullopt);\n\n CoTryTask symlink(const UserInfo &userInfo, InodeId parent, const Path &path, const Path &target);\n\n // remove without check inode type\n CoTryTask remove(const UserInfo &userInfo, InodeId parent, const std::optional &path, bool recursive);\n\n // only remove directory\n CoTryTask rmdir(const UserInfo &userInfo, InodeId parent, const std::optional &path, bool recursive);\n\n // unlink file\n CoTryTask unlink(const UserInfo &userInfo, InodeId parent, const Path &path);\n\n CoTryTask rename(const UserInfo &userInfo,\n InodeId srcParent,\n const Path &src,\n InodeId dstParent,\n const Path &dst,\n bool moveToTrash = false);\n\n CoTryTask list(const UserInfo &userInfo,\n InodeId inodeId,\n const std::optional &path,\n std::string_view prev,\n int32_t limit,\n bool needStatus);\n\n CoTryTask setLayout(const UserInfo &userInfo, InodeId inodeId, const std::optional &path, Layout layout);\n\n CoTryTask truncate(const UserInfo &userInfo, InodeId inodeId, uint64_t length);\n\n CoTryTask sync(const UserInfo &userInfo,\n InodeId inode,\n bool read,\n bool written,\n std::optional hint);\n CoTryTask sync(const UserInfo &userInfo,\n InodeId inode,\n bool updateLength,\n const std::optional atime,\n const std::optional mtime,\n std::optional hint);\n\n CoTryTask hardLink(const UserInfo &userInfo,\n InodeId oldParent,\n const std::optional &oldPath,\n InodeId newParent,\n const Path &newPath,\n bool followLastSymlink);\n\n CoTryTask lockDirectory(const UserInfo &userInfo, InodeId inode, LockDirectoryReq::LockAction action);\n\n CoTryTask extendStripe(const UserInfo &userInfo, InodeId inodeId, uint32_t stripe);\n\n CoTryTask testRpc();\n\n private:\n CoTryTask openCreate(auto func, auto req);\n\n CoTryTask removeImpl(RemoveReq &req);\n\n struct CloseTask {\n std::variant req;\n Duration backoff;\n\n std::string describe() const {\n return fmt::format(\"{{{}, backoff {}}}\",\n std::visit([](const auto &req) -> std::string { return fmt::format(\"{}\", req); }, req),\n backoff);\n }\n };\n\n class PrunSessionBatch {\n SteadyTime lastTime;\n std::vector sessions;\n\n public:\n std::vector take(size_t batchSize, Duration batchDur) {\n if (sessions.size() < batchSize && (sessions.empty() || SteadyClock::now() - lastTime < batchDur)) {\n return {};\n }\n return std::exchange(sessions, {});\n }\n\n std::vector push(SessionId session, size_t batchSize) {\n if (sessions.empty()) {\n lastTime = SteadyClock::now();\n sessions.reserve(batchSize);\n }\n sessions.push_back(session);\n\n if (sessions.size() >= batchSize) {\n return std::exchange(sessions, {});\n }\n return {};\n }\n };\n\n CoTryTask tryClose(const CloseReq &req, bool &needRetry);\n CoTryTask tryPrune(const PruneSessionReq &req, bool &needRetry);\n CoTryTask updateLayout(Layout &layout);\n\n CoTask pruneSession(SessionId session);\n void enqueueCloseTask(CloseTask task);\n CoTask scanCloseTask();\n CoTask runCloseTask(CloseTask task);\n\n folly::Synchronized batchPrune_;\n std::unique_ptr bgRunner_;\n std::unique_ptr> bgCloser_;\n folly::Synchronized, std::mutex> bgCloseTasks_;\n\n CoTryTask truncateImpl(const UserInfo &userInfo, const Inode &inode, size_t targetLength);\n\n private:\n struct ServerNode {\n ServerSelectionStrategy::NodeInfo node;\n StubFactory::Stub stub;\n size_t failure;\n\n ServerNode(ServerSelectionStrategy::NodeInfo node, StubFactory::Stub stub)\n : node(std::move(node)),\n stub(std::move(stub)),\n failure(0) {}\n };\n folly::Synchronized> errNodes_;\n CoTryTask getStub();\n CoTryTask getServerNode();\n CoTask checkServers();\n\n template \n auto retry(Func &&func, Req &&req)\n -> std::invoke_result_t {\n co_return co_await retry(func, req, config_.retry_default());\n }\n template \n auto retry(Func &&func, Req &&req, RetryConfig retryConfig, std::function onError = {})\n -> std::invoke_result_t;\n\n template \n CoTryTask waitRoutingInfo(const Rsp &rsp, const RetryConfig &retryConfig);\n\n private:\n [[maybe_unused]] ClientId clientId_;\n const Config &config_;\n const bool dynStripe_; // only fuse client support dynamic stripe.\n std::unique_ptr factory_;\n std::shared_ptr mgmtd_;\n std::shared_ptr storage_;\n\n private:\n folly::atomic_shared_ptr serverSelection_;\n std::unique_ptr onConfigUpdated_;\n Semaphore concurrentReqSemaphore_;\n};\n} // namespace hf3fs::meta::client\n"], ["/3FS/src/meta/components/GcManager.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"client/mgmtd/ICommonMgmtdClient.h\"\n#include \"client/mgmtd/MgmtdClient.h\"\n#include \"client/storage/StorageClient.h\"\n#include \"common/app/ApplicationBase.h\"\n#include \"common/app/NodeId.h\"\n#include \"common/kv/IKVEngine.h\"\n#include \"common/kv/ITransaction.h\"\n#include \"common/utils/BackgroundRunner.h\"\n#include \"common/utils/CPUExecutorGroup.h\"\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/CoroutinesPool.h\"\n#include \"common/utils/CountDownLatch.h\"\n#include \"common/utils/Duration.h\"\n#include \"common/utils/PriorityCoroutinePool.h\"\n#include \"common/utils/Result.h\"\n#include \"common/utils/Semaphore.h\"\n#include \"common/utils/UtcTime.h\"\n#include \"core/user/UserStoreEx.h\"\n#include \"fbs/core/user/User.h\"\n#include \"fbs/meta/Common.h\"\n#include \"fdb/FDBRetryStrategy.h\"\n#include \"fmt/core.h\"\n#include \"meta/base/Config.h\"\n#include \"meta/components/InodeIdAllocator.h\"\n#include \"meta/components/SessionManager.h\"\n#include \"meta/event/Event.h\"\n#include \"meta/store/DirEntry.h\"\n#include \"meta/store/FileSession.h\"\n#include \"scn/scan/scan.h\"\n\nnamespace hf3fs::meta::server {\n\nclass FileHelper;\nusing hf3fs::client::ICommonMgmtdClient;\n\nclass GcManager {\n public:\n static Result> parseGcEntry(std::string_view entry) {\n char prefix;\n uint64_t timestamp;\n uint64_t inode;\n auto ret = scn::scan(entry, \"{}-{}-{:i}\", prefix, timestamp, inode);\n if (!ret) {\n return makeError(StatusCode::kInvalidArg);\n }\n return std::pair{UtcTime::fromMicroseconds(timestamp), InodeId(inode)};\n }\n\n static std::string formatGcEntry(char prefix, UtcTime timestamp, InodeId inode) {\n return fmt::format(\"{}-{:020d}-{}\", prefix, (uint64_t)timestamp.toMicroseconds(), inode.toHexString());\n }\n\n GcManager(const Config &config,\n flat::NodeId nodeId,\n analytics::StructuredTraceLog &metaEventTraceLog,\n std::shared_ptr kvEngine,\n std::shared_ptr mgmtd,\n std::shared_ptr idAlloc,\n std::shared_ptr fileHelper,\n std::shared_ptr sessionManager,\n std::shared_ptr userStore)\n : config_(config),\n nodeId_(nodeId),\n metaEventTraceLog_(metaEventTraceLog),\n kvEngine_(kvEngine),\n mgmtd_(mgmtd),\n idAlloc_(idAlloc),\n fileHelper_(fileHelper),\n sessionManager_(sessionManager),\n userStore_(userStore),\n concurrentGcDirSemaphore_(config_.gc().gc_directory_concurrent()),\n concurrentGcFileSemaphore_(config_.gc().gc_file_concurrent()) {\n XLOGF_IF(FATAL, !nodeId_, \"invalid node id {}\", nodeId_);\n guard_ = config_.gc().addCallbackGuard([&]() {\n auto dirConcurrent = config_.gc().gc_directory_concurrent();\n if (dirConcurrent != 0 && dirConcurrent != concurrentGcDirSemaphore_.getUsableTokens()) {\n XLOGF(INFO, \"GcManager set gc directory concurrent to {}\", dirConcurrent);\n concurrentGcDirSemaphore_.changeUsableTokens(dirConcurrent);\n XLOGF(INFO, \"GcManager finished update gc directory concurrent\");\n }\n auto fileConcurrent = config_.gc().gc_file_concurrent();\n if (fileConcurrent != 0 && fileConcurrent != concurrentGcFileSemaphore_.getUsableTokens()) {\n XLOGF(INFO, \"GcManager set gc directory concurrent to {}\", fileConcurrent);\n concurrentGcFileSemaphore_.changeUsableTokens(fileConcurrent);\n XLOGF(INFO, \"GcManager finished update gc file concurrent\");\n }\n });\n }\n\n CoTryTask init();\n\n void start(CPUExecutorGroup &exec);\n void stopAndJoin();\n\n auto &getEventTraceLog() { return metaEventTraceLog_; }\n\n CoTryTask removeEntry(IReadWriteTransaction &txn, const DirEntry &entry, Inode &inode, GcInfo gcInfo);\n\n private:\n template \n FRIEND_TEST(TestRemove, GC);\n\n enum GcEntryType {\n DIRECTORY = 0,\n FILE_MEDIUM,\n FILE_LARGE,\n FILE_SMALL,\n MAX,\n };\n\n class GcDirectory;\n\n struct GcTask {\n std::shared_ptr gcDir;\n GcEntryType type;\n DirEntry taskEntry;\n\n GcTask(std::shared_ptr gcDir, GcEntryType type, DirEntry entry)\n : gcDir(std::move(gcDir)),\n type(type),\n taskEntry(std::move(entry)) {}\n\n static CoTryTask getUserAttr(GcManager &manager, flat::Uid uid);\n\n CoTryTask run(GcManager &manager);\n CoTryTask gcDirectory(GcManager &manager);\n CoTryTask gcFile(GcManager &manager);\n\n CoTryTask removeEntry(GcManager &manager,\n IReadWriteTransaction &txn,\n const DirEntry &entry,\n const flat::UserAttr &user);\n CoTryTask removeGcEntryAndInode(GcManager &manager, IReadWriteTransaction &txn);\n CoTryTask createOrphanEntry(GcManager &manager,\n IReadWriteTransaction &txn,\n const DirEntry &entry,\n const Inode &inode,\n const flat::UserAttr &user);\n };\n\n class GcDirectory : folly::MoveOnly, public std::enable_shared_from_this {\n public:\n using Ptr = std::shared_ptr;\n\n static char prefixOf(GcEntryType type) {\n switch (type) {\n case DIRECTORY:\n return 'd';\n case FILE_MEDIUM:\n return 'f';\n case FILE_LARGE:\n return 'L';\n case FILE_SMALL:\n return 'S';\n default:\n XLOGF(FATAL, \"invalid type {}\", (int)type);\n }\n }\n\n int8_t priorityOf(GcEntryType type) {\n switch (type) {\n case DIRECTORY:\n return folly::Executor::MID_PRI;\n case FILE_MEDIUM:\n return folly::Executor::MID_PRI;\n case FILE_LARGE:\n return folly::Executor::HI_PRI;\n case FILE_SMALL:\n return folly::Executor::LO_PRI;\n default:\n XLOGF(FATAL, \"invalid type {}\", (int)type);\n }\n }\n\n static std::string nameOf(flat::NodeId nodeId, size_t idx) {\n return idx == 0 ? fmt::format(\"GC-Node-{}\", (uint32_t)nodeId)\n : fmt::format(\"GC-Node-{}.{}\", (uint32_t)nodeId, idx);\n }\n\n GcDirectory(DirEntry entry)\n : entry_(std::move(entry)) {}\n ~GcDirectory() { stopAndJoin(); }\n\n void start(GcManager &manager, CPUExecutorGroup &exec);\n void stopAndJoin();\n\n auto dirId() const { return entry_.id; }\n std::string name() const { return entry_.name; }\n\n CoTryTask add(auto &txn, const Inode &inode, const GcConfig &config, GcInfo gcInfo);\n void finish(const GcTask &task);\n\n CoTryTask moveToTail(auto &txn, const GcTask &task, Duration delay);\n\n private:\n struct QueueState {\n folly::Synchronized, std::mutex> queued;\n folly::Synchronized, std::mutex> finished;\n std::atomic counter{0};\n };\n\n CoTask scan(GcManager &manager, GcEntryType type);\n CoTryTask scan(GcManager &manager,\n GcEntryType type,\n Duration delay,\n size_t limit,\n std::optional &prev);\n CoTryTask addFile(auto &txn, const Inode &inode, const GcConfig &config);\n CoTryTask addDirectory(auto &txn, const Inode &inode, GcInfo gcInfo);\n\n DirEntry entry_; // entry points to this GcDirectory\n std::array states_;\n CancellationSource cancel_;\n CountDownLatch<> latch_;\n };\n\n const std::vector &currGcDirectories() const { return currGcDirectories_; }\n\n GcDirectory::Ptr pickGcDirectory() {\n XLOGF_IF(FATAL, currGcDirectories_.empty(), \"currGcDirectories_.empty()\");\n if (config_.gc().distributed_gc()) {\n auto guard = allGcDirectories_.rlock();\n if (!guard->empty()) {\n return guard->at(folly::Random::rand64(guard->size()));\n }\n }\n if (currGcDirectories_.size() == 1) {\n return currGcDirectories_[0];\n } else {\n return currGcDirectories_[folly::Random::rand32(1, currGcDirectories_.size())];\n }\n }\n\n bool enableGcDelay() const;\n\n CoTryTask checkFs();\n CoTryTask> openGcDirectory(size_t idx, bool create);\n CoTryTask scanAllGcDirectories();\n\n CoTask runGcTask(GcTask task);\n\n template \n std::invoke_result_t runReadOnly(H &&handler) {\n auto retry = kv::FDBRetryStrategy({1_s, 10, true});\n co_return co_await kv::WithTransaction(retry).run(kvEngine_->createReadonlyTransaction(), std::forward(handler));\n }\n\n template \n std::invoke_result_t runReadWrite(H &&handler) {\n auto retry = kv::FDBRetryStrategy({1_s, 10, true});\n co_return co_await kv::WithTransaction(retry).run(kvEngine_->createReadWriteTransaction(),\n std::forward(handler));\n }\n\n const Config &config_;\n std::unique_ptr guard_;\n flat::NodeId nodeId_;\n analytics::StructuredTraceLog &metaEventTraceLog_;\n std::shared_ptr kvEngine_;\n std::shared_ptr mgmtd_;\n std::shared_ptr idAlloc_;\n std::shared_ptr fileHelper_;\n std::shared_ptr sessionManager_;\n std::shared_ptr userStore_;\n\n std::vector currGcDirectories_;\n folly::Synchronized> allGcDirectories_;\n\n std::unique_ptr gcRunner_;\n std::unique_ptr> gcWorkers_;\n Semaphore concurrentGcDirSemaphore_;\n Semaphore concurrentGcFileSemaphore_;\n};\n\n} // namespace hf3fs::meta::server\n"], ["/3FS/src/meta/service/MetaOperator.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"client/mgmtd/ICommonMgmtdClient.h\"\n#include \"client/mgmtd/IMgmtdClientForServer.h\"\n#include \"client/storage/StorageClient.h\"\n#include \"common/kv/IKVEngine.h\"\n#include \"common/kv/ITransaction.h\"\n#include \"common/kv/WithTransaction.h\"\n#include \"common/utils/BackgroundRunner.h\"\n#include \"common/utils/CPUExecutorGroup.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/CoroutinesPool.h\"\n#include \"common/utils/Result.h\"\n#include \"core/user/UserStoreEx.h\"\n#include \"fbs/meta/Common.h\"\n#include \"fbs/meta/Service.h\"\n#include \"fdb/FDBRetryStrategy.h\"\n#include \"meta/base/Config.h\"\n#include \"meta/components/ChainAllocator.h\"\n#include \"meta/components/Distributor.h\"\n#include \"meta/components/FileHelper.h\"\n#include \"meta/components/Forward.h\"\n#include \"meta/components/GcManager.h\"\n#include \"meta/components/SessionManager.h\"\n#include \"meta/store/Inode.h\"\n#include \"meta/store/MetaStore.h\"\n#include \"meta/store/ops/BatchOperation.h\"\n\nnamespace hf3fs::meta::server {\n\nclass BatchedOp;\n\nclass MetaOperator : public folly::NonCopyableNonMovable {\n public:\n MetaOperator(const Config &cfg,\n flat::NodeId nodeId,\n std::shared_ptr kvEngine,\n std::shared_ptr mgmtdClient,\n std::shared_ptr storageClient,\n std::unique_ptr forward);\n\n CoTryTask init(std::optional rootLayout);\n\n void start(CPUExecutorGroup &exec);\n void beforeStop();\n void afterStop();\n\n CoTryTask authenticate(AuthReq req);\n\n CoTryTask statFs(StatFsReq req);\n\n CoTryTask stat(StatReq req);\n\n CoTryTask getRealPath(GetRealPathReq req);\n\n CoTryTask open(OpenReq req);\n\n CoTryTask close(CloseReq req);\n\n CoTryTask create(CreateReq req);\n\n CoTryTask mkdirs(MkdirsReq req);\n\n CoTryTask symlink(SymlinkReq req);\n\n CoTryTask remove(RemoveReq req);\n\n CoTryTask rename(RenameReq req);\n\n CoTryTask list(ListReq req);\n\n CoTryTask truncate(TruncateReq req);\n\n CoTryTask sync(SyncReq req);\n\n CoTryTask hardLink(HardLinkReq req);\n\n CoTryTask setAttr(SetAttrReq req);\n\n CoTryTask pruneSession(PruneSessionReq req);\n\n CoTryTask dropUserCache(DropUserCacheReq req);\n\n CoTryTask lockDirectory(LockDirectoryReq req);\n\n CoTryTask testRpc(TestRpcReq req);\n\n CoTryTask batchStat(BatchStatReq req);\n\n CoTryTask batchStatByPath(BatchStatByPathReq req);\n\n private:\n friend class MockMeta;\n\n template \n FRIEND_TEST(TestBatchOp, batch);\n\n template \n FRIEND_TEST(TestCreate, batch);\n\n class Batch {\n public:\n void setNext(BatchedOp *op, folly::coro::Baton *baton) {\n next = op;\n nextBaton = baton;\n }\n\n bool wakeupNext() {\n if (!next) {\n return false;\n }\n nextBaton->post();\n next = nullptr;\n nextBaton = nullptr;\n return true;\n }\n\n BatchedOp *getNext() const { return next; }\n\n private:\n BatchedOp *next = nullptr;\n folly::coro::Baton *nextBaton = nullptr;\n };\n\n kv::FDBRetryStrategy::Config createRetryConfig() const;\n kv::FDBRetryStrategy createRetryStrategy() const { return kv::FDBRetryStrategy(createRetryConfig()); }\n\n template \n auto runOp(Func &&func, Arg &&arg)\n -> CoTryTask::element_type::RspT>;\n\n template \n std::unique_ptr addBatchReq(InodeId inodeId, BatchedOp::Waiter &waiter) {\n auto func = [&](auto &map) {\n auto [iter, inserted] = map.try_emplace(inodeId);\n auto &batch = iter->second;\n if (inserted) {\n assert(!batch.getNext());\n auto op = std::make_unique(*metaStore_, inodeId);\n op->add(waiter);\n waiter.baton.post();\n return op;\n } else if (!batch.getNext()) {\n auto op = std::make_unique(*metaStore_, inodeId);\n op->add(waiter);\n batch.setNext(op.get(), &waiter.baton);\n return op;\n } else {\n auto next = batch.getNext();\n auto num_reqs = next->numReqs();\n if (UNLIKELY(config_.max_batch_operations() != 0 && num_reqs >= config_.max_batch_operations())) {\n auto msg = fmt::format(\"too many batch operations on {}\", inodeId);\n XLOG(WARN, msg);\n waiter.result = makeError(MetaCode::kBusy, std::move(msg));\n waiter.baton.post();\n } else {\n if (num_reqs && num_reqs % 1024 == 0) {\n XLOGF(WARN, \"{} batch operations on {}\", num_reqs, inodeId);\n }\n next->add(waiter);\n }\n return std::unique_ptr();\n }\n };\n return batches_.withLock(func, inodeId);\n }\n\n CoTryTask runBatch(InodeId inodeId,\n std::unique_ptr op,\n std::optional deadline = std::nullopt);\n\n template \n CoTryTask runInBatch(InodeId inodeId, Req req);\n\n CoTryTask authenticate(UserInfo &userInfo);\n\n const Config &config_;\n flat::NodeId nodeId_;\n analytics::StructuredTraceLog metaEventTraceLog_;\n std::shared_ptr kvEngine_;\n std::shared_ptr mgmtd_;\n std::shared_ptr distributor_;\n std::shared_ptr userStore_;\n std::shared_ptr inodeIdAlloc_;\n std::shared_ptr chainAlloc_;\n std::shared_ptr fileHelper_;\n std::shared_ptr sessionManager_;\n std::shared_ptr gcManager_;\n std::unique_ptr forward_;\n\n std::unique_ptr metaStore_;\n\n Shards, 63> batches_;\n\n std::atomic_bool stop_{false};\n std::unique_ptr bgRunner_;\n};\n} // namespace hf3fs::meta::server\n"], ["/3FS/src/meta/components/Distributor.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/app/NodeId.h\"\n#include \"common/kv/IKVEngine.h\"\n#include \"common/kv/ITransaction.h\"\n#include \"common/kv/KeyPrefix.h\"\n#include \"common/serde/Serde.h\"\n#include \"common/utils/BackgroundRunner.h\"\n#include \"common/utils/CPUExecutorGroup.h\"\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/UtcTime.h\"\n#include \"fbs/meta/Common.h\"\n#include \"meta/store/Inode.h\"\n\nnamespace hf3fs::meta::server {\n\nclass Distributor {\n public:\n struct Config : ConfigBase {\n CONFIG_HOT_UPDATED_ITEM(update_interval, 1_s);\n CONFIG_HOT_UPDATED_ITEM(timeout, 30_s);\n };\n\n Distributor(const Config &config, flat::NodeId nodeId, std::shared_ptr kvEngine)\n : config_(config),\n nodeId_(nodeId),\n kvEngine_(kvEngine) {\n XLOGF_IF(FATAL, !nodeId_, \"invalid node id {}\", nodeId_);\n }\n\n ~Distributor() { stopAndJoin(); }\n\n flat::NodeId nodeId() const { return nodeId_; }\n\n void start(CPUExecutorGroup &exec);\n void stopAndJoin(bool updateMap = true);\n\n flat::NodeId getServer(InodeId inodeId);\n\n CoTryTask> checkOnServer(kv::IReadWriteTransaction &txn, InodeId inodeId);\n CoTryTask> checkOnServer(kv::IReadWriteTransaction &txn,\n InodeId inodeId,\n flat::NodeId nodeId);\n\n private:\n static constexpr auto kPrefix = kv::toStr(kv::KeyPrefix::MetaDistributor);\n static constexpr auto kMapKey = kPrefix;\n\n struct ServerMap {\n SERDE_STRUCT_FIELD(active, std::vector());\n };\n\n struct LatestServerMap : ServerMap {\n kv::Versionstamp versionstamp{0};\n };\n\n struct ServerStatus {\n std::string versionstamp;\n SteadyTime lastUpdate;\n };\n\n struct PerServerKey {\n static std::string pack(flat::NodeId nodeId);\n static flat::NodeId unpack(std::string_view key);\n };\n\n CoTryTask loadVersion(kv::IReadOnlyTransaction &txn);\n CoTryTask loadServerMap(kv::IReadOnlyTransaction &txn, bool update);\n\n CoTryTask updateVersion(kv::IReadWriteTransaction &txn);\n CoTryTask updateServerMap(kv::IReadWriteTransaction &txn, const ServerMap &map);\n\n CoTryTask update(bool exit);\n CoTryTask update(kv::IReadWriteTransaction &txn, bool exit);\n\n const Config config_;\n flat::NodeId nodeId_;\n std::atomic updated_{0};\n std::shared_ptr kvEngine_;\n std::unique_ptr bgRunner_;\n\n folly::Synchronized latest_;\n folly::Synchronized> servers_;\n};\n\n} // namespace hf3fs::meta::server"], ["/3FS/src/meta/store/MetaStore.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"client/mgmtd/ICommonMgmtdClient.h\"\n#include \"client/storage/StorageClient.h\"\n#include \"common/kv/IKVEngine.h\"\n#include \"common/kv/ITransaction.h\"\n#include \"common/kv/WithTransaction.h\"\n#include \"common/monitor/Recorder.h\"\n#include \"common/monitor/Sample.h\"\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/Path.h\"\n#include \"common/utils/Result.h\"\n#include \"common/utils/Status.h\"\n#include \"common/utils/UtcTime.h\"\n#include \"fbs/meta/Service.h\"\n#include \"meta/base/Config.h\"\n#include \"meta/components/AclCache.h\"\n#include \"meta/components/ChainAllocator.h\"\n#include \"meta/components/FileHelper.h\"\n#include \"meta/components/GcManager.h\"\n#include \"meta/components/InodeIdAllocator.h\"\n#include \"meta/components/SessionManager.h\"\n#include \"meta/store/DirEntry.h\"\n#include \"meta/store/Inode.h\"\n#include \"meta/store/PathResolve.h\"\n#include \"meta/store/Utils.h\"\n\nnamespace hf3fs::meta::server {\nusing hf3fs::kv::IReadOnlyTransaction;\nusing hf3fs::kv::IReadWriteTransaction;\n\ntemplate \nclass IOperation {\n public:\n using RspT = Rsp;\n\n virtual ~IOperation() = default;\n\n virtual bool isReadOnly() = 0;\n virtual bool retryMaybeCommitted() { return true; }\n\n virtual bool needIdempotent(Uuid &clientId, Uuid &requestId) const {\n boost::ignore_unused(clientId, requestId);\n return false;\n }\n\n virtual std::string_view name() const { return \"other\"; }\n virtual flat::Uid user() const { return flat::Uid(-1); }\n\n virtual CoTryTask run(IReadWriteTransaction &) = 0;\n\n virtual void retry(const Status &) = 0;\n virtual void finish(const Result &) = 0;\n\n CoTryTask operator()(IReadWriteTransaction &txn) { co_return co_await run(txn); }\n};\n\nclass MetaStore {\n public:\n MetaStore(const Config &config,\n analytics::StructuredTraceLog &metaEventTraceLog,\n std::shared_ptr distributor,\n std::shared_ptr inodeAlloc,\n std::shared_ptr chainAlloc,\n std::shared_ptr fileHelper,\n std::shared_ptr sessionManager,\n std::shared_ptr gcManager)\n : config_(config),\n metaEventTraceLog_(metaEventTraceLog),\n distributor_(distributor),\n inodeAlloc_(inodeAlloc),\n chainAlloc_(chainAlloc),\n fileHelper_(fileHelper),\n sessionManager_(sessionManager),\n gcManager_(gcManager),\n aclCache_(2 << 20 /* 2m acl */) {}\n\n auto &getEventTraceLog() { return metaEventTraceLog_; }\n\n template \n using Op = IOperation;\n\n template \n using OpPtr = std::unique_ptr>;\n\n static OpPtr initFileSystem(ChainAllocator &chainAlloc, Layout rootLayout);\n\n OpPtr initFs(Layout rootLayout) { return MetaStore::initFileSystem(*chainAlloc_, rootLayout); }\n\n OpPtr statFs(const StatFsReq &req);\n\n OpPtr stat(const StatReq &req);\n\n OpPtr batchStat(const BatchStatReq &req);\n\n OpPtr batchStatByPath(const BatchStatByPathReq &req);\n\n OpPtr getRealPath(const GetRealPathReq &req);\n\n OpPtr open(OpenReq &req);\n\n OpPtr tryOpen(CreateReq &req);\n\n OpPtr mkdirs(const MkdirsReq &req);\n\n OpPtr symlink(const SymlinkReq &req);\n\n OpPtr remove(const RemoveReq &req);\n\n OpPtr rename(const RenameReq &req);\n\n OpPtr list(const ListReq &req);\n\n OpPtr sync(const SyncReq &req);\n\n OpPtr hardLink(const HardLinkReq &req);\n\n OpPtr setAttr(const SetAttrReq &req);\n\n OpPtr pruneSession(const PruneSessionReq &req);\n\n OpPtr testRpc(const TestRpcReq &req);\n\n OpPtr lockDirectory(const LockDirectoryReq &req);\n\n private:\n template \n FRIEND_TEST(TestRemove, GC);\n\n template \n friend class Operation;\n\n const Config &config_;\n analytics::StructuredTraceLog &metaEventTraceLog_;\n std::shared_ptr distributor_;\n std::shared_ptr inodeAlloc_;\n std::shared_ptr chainAlloc_;\n std::shared_ptr fileHelper_;\n std::shared_ptr sessionManager_;\n std::shared_ptr gcManager_;\n AclCache aclCache_;\n};\n\n} // namespace hf3fs::meta::server\n"], ["/3FS/src/meta/service/MockMeta.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"client/mgmtd/ICommonMgmtdClient.h\"\n#include \"client/storage/StorageClient.h\"\n#include \"common/app/NodeId.h\"\n#include \"common/kv/IKVEngine.h\"\n#include \"common/kv/mem/MemKVEngine.h\"\n#include \"common/serde/ClientMockContext.h\"\n#include \"common/utils/CPUExecutorGroup.h\"\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"meta/components/ChainAllocator.h\"\n#include \"meta/components/FileHelper.h\"\n#include \"meta/components/GcManager.h\"\n#include \"meta/service/MetaOperator.h\"\n#include \"meta/service/MetaSerdeService.h\"\n#include \"meta/store/MetaStore.h\"\n\nnamespace hf3fs::meta::server {\n\nclass MockMeta : folly::NonCopyableNonMovable {\n public:\n static CoTryTask> create(const Config &cfg,\n std::shared_ptr kv,\n std::shared_ptr mgmtdClient) {\n auto meta = std::unique_ptr(new MockMeta(cfg, kv, mgmtdClient));\n for (auto &moperator : meta->operators_) {\n CO_RETURN_ON_ERROR(co_await moperator->init(Layout::newEmpty(ChainTableId(1), 512 << 10, 128)));\n }\n co_return meta;\n }\n\n ~MockMeta() { stop(); }\n\n void start(CPUExecutorGroup &exec) {\n for (auto &moperator : operators_) {\n moperator->start(exec);\n }\n }\n\n void stop() {\n for (auto &moperator : operators_) {\n moperator->beforeStop();\n moperator->afterStop();\n }\n }\n\n std::unique_ptr getService() { return std::make_unique(*operators_.at(0)); }\n\n MetaOperator &getOperator() { return *operators_.at(0); }\n\n MetaStore &getStore() { return dynamic_cast(*getOperator().metaStore_); }\n\n storage::client::StorageClient &getStorageClient() { return *storageClient_; }\n\n FileHelper &getFileHelper() { return *getOperator().fileHelper_; }\n\n GcManager &getGcManager() { return *getOperator().gcManager_; }\n\n SessionManager &getSessionManager() { return *getOperator().sessionManager_; }\n\n private:\n MockMeta(const Config &cfg,\n std::shared_ptr kv,\n std::shared_ptr mgmtdClient)\n : cfg_(cfg),\n mgmtdClient_(mgmtdClient) {\n storageClientCfg_.set_implementation_type(storage::client::StorageClient::ImplementationType::InMem);\n storageClient_ = storage::client::StorageClient::create(ClientId::random(), storageClientCfg_, *mgmtdClient_);\n\n auto routing = mgmtdClient->getRoutingInfo();\n XLOGF_IF(FATAL, !routing, \"routing info not available\");\n auto nodes = routing->getNodeBy(flat::selectNodeByType(flat::NodeType::META) && flat::selectActiveNode());\n XLOGF_IF(FATAL, nodes.empty(), \"no active metas\");\n for (auto &node : nodes) {\n XLOGF_IF(FATAL, contexts_.contains(node.app.nodeId), \"duplicated {}\", node.app.nodeId);\n auto moperator = std::make_unique(\n cfg,\n node.app.nodeId,\n kv,\n mgmtdClient_,\n storageClient_,\n std::make_unique(cfg.forward(), node.app.nodeId, contexts_, mgmtdClient_));\n contexts_[node.app.nodeId] = serde::ClientMockContext::create(std::make_unique(*moperator));\n operators_.push_back(std::move(moperator));\n }\n }\n\n [[maybe_unused]] const Config &cfg_;\n storage::client::StorageClient::Config storageClientCfg_;\n std::vector> operators_;\n std::map contexts_;\n std::shared_ptr mgmtdClient_;\n std::shared_ptr storageClient_;\n};\n\n} // namespace hf3fs::meta::server\n"], ["/3FS/src/meta/store/FileSession.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/app/ClientId.h\"\n#include \"common/kv/ITransaction.h\"\n#include \"common/serde/Serde.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/Result.h\"\n#include \"common/utils/UtcTime.h\"\n#include \"common/utils/Uuid.h\"\n#include \"fbs/meta/Common.h\"\n#include \"fbs/meta/Schema.h\"\n\nnamespace hf3fs::meta::server {\n\nusing kv::IReadOnlyTransaction;\nusing kv::IReadWriteTransaction;\n\nstruct FileSession {\n SERDE_STRUCT_FIELD(inodeId, InodeId());\n SERDE_STRUCT_FIELD(clientId, ClientId::zero());\n SERDE_STRUCT_FIELD(sessionId, Uuid::zero());\n SERDE_STRUCT_FIELD(timestamp, UtcTime());\n SERDE_STRUCT_FIELD(payload, std::string()); // for placeholder\n\n public:\n static std::string prefix(InodeId inodeId);\n static std::string packKey(InodeId inodeId, Uuid session);\n static Result> unpackByInodeKey(std::string_view key);\n\n static FileSession create(InodeId inodeId, SessionInfo session, UtcTime timestamp = UtcClock::now()) {\n return {inodeId, session.client, session.session, timestamp};\n }\n static FileSession create(InodeId inodeId, ClientId clientId, Uuid sessionId, UtcTime timestamp = UtcClock::now()) {\n return {inodeId, clientId, sessionId, timestamp};\n }\n\n static Result unpack(std::string_view key, std::string_view value);\n\n static CoTryTask> load(IReadOnlyTransaction &txn, InodeId inodeId, Uuid session);\n static CoTryTask> list(IReadOnlyTransaction &txn,\n InodeId inodeId,\n bool snapshot,\n size_t limit = 0);\n\n static CoTryTask> snapshotCheckExists(IReadOnlyTransaction &txn, const InodeId inodeId);\n static CoTryTask> checkExists(IReadWriteTransaction &txn, const InodeId inodeId);\n static CoTryTask removeAll(IReadWriteTransaction &txn, InodeId inodeId);\n\n static constexpr size_t kShard = 256;\n static_assert(kShard == (1 << 8));\n static CoTryTask> scan(IReadOnlyTransaction &txn,\n size_t shard,\n std::optional prev);\n\n CoTryTask store(IReadWriteTransaction &txn) const;\n CoTryTask remove(IReadWriteTransaction &txn) const;\n\n // prune, store FileSessions need to be pruned under special InodeId(-1)\n static FileSession createPrune(ClientId clientId, Uuid sessionId) {\n return FileSession::create(InodeId(-1), clientId, sessionId);\n }\n\n static CoTryTask> listPrune(IReadOnlyTransaction &txn, size_t limit) {\n co_return co_await FileSession::list(txn, InodeId(-1), true, limit);\n }\n\n // static CoTryTask> load(IReadOnlyTransaction &txn, ClientId clientId, Uuid session);\n // static CoTryTask> list(IReadOnlyTransaction &txn, Uuid clientId, bool snapshot);\n // static std::string prefix(Uuid clientId);\n // static std::string packKey(Uuid clientId, Uuid session);\n // static Result> unpackByClientKey(std::string_view key);\n};\n\n} // namespace hf3fs::meta::server"], ["/3FS/src/meta/components/FileHelper.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"client/mgmtd/ICommonMgmtdClient.h\"\n#include \"client/storage/StorageClient.h\"\n#include \"common/utils/BackgroundRunner.h\"\n#include \"common/utils/CPUExecutorGroup.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/Duration.h\"\n#include \"common/utils/UtcTime.h\"\n#include \"fbs/meta/Common.h\"\n#include \"fbs/meta/Service.h\"\n#include \"meta/base/Config.h\"\n#include \"meta/store/Inode.h\"\n\nnamespace hf3fs::meta::server {\n\nusing FsStatus = StatFsRsp;\n\nclass FileHelper {\n public:\n using RetryOptions = storage::client::RetryOptions;\n\n FileHelper(const Config &config,\n std::shared_ptr mgmtdClient,\n std::shared_ptr storageClient)\n : config_(config),\n mgmtdClient_(std::move(mgmtdClient)),\n storageClient_(std::move(storageClient)) {}\n\n ~FileHelper() { stopAndJoin(); }\n\n void start(CPUExecutorGroup &exec);\n void stopAndJoin();\n\n CoTryTask queryLength(const UserInfo &userInfo, const Inode &inode, bool *hasHole = nullptr);\n\n CoTryTask remove(const UserInfo &userInfo,\n const Inode &inode,\n RetryOptions retry,\n uint32_t removeChunksBatchSize);\n\n CoTryTask statFs(const UserInfo &userInfo, std::chrono::milliseconds cacheDuration);\n\n std::optional cachedFsStatus() const { return cachedFsStatus_.rlock()->status_; }\n\n private:\n CoTryTask updateStatFs();\n\n const Config &config_;\n std::shared_ptr mgmtdClient_;\n std::shared_ptr storageClient_;\n\n struct CachedFsStatus {\n RelativeTime update_;\n std::optional status_;\n };\n\n std::unique_ptr bgRunner_;\n folly::Synchronized cachedFsStatus_;\n};\n\n} // namespace hf3fs::meta::server\n"], ["/3FS/src/meta/event/Scan.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/kv/IKVEngine.h\"\n#include \"common/kv/ITransaction.h\"\n#include \"common/kv/KeyPrefix.h\"\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/Duration.h\"\n#include \"common/utils/Result.h\"\n#include \"meta/store/DirEntry.h\"\n#include \"meta/store/Inode.h\"\n\nnamespace hf3fs::meta::server {\n\nclass MetaScan {\n public:\n struct Options {\n // scan options\n int threads = 4;\n int coroutines = 8;\n int items_per_getrange = -1;\n double backoff_min_wait = 0.1; // 100ms\n double backoff_max_wait = 5; // 5s\n double backoff_total_wait = 60; // 60s\n // log level\n std::string logging;\n // create FDB client with given config path\n std::string fdb_cluster_file;\n };\n\n MetaScan(Options options,\n std::shared_ptr kvEngine = {} /* create new fdb client if kvEngine is not set */);\n ~MetaScan();\n\n std::vector getInodes();\n std::vector getDirEntries();\n\n kv::IKVEngine &kvEngine() { return *kvEngine_; }\n\n private:\n struct KeyRange {\n std::string begin;\n std::string end;\n bool hasMore;\n\n KeyRange()\n : begin(),\n end(),\n hasMore(false) {}\n KeyRange(std::string begin, std::string end)\n : begin(std::move(begin)),\n end(std::move(end)),\n hasMore(true) {}\n\n static std::vector split(std::string prefix);\n\n CoTryTask snapshotGetRange(kv::IReadOnlyTransaction &txn, int32_t limit);\n\n std::string describe() const {\n return fmt::format(\"[begin {:02x}, end {:02x}, hasMore {}]\", fmt::join(begin, \"\"), fmt::join(end, \"\"), hasMore);\n }\n };\n\n template \n struct BackgroundTask {\n folly::coro::BoundedQueue> queue;\n folly::SemiFuture> future;\n folly::CancellationSource cancel;\n\n BackgroundTask(size_t cap)\n : queue(cap),\n future(folly::SemiFuture>::makeEmpty()),\n cancel() {}\n };\n\n void createKVEngine();\n\n template \n std::vector waitResult(std::optional> &task);\n\n CoTryTask scanInode(BackgroundTask &task);\n CoTryTask scanDirEntry(BackgroundTask &task);\n\n template \n CoTryTask scan(kv::KeyPrefix prefix, BackgroundTask &task);\n\n template \n CoTryTask scanRange(KeyRange range, BackgroundTask &task);\n\n std::mutex mutex_;\n Options options_;\n std::optional fdbNetwork_;\n std::shared_ptr kvEngine_;\n folly::CPUThreadPoolExecutor exec_;\n std::optional> scanInodeTask_;\n std::optional> scanDirEntryTask_;\n};\n\n} // namespace hf3fs::meta::server"], ["/3FS/src/fuse/FuseClients.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/utils/BackgroundRunner.h\"\n#include \"common/utils/CoroutinesPool.h\"\n#include \"common/utils/Result.h\"\n#include \"common/utils/Semaphore.h\"\n#include \"common/utils/UtcTime.h\"\n#include \"fbs/core/user/User.h\"\n#include \"fbs/meta/Common.h\"\n#define FUSE_USE_VERSION 312\n#define OP_LOG_LEVEL DBG\n\n#include \n#include \n\n#include \"FuseConfig.h\"\n#include \"IoRing.h\"\n#include \"IovTable.h\"\n#include \"PioV.h\"\n#include \"UserConfig.h\"\n#include \"client/meta/MetaClient.h\"\n#include \"client/mgmtd/MgmtdClientForClient.h\"\n#include \"client/storage/StorageClient.h\"\n#include \"fbs/meta/Schema.h\"\n\nnamespace hf3fs::fuse {\nusing flat::Gid;\nusing flat::Uid;\nusing flat::UserInfo;\nusing lib::agent::PioV;\nusing meta::Acl;\nusing meta::Directory;\nusing meta::DirEntry;\nusing meta::Inode;\nusing meta::InodeData;\nusing meta::InodeId;\nusing meta::Permission;\nusing storage::client::IOBuffer;\n\nstruct InodeWriteBuf {\n std::vector buf;\n std::unique_ptr memh;\n off_t off{0};\n size_t len{0};\n};\n\nstruct RcInode {\n struct DynamicAttr {\n uint64_t written = 0;\n uint64_t synced = 0; // period sync\n uint64_t fsynced = 0; // fsync, close, truncate, etc...\n flat::Uid writer = flat::Uid(0);\n\n uint32_t dynStripe = 1; // dynamic stripe\n\n uint64_t truncateVer = 0; // largest known truncate version.\n std::optional hintLength; // local hint length\n std::optional atime; // local read time, but only update for write open\n std::optional mtime; // local write time\n\n void update(const Inode &inode, uint64_t syncver = 0, bool fsync = false) {\n if (!inode.isFile()) {\n return;\n }\n\n synced = std::max(synced, syncver);\n if (written == synced) {\n // clear local hint, since not write happens after sync\n hintLength = meta::VersionedLength{0, 0};\n }\n if (fsync) {\n fsynced = std::max(fsynced, syncver);\n }\n truncateVer = std::max(truncateVer, inode.asFile().truncateVer);\n dynStripe = inode.asFile().dynStripe;\n }\n };\n\n Inode inode;\n int refcount;\n std::atomic opened;\n\n std::mutex wbMtx;\n std::shared_ptr writeBuf;\n\n folly::Synchronized dynamicAttr;\n folly::coro::Mutex extendStripeLock;\n\n RcInode(Inode inode, int refcount = 1)\n : inode(inode),\n refcount(refcount),\n extendStripeLock() {\n if (inode.isFile()) {\n auto guard = dynamicAttr.wlock();\n guard->truncateVer = inode.asFile().truncateVer;\n guard->hintLength = meta::VersionedLength{0, guard->truncateVer};\n guard->dynStripe = inode.asFile().dynStripe;\n }\n }\n\n uint64_t getTruncateVer() const { return dynamicAttr.rlock()->truncateVer; }\n\n void update(const Inode &inode, uint64_t syncver = 0, bool fsync = false) {\n if (!inode.isFile()) {\n return;\n } else {\n auto guard = dynamicAttr.wlock();\n return guard->update(inode, syncver, fsync);\n }\n }\n\n // clear hint length, force calculate length on next sync\n void clearHintLength() {\n auto guard = dynamicAttr.wlock();\n guard->hintLength = std::nullopt;\n }\n\n CoTryTask beginWrite(flat::UserInfo userInfo,\n meta::client::MetaClient &meta,\n uint64_t offset,\n uint64_t length);\n\n void finishWrite(flat::UserInfo userInfo, uint64_t truncateVer, uint64_t offset, ssize_t ret);\n};\n\nstruct FileHandle {\n std::shared_ptr rcinode;\n bool oDirect;\n Uuid sessionId;\n\n /* FileHandle(std::shared_ptr rcinode, bool oDirect, Uuid sessionId) */\n /* : rcinode(rcinode), */\n /* sessionId(sessionId) {} */\n};\n\nstruct DirHandle {\n size_t dirId;\n pid_t pid;\n bool iovDir;\n};\n\nstruct DirEntryVector {\n std::shared_ptr> dirEntries;\n\n DirEntryVector(std::shared_ptr> &&dirEntries)\n : dirEntries(std::move(dirEntries)) {}\n};\n\nstruct DirEntryInodeVector {\n std::shared_ptr> dirEntries;\n std::shared_ptr>> inodes;\n\n DirEntryInodeVector(std::shared_ptr> dirEntries,\n std::shared_ptr>> inodes)\n : dirEntries(std::move(dirEntries)),\n inodes(std::move(inodes)) {}\n};\n\nstruct FuseClients {\n FuseClients() = default;\n ~FuseClients();\n\n Result init(const flat::AppInfo &appInfo,\n const String &mountPoint,\n const String &tokenFile,\n FuseConfig &fuseConfig);\n void stop();\n\n CoTask ioRingWorker(int i, int ths);\n void watch(int prio, std::stop_token stop);\n\n CoTask periodicSyncScan();\n CoTask periodicSync(InodeId inodeId);\n\n std::unique_ptr client;\n std::shared_ptr mgmtdClient;\n std::shared_ptr storageClient;\n std::shared_ptr metaClient;\n\n std::string fuseToken;\n std::string fuseMount;\n Path fuseMountpoint;\n std::optional fuseRemountPref;\n std::atomic memsetBeforeRead = false;\n int maxIdleThreads = 0;\n int maxThreads = 0;\n bool enableWritebackCache = false;\n\n std::unique_ptr onFuseConfigUpdated;\n\n std::unordered_map> inodes = {\n {InodeId::root(), std::make_shared(Inode{}, 2)}};\n std::mutex inodesMutex;\n\n std::unordered_map readdirplusResults;\n std::mutex readdirplusResultsMutex;\n\n std::atomic_uint64_t dirHandle{0};\n\n std::shared_ptr bufPool;\n int maxBufsize = 0;\n\n fuse_session *se = nullptr;\n\n std::atomic jitter;\n\n IovTable iovs;\n IoRingTable iors;\n std::vector>> iojqs; // job queues\n std::vector ioWatches;\n folly::CancellationSource cancelIos;\n\n UserConfig userConfig;\n\n folly::Synchronized, std::mutex> dirtyInodes;\n std::atomic lastSynced;\n std::unique_ptr periodicSyncRunner;\n std::unique_ptr> periodicSyncWorker;\n\n std::unique_ptr notifyInvalExec;\n const FuseConfig *config;\n};\n} // namespace hf3fs::fuse\n"], ["/3FS/src/meta/components/Forward.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"client/mgmtd/ICommonMgmtdClient.h\"\n#include \"client/mgmtd/MgmtdClientForServer.h\"\n#include \"common/app/NodeId.h\"\n#include \"common/net/Client.h\"\n#include \"common/net/RequestOptions.h\"\n#include \"common/serde/CallContext.h\"\n#include \"common/serde/ClientContext.h\"\n#include \"common/serde/ClientMockContext.h\"\n#include \"common/serde/MessagePacket.h\"\n#include \"common/utils/Address.h\"\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/Result.h\"\n#include \"common/utils/StatusCode.h\"\n#include \"fbs/meta/Common.h\"\n#include \"fbs/meta/Service.h\"\n#include \"fbs/meta/Utils.h\"\n#include \"fmt/core.h\"\n#include \"meta/store/Inode.h\"\n\nnamespace hf3fs::meta::server {\n\nclass Forward {\n public:\n struct Config : ConfigBase {\n CONFIG_HOT_UPDATED_ITEM(debug, true);\n CONFIG_HOT_UPDATED_ITEM(addr_type, net::Address::Type::RDMA);\n CONFIG_HOT_UPDATED_ITEM(timeout, 10_s);\n };\n\n using NetClient = std::reference_wrapper;\n using MockClient = std::reference_wrapper>;\n\n Forward(const Config &config,\n flat::NodeId nodeId,\n std::variant client,\n std::shared_ptr<::hf3fs::client::ICommonMgmtdClient> mgmtdClient)\n : config_(config),\n nodeId_(nodeId),\n client_(client),\n mgmtdClient_(mgmtdClient) {\n XLOGF_IF(FATAL, !nodeId_, \"invalid nodeId {}\", nodeId_);\n }\n\n template \n CoTryTask forward(flat::NodeId node, Req req) {\n OperationRecorder::Guard record(OperationRecorder::server(), \"forward\", req.user.uid);\n auto result = co_await forwardImpl(node, std::move(req));\n record.finish(result);\n co_return result;\n }\n\n private:\n template \n struct ForwardMethod {};\n\n template \n struct ForwardMethod {\n static constexpr auto rpcMethod = MetaSerde<>::sync;\n };\n\n template \n struct ForwardMethod {\n static constexpr auto rpcMethod = MetaSerde<>::close;\n };\n\n template \n struct ForwardMethod {\n static constexpr auto rpcMethod = MetaSerde<>::setAttr;\n };\n\n template \n struct ForwardMethod {\n static constexpr auto rpcMethod = MetaSerde<>::create;\n };\n\n template \n Result check(flat::NodeId node, Req &req) {\n if (!node) {\n XLOGF(WARN, \"request {}, unknown corresponding server, need retry\", req);\n return makeError(MetaCode::kForwardFailed, \"unknown corresponding server\");\n }\n if (req.forward) {\n XLOGF_IF(INFO, config_.debug(), \"request is forward from {}, can't forward again, req {}.\", req.forward, req);\n return makeError(MetaCode::kForwardFailed, \"double forward, retry\");\n }\n req.forward = nodeId_;\n\n XLOGF_IF(INFO, config_.debug(), \"forward req {} to {}\", req, node);\n XLOGF_IF(DBG, !config_.debug(), \"forward req {} to {}\", req, node);\n XLOGF_IF(FATAL, nodeId_ == node, \"forward to self, {} == {}\", nodeId_, node);\n\n return Void{};\n }\n\n CoTryTask getAddress(flat::NodeId node) {\n auto routing = mgmtdClient_->getRoutingInfo();\n if (!routing) {\n co_return makeError(MetaCode::kForwardFailed, \"routing info not ready, need retry\");\n }\n\n auto *nodeInfo = routing->raw()->getNode(node);\n if (!nodeInfo) {\n auto msg = fmt::format(\"req forward: routing info doesn't contains node {}\", node);\n XLOG(WARN, msg);\n co_return makeError(MetaCode::kForwardFailed, std::move(msg));\n }\n auto addrs = nodeInfo->extractAddresses(\"MetaSerde\", config_.addr_type());\n if (addrs.empty()) {\n auto msg =\n fmt::format(\"req forward: node {} doesn't have {} addr.\", node, magic_enum::enum_name(config_.addr_type()));\n XLOG(WARN, msg);\n co_return makeError(MetaCode::kForwardFailed, std::move(msg));\n }\n co_return addrs.front();\n }\n\n template \n CoTryTask forwardImpl(flat::NodeId node, Req req) {\n CO_RETURN_ON_ERROR(check(node, req));\n\n auto opts = net::UserRequestOptions();\n opts.timeout = config_.timeout();\n opts.sendRetryTimes = 3;\n opts.compression = std::nullopt;\n\n Result result = makeError(MetaCode::kFoundBug);\n if (std::holds_alternative(client_)) {\n auto &client = std::get(client_);\n auto addr = co_await getAddress(node);\n CO_RETURN_ON_ERROR(addr);\n auto ctx = client.get().serdeCtx(*addr);\n result = co_await ForwardMethod::rpcMethod(ctx, req, &opts, nullptr);\n } else {\n auto &client = std::get(client_);\n if (!client.get().contains(node)) {\n co_return makeError(MetaCode::kForwardFailed, fmt::format(\"{} not found\", node));\n }\n auto &ctx = client.get()[node];\n result = co_await ForwardMethod::rpcMethod(ctx, req, &opts, nullptr);\n }\n\n if (result.hasError() && StatusCode::typeOf(result.error().code()) == StatusCodeType::RPC) {\n XLOGF(ERR, \"failed to forward req to {}, error {}\", node, result.error());\n co_return makeError(MetaCode::kForwardTimeout,\n fmt::format(\"failed to forward req to {}, error {}\", node, result.error()));\n }\n\n if (result.hasError()) {\n XLOGF_IF(INFO, config_.debug(), \"forward req {} to {}, rsp {}\", req, node, result.error());\n } else {\n XLOGF_IF(INFO, config_.debug(), \"forward req {} to {}, rsp {}\", req, node, result.value());\n }\n\n co_return result;\n }\n\n const Config &config_;\n flat::NodeId nodeId_;\n std::variant client_;\n std::shared_ptr<::hf3fs::client::ICommonMgmtdClient> mgmtdClient_;\n};\n\n} // namespace hf3fs::meta::server"], ["/3FS/src/common/net/ib/IBDevice.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/net/EventLoop.h\"\n#include \"common/net/IfAddrs.h\"\n#include \"common/utils/Address.h\"\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/Duration.h\"\n#include \"common/utils/MagicEnum.hpp\"\n#include \"common/utils/Result.h\"\n#include \"common/utils/StrongType.h\"\n\nnamespace hf3fs::net {\n\nclass TestIBNotInitialized;\nclass TestIBDevice;\n\nclass IBConfig : public ConfigBase {\n public:\n static constexpr std::string_view kUnknownZone = \"UNKNOWN\";\n class Network : public folly::CIDRNetworkV4 {\n public:\n static Result from(std::string_view str);\n Network(folly::CIDRNetworkV4 network)\n : folly::CIDRNetworkV4(network) {}\n folly::IPAddressV4 ip() const { return first; }\n uint8_t mask() const { return second; }\n std::string toString() const { return fmt::format(\"{}/{}\", ip().str(), mask()); }\n };\n\n class Subnet : public ConfigBase {\n CONFIG_ITEM(subnet, Network({}));\n CONFIG_ITEM(network_zones, std::vector{std::string(kUnknownZone)}, [](auto &v) { return !v.empty(); });\n };\n\n CONFIG_ITEM(allow_no_usable_devices, false);\n CONFIG_ITEM(skip_inactive_ports, true);\n CONFIG_ITEM(skip_unusable_device, true);\n\n CONFIG_ITEM(allow_unknown_zone, true);\n CONFIG_ITEM(device_filter, std::vector());\n CONFIG_ITEM(default_network_zone, std::string(kUnknownZone), [](auto &v) { return !v.empty(); });\n CONFIG_ITEM(subnets, std::vector());\n CONFIG_ITEM(fork_safe, true);\n CONFIG_ITEM(default_pkey_index, uint16_t(0));\n CONFIG_ITEM(default_roce_pkey_index, uint16_t(0)); // for RoCE, should just use default value 0\n // CONFIG_ITEM(default_gid_index, uint8_t(0)); // for RoCE\n CONFIG_ITEM(default_traffic_class, uint8_t(0)); // for RoCE\n CONFIG_ITEM(prefer_ibdevice, true); // prefer use ibdevice instead of RoCE device.\n};\n\nclass IBPort;\nclass IBManager;\n\nclass IBDevice : public std::enable_shared_from_this {\n public:\n using Ptr = std::shared_ptr;\n using Config = IBConfig;\n using IB2NetMap = std::map, std::string>;\n\n struct Port {\n std::vector addrs;\n std::set zones;\n mutable folly::Synchronized attr;\n };\n\n struct Deleter {\n void operator()(ibv_pd *pd) const {\n auto ret = ibv_dealloc_pd(pd);\n XLOGF_IF(CRITICAL, ret != 0, \"ibv_dealloc_pd failed {}\", ret);\n }\n void operator()(ibv_context *context) const {\n auto ret = ibv_close_device(context);\n XLOGF_IF(CRITICAL, ret != 0, \"ibv_close_device failed {}\", ret);\n }\n void operator()(ibv_cq *cq) const {\n auto ret = ibv_destroy_cq(cq);\n XLOGF_IF(CRITICAL, ret != 0, \"ibv_destroy_cq failed {}\", ret);\n }\n void operator()(ibv_qp *qp) const {\n auto ret = ibv_destroy_qp(qp);\n XLOGF_IF(CRITICAL, ret != 0, \"ibv_destroy_qp failed {}\", ret);\n }\n void operator()(ibv_comp_channel *channel) const {\n auto ret = ibv_destroy_comp_channel(channel);\n XLOGF_IF(CRITICAL, ret != 0, \"ibv_destroy_comp_channel failed {}\", ret);\n }\n };\n\n static constexpr size_t kMaxDeviceCnt = 4;\n static const std::vector &all();\n static IBDevice::Ptr get(uint8_t devId) {\n if (all().size() < devId) {\n return nullptr;\n }\n return all().at(devId);\n }\n\n uint8_t id() const { return devId_; }\n const std::string &name() const { return name_; }\n const ibv_device_attr &attr() const { return attr_; }\n ibv_context *context() const { return context_.get(); }\n ibv_pd *pd() const { return pd_.get(); }\n const std::map &ports() const { return ports_; }\n Result openPort(size_t portNum) const;\n\n ibv_mr *regMemory(void *addr, size_t length, int access) const;\n int deregMemory(ibv_mr *mr) const;\n\n private:\n friend class IBManager;\n class BackgroundRunner;\n class AsyncEventHandler;\n\n static Result> openAll(const IBConfig &config);\n static Result open(ibv_device *dev,\n uint8_t devId,\n std::map, std::string> ib2net,\n std::multimap ifaddrs,\n const IBConfig &config);\n\n FRIEND_TEST(TestIBDevice, IBConfig);\n static std::vector getIBPortAddrs(const IB2NetMap &ibdev2netdev,\n const IfAddrs::Map &ifaddrs,\n const std::string &devName,\n uint8_t portNum);\n static std::set getZonesByAddrs(std::vector addrs,\n const IBConfig &config,\n const std::string &devName,\n uint8_t portNum);\n\n void checkAsyncEvent() const;\n Result updatePort(size_t portNum) const;\n\n uint8_t devId_ = 0;\n std::string name_;\n std::unique_ptr context_;\n std::unique_ptr pd_;\n ibv_device_attr attr_;\n std::map ports_;\n};\n\nclass IBPort {\n public:\n IBPort(std::shared_ptr dev = {},\n uint8_t portNum = 0,\n ibv_port_attr attr = {},\n std::optional> rocev2Gid = {});\n\n uint8_t portNum() const { return portNum_; }\n const IBDevice *dev() const { return dev_.get(); }\n const ibv_port_attr attr() const { return attr_; }\n const std::vector &addrs() const { return dev_->ports().at(portNum_).addrs; }\n const std::set &zones() const { return dev_->ports().at(portNum_).zones; }\n\n bool isRoCE() const { return attr().link_layer == IBV_LINK_LAYER_ETHERNET; }\n bool isInfiniband() const { return attr().link_layer == IBV_LINK_LAYER_INFINIBAND; }\n bool isActive() const { return attr().state == IBV_PORT_ACTIVE || attr().state == IBV_PORT_ACTIVE_DEFER; }\n Result queryGid(uint8_t index) const;\n std::pair getRoCEv2Gid() const {\n XLOGF_IF(FATAL, !isRoCE(), \"port is not RoCE\");\n return *rocev2Gid_;\n }\n\n operator bool() const { return dev_ && portNum_ != 0; }\n\n private:\n std::shared_ptr dev_;\n uint8_t portNum_;\n ibv_port_attr attr_;\n std::optional> rocev2Gid_;\n};\n\nclass IBSocket;\nclass IBSocketManager;\n\nclass IBManager {\n public:\n static IBManager &instance() {\n static IBManager instance;\n return instance;\n }\n static Result start(IBConfig config) { return instance().startImpl(config); }\n static void stop() { return instance().reset(); }\n static void close(std::unique_ptr socket);\n static bool initialized() { return instance().inited_; }\n\n ~IBManager();\n\n const std::vector &allDevices() const { return devices_; }\n const std::multimap> zone2port() const { return zone2port_; }\n const auto &config() const { return config_; }\n\n private:\n IBManager();\n\n void reset();\n\n Result startImpl(IBConfig config);\n void stopImpl() { return reset(); }\n void closeImpl(std::unique_ptr socket);\n\n friend class IBSocketManager;\n\n IBConfig config_;\n std::atomic inited_ = false;\n std::vector devices_;\n std::multimap> zone2port_;\n std::shared_ptr eventLoop_;\n std::shared_ptr socketManager_;\n std::shared_ptr devBgRunner_;\n std::vector> devEventHandlers_;\n};\n} // namespace hf3fs::net\n\nFMT_BEGIN_NAMESPACE\n\ninline std::string_view ibvLinklayerName(int linklayer) {\n switch (linklayer) {\n case IBV_LINK_LAYER_INFINIBAND:\n return \"INFINIBAND\";\n case IBV_LINK_LAYER_ETHERNET:\n return \"ETHERNET\";\n default:\n return \"UNSPECIFIED\";\n }\n}\n\ninline std::string_view ibvPortStateName(ibv_port_state state) {\n switch (state) {\n case IBV_PORT_NOP:\n return \"NOP\";\n case IBV_PORT_DOWN:\n return \"DOWN\";\n case IBV_PORT_INIT:\n return \"INIT\";\n case IBV_PORT_ARMED:\n return \"ARMED\";\n case IBV_PORT_ACTIVE:\n return \"ACTIVE\";\n case IBV_PORT_ACTIVE_DEFER:\n return \"ACTIVE_DEFER\";\n default:\n return \"UNKNOWN\";\n }\n}\n\ntemplate <>\nstruct formatter : formatter {\n template \n auto format(const ibv_gid &gid, FormatContext &ctx) const {\n std::string str = fmt::format(\"{:x}\", fmt::join(&gid.raw[0], &gid.raw[sizeof(gid.raw)], \":\"));\n return formatter::format(str, ctx);\n }\n};\n\ntemplate <>\nstruct formatter : formatter {\n template \n auto format(const ibv_port_attr &attr, FormatContext &ctx) const {\n std::string str = fmt::format(\"{{linklayer: {}, state: {}, lid: {}, mtu: {}}}\",\n ibvLinklayerName(attr.link_layer),\n ibvPortStateName(attr.state),\n attr.lid,\n magic_enum::enum_name(attr.active_mtu));\n return formatter::format(str, ctx);\n }\n};\n\ntemplate <>\nstruct formatter : formatter {\n template \n auto format(const hf3fs::net::IBPort &port, FormatContext &ctx) const {\n return fmt::format_to(ctx.out(),\n \"{{{}:{}, ifaddrs [{}], zones [{}], {}, {}}}\",\n port.dev()->name(),\n port.portNum(),\n fmt::join(port.addrs().begin(), port.addrs().end(), \";\"),\n fmt::join(port.zones().begin(), port.zones().end(), \";\"),\n ibvLinklayerName(port.attr().link_layer),\n ibvPortStateName(port.attr().state));\n }\n};\n\ntemplate <>\nstruct formatter : formatter {\n template \n auto format(const hf3fs::net::IBDevice::Config::Network &network, FormatContext &ctx) const {\n return fmt::format_to(ctx.out(), \"{}/{}\", network.ip().str(), network.mask());\n }\n};\n\nFMT_END_NAMESPACE"], ["/3FS/src/client/mgmtd/MgmtdClient.h", "#pragma once\n\n#include \"IMgmtdClientForClient.h\"\n#include \"IMgmtdClientForServer.h\"\n#include \"RoutingInfo.h\"\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/Duration.h\"\n#include \"stubs/common/IStubFactory.h\"\n#include \"stubs/mgmtd/IMgmtdServiceStub.h\"\n\nnamespace hf3fs::client {\nclass MgmtdClient {\n public:\n struct Config : public ConfigBase {\n CONFIG_ITEM(mgmtd_server_addresses, std::vector{});\n CONFIG_ITEM(work_queue_size, 100, ConfigCheckers::checkPositive);\n CONFIG_ITEM(network_type, std::optional{});\n\n CONFIG_HOT_UPDATED_ITEM(enable_auto_refresh, true);\n CONFIG_HOT_UPDATED_ITEM(auto_refresh_interval, 10_s);\n CONFIG_HOT_UPDATED_ITEM(enable_auto_heartbeat, true);\n CONFIG_HOT_UPDATED_ITEM(auto_heartbeat_interval, 10_s);\n CONFIG_HOT_UPDATED_ITEM(enable_auto_extend_client_session, true);\n CONFIG_HOT_UPDATED_ITEM(auto_extend_client_session_interval, 10_s);\n CONFIG_HOT_UPDATED_ITEM(accept_incomplete_routing_info_during_mgmtd_bootstrapping, true);\n };\n\n using MgmtdStub = mgmtd::IMgmtdServiceStub;\n using MgmtdStubFactory = stubs::IStubFactory;\n using RoutingInfoListener = ICommonMgmtdClient::RoutingInfoListener;\n using ConfigListener = IMgmtdClientForServer::ConfigListener;\n using HeartbeatPayload = IMgmtdClientForServer::HeartbeatPayload;\n using ClientSessionPayload = IMgmtdClientForClient::ClientSessionPayload;\n\n MgmtdClient(String clusterId, std::unique_ptr stubFactory, const Config &config);\n ~MgmtdClient();\n\n // backgroundExecutor == nullptr means using the current executor\n CoTask start(folly::Executor *backgroundExecutor = nullptr, bool startBackground = true);\n\n CoTask startBackgroundTasks();\n\n CoTask stop();\n\n std::shared_ptr getRoutingInfo();\n\n CoTryTask refreshRoutingInfo(bool force);\n\n CoTryTask heartbeat();\n\n Result triggerHeartbeat();\n\n void setAppInfoForHeartbeat(flat::AppInfo info);\n\n bool addRoutingInfoListener(String name, RoutingInfoListener listener);\n\n bool removeRoutingInfoListener(std::string_view name);\n\n void setServerConfigListener(ConfigListener listener);\n\n void setClientConfigListener(ConfigListener listener);\n\n void updateHeartbeatPayload(HeartbeatPayload payload);\n\n CoTryTask setChains(const flat::UserInfo &userInfo,\n const std::vector &chains);\n\n CoTryTask setChainTable(const flat::UserInfo &userInfo,\n flat::ChainTableId tableId,\n const std::vector &chains,\n const String &desc);\n\n void setClientSessionPayload(ClientSessionPayload payload);\n\n CoTryTask extendClientSession();\n\n CoTryTask listClientSessions();\n\n CoTryTask setConfig(const flat::UserInfo &userInfo,\n flat::NodeType nodeType,\n const String &content,\n const String &desc);\n\n CoTryTask> getConfig(flat::NodeType nodeType, flat::ConfigVersion version);\n\n CoTryTask> getConfigVersions();\n\n CoTryTask enableNode(const flat::UserInfo &userInfo, flat::NodeId nodeId);\n\n CoTryTask disableNode(const flat::UserInfo &userInfo, flat::NodeId nodeId);\n\n CoTryTask registerNode(const flat::UserInfo &userInfo, flat::NodeId nodeId, flat::NodeType type);\n\n CoTryTask unregisterNode(const flat::UserInfo &userInfo, flat::NodeId nodeId);\n\n CoTryTask setNodeTags(const flat::UserInfo &userInfo,\n flat::NodeId nodeId,\n const std::vector &tags,\n flat::SetTagMode mode);\n\n CoTryTask> setUniversalTags(const flat::UserInfo &userInfo,\n const String &universalId,\n const std::vector &tags,\n flat::SetTagMode mode);\n\n CoTryTask> getUniversalTags(const String &universalId);\n\n CoTryTask getClientSession(const String &clientId);\n\n CoTryTask rotateLastSrv(const flat::UserInfo &userInfo, flat::ChainId chainId);\n\n CoTryTask rotateAsPreferredOrder(const flat::UserInfo &userInfo, flat::ChainId chainId);\n\n CoTryTask setPreferredTargetOrder(const flat::UserInfo &userInfo,\n flat::ChainId chainId,\n const std::vector &preferredTargetOrder);\n\n CoTryTask listOrphanTargets();\n\n CoTryTask updateChain(const flat::UserInfo &userInfo,\n flat::ChainId cid,\n flat::TargetId tid,\n mgmtd::UpdateChainReq::Mode mode);\n\n struct Impl;\n\n private:\n std::unique_ptr impl_;\n};\n} // namespace hf3fs::client\n"], ["/3FS/src/common/net/ib/IBSocket.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/monitor/Sample.h\"\n#include \"common/net/EventLoop.h\"\n#include \"common/net/Network.h\"\n#include \"common/net/Socket.h\"\n#include \"common/net/WriteItem.h\"\n#include \"common/net/ib/IBConnect.h\"\n#include \"common/net/ib/IBDevice.h\"\n#include \"common/net/ib/RDMABuf.h\"\n#include \"common/utils/Address.h\"\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/Duration.h\"\n#include \"common/utils/FdWrapper.h\"\n#include \"common/utils/Result.h\"\n#include \"common/utils/StatusCode.h\"\n#include \"common/utils/UtcTime.h\"\n\nnamespace hf3fs {\n\nnamespace serde {\nclass ClientContext;\n};\n\nnamespace net {\nclass IBConnectService;\nclass IBSocketManager;\n\nclass IBSocket : public Socket, folly::MoveOnly {\n public:\n struct Config : public ConfigBase {\n // for recorder\n CONFIG_HOT_UPDATED_ITEM(record_bytes_per_peer, false);\n CONFIG_HOT_UPDATED_ITEM(record_latency_per_peer, false);\n\n // connection param\n CONFIG_HOT_UPDATED_ITEM(pkey_index, std::optional());\n CONFIG_HOT_UPDATED_ITEM(roce_pkey_index, std::optional()); // RoCE pkey should be 0\n CONFIG_HOT_UPDATED_ITEM(sl, (uint8_t)0);\n CONFIG_HOT_UPDATED_ITEM(traffic_class, std::optional()); // for RoCE\n // CONFIG_HOT_UPDATED_ITEM(gid_index, std::optional()); // for RoCE\n\n CONFIG_HOT_UPDATED_ITEM(start_psn, (uint32_t)0);\n CONFIG_HOT_UPDATED_ITEM(min_rnr_timer, (uint8_t)1);\n CONFIG_HOT_UPDATED_ITEM(timeout, (uint8_t)14); // ibv_qp_attr.timeout\n CONFIG_HOT_UPDATED_ITEM(retry_cnt, (uint8_t)7);\n CONFIG_HOT_UPDATED_ITEM(rnr_retry, (uint8_t)0);\n\n CONFIG_HOT_UPDATED_ITEM(max_sge, 16u, ConfigCheckers::checkPositive);\n CONFIG_HOT_UPDATED_ITEM(max_rdma_wr, 128u, ConfigCheckers::checkPositive); // max number of RDMA WRs in send queue\n CONFIG_HOT_UPDATED_ITEM(max_rdma_wr_per_post,\n 32u,\n ConfigCheckers::checkPositive); // max number of RDMA WRs per ibv_post_send\n CONFIG_HOT_UPDATED_ITEM(max_rd_atomic, 16u, ConfigCheckers::checkPositive); // ibv_qp_attr.max_rd_atomic\n\n CONFIG_HOT_UPDATED_ITEM(buf_size, (16u * 1024), ConfigCheckers::checkPositive);\n CONFIG_HOT_UPDATED_ITEM(send_buf_cnt, 32u, ConfigCheckers::checkPositive);\n CONFIG_HOT_UPDATED_ITEM(buf_ack_batch, 8u, ConfigCheckers::checkPositive);\n CONFIG_HOT_UPDATED_ITEM(buf_signal_batch, 8u, ConfigCheckers::checkPositive);\n CONFIG_HOT_UPDATED_ITEM(event_ack_batch, 128u, ConfigCheckers::checkPositive);\n\n CONFIG_HOT_UPDATED_ITEM(drain_timeout, 5_s);\n CONFIG_HOT_UPDATED_ITEM(drop_connections, 0u);\n\n public:\n mutable folly::Synchronized> roundRobin_;\n IBConnectConfig toIBConnectConfig(bool roce) const;\n };\n\n using Ptr = std::unique_ptr;\n\n IBSocket(const Config &config, IBPort port = {});\n ~IBSocket() override;\n\n CoTryTask connect(serde::ClientContext &ctx, Duration timeout);\n Result accept(folly::IPAddressV4 ip, const IBConnectReq &req, Duration acceptTimeout = 15_s);\n\n std::string describe() override { return *describe_.rlock(); };\n std::string describe() const { return *describe_.rlock(); }\n folly::IPAddressV4 peerIP() override { return peerIP_; };\n\n int fd() const override { return channel_->fd; }\n\n Result poll(uint32_t events) override;\n\n Result send(folly::ByteRange buf);\n Result send(struct iovec *iov, uint32_t cnt) override;\n Result flush() override;\n Result recv(folly::MutableByteRange buf) override;\n\n CoTask close();\n\n // Send a empty message to check the liveness of the socket.\n // - if socket is known to be broken, return corresponding error.\n // - else send check message and return immediately\n // - if the message cannot be delivered, an error will be returned in future during poll.\n Result check() override;\n\n // Socket should already turn from ACCEPTED state to READY or ERROR state\n bool checkConnectFinished() const;\n\n /** RDMA operations. */\n CoTryTask rdmaRead(const RDMARemoteBuf &remoteBuf, RDMABuf &localBuf) {\n co_return co_await rdmaRead(remoteBuf, std::span(&localBuf, 1));\n }\n CoTryTask rdmaRead(const RDMARemoteBuf &remoteBuf, std::span localBufs) {\n co_return co_await rdma(IBV_WR_RDMA_READ, remoteBuf, localBufs);\n }\n\n CoTryTask rdmaWrite(const RDMARemoteBuf &remoteBuf, RDMABuf &localBuf) {\n co_return co_await rdmaWrite(remoteBuf, std::span(&localBuf, 1));\n }\n CoTryTask rdmaWrite(const RDMARemoteBuf &remoteBuf, std::span localBufs) {\n co_return co_await rdma(IBV_WR_RDMA_WRITE, remoteBuf, localBufs);\n }\n\n private:\n struct RDMAReq {\n uint64_t raddr;\n uint32_t rkey;\n uint32_t localBufFirst;\n uint32_t localBufCnt;\n\n RDMAReq()\n : RDMAReq(0, 0, 0, 0) {}\n RDMAReq(uint64_t raddr, uint32_t rkey, uint32_t localBufFirst, uint32_t localBufCnt)\n : raddr(raddr),\n rkey(rkey),\n localBufFirst(localBufFirst),\n localBufCnt(localBufCnt) {}\n };\n\n public:\n class RDMAReqBatch {\n public:\n RDMAReqBatch()\n : RDMAReqBatch(nullptr, ibv_wr_opcode(-1)) {}\n RDMAReqBatch(IBSocket *socket, ibv_wr_opcode opcode)\n : socket_(socket),\n opcode_(opcode),\n reqs_(),\n localBufs_() {}\n\n Result add(const RDMARemoteBuf &remoteBuf, RDMABuf localBuf);\n Result add(RDMARemoteBuf remoteBuf, std::span localBufs);\n\n void reserve(size_t numReqs, size_t numLocalBufs) {\n reqs_.reserve(numReqs);\n localBufs_.reserve(numLocalBufs);\n }\n\n void clear() {\n reqs_.clear();\n localBufs_.clear();\n waitLatency_ = std::chrono::nanoseconds(0);\n transferLatency_ = std::chrono::nanoseconds(0);\n }\n\n ibv_wr_opcode opcode() const { return opcode_; }\n CoTryTask post() {\n co_return co_await socket_->rdmaBatch(opcode_, reqs_, localBufs_, waitLatency_, transferLatency_);\n }\n\n std::chrono::nanoseconds waitLatency() const { return waitLatency_; };\n std::chrono::nanoseconds transferLatency() const { return transferLatency_; };\n\n private:\n IBSocket *socket_;\n ibv_wr_opcode opcode_;\n std::vector reqs_;\n std::vector localBufs_;\n std::chrono::nanoseconds waitLatency_;\n std::chrono::nanoseconds transferLatency_;\n };\n\n RDMAReqBatch rdmaReadBatch() { return RDMAReqBatch(this, IBV_WR_RDMA_READ); }\n RDMAReqBatch rdmaWriteBatch() { return RDMAReqBatch(this, IBV_WR_RDMA_WRITE); }\n\n const IBDevice *device() const { return port_.dev(); }\n\n private:\n static constexpr size_t kRDMAPostBatch = 8;\n\n enum class State {\n INIT,\n CONNECTING,\n ACCEPTED,\n READY,\n CLOSE,\n ERROR,\n };\n\n struct RDMAPostCtx {\n std::optional> sem;\n std::optional waiter;\n\n ibv_wr_opcode opcode;\n std::span reqs;\n std::span localBufs;\n size_t bytes = 0;\n\n folly::coro::Baton baton;\n ibv_wc_status status = IBV_WC_SUCCESS;\n std::chrono::steady_clock::time_point postBegin;\n std::chrono::steady_clock::time_point postEnd;\n\n CoTask waitSem() {\n if (waiter.has_value()) {\n co_await waiter->baton;\n }\n }\n\n bool setError(ibv_wc_status error) {\n if (status == IBV_WC_SUCCESS) {\n status = error;\n return true;\n }\n return false;\n }\n\n __attribute__((no_sanitize(\"thread\"))) void finish() {\n postEnd = std::chrono::steady_clock::now();\n baton.post();\n }\n };\n\n enum class WRType : uint16_t { SEND, RECV, ACK, RDMA, RDMA_LAST, CLOSE, CHECK };\n\n public: // note: public to formatter\n struct WRId : private folly::StampedPtr {\n using Base = folly::StampedPtr;\n\n static uint64_t send(uint32_t signalCount) { return WRId::pack(signalCount, WRType::SEND); }\n static uint64_t recv(uint32_t bufIndex) { return WRId::pack(bufIndex, WRType::RECV); }\n static uint64_t ack() { return WRId::pack(nullptr, WRType::ACK); }\n static uint64_t rdma(RDMAPostCtx *ptr, bool last) {\n return WRId::pack(ptr, last ? WRType::RDMA_LAST : WRType::RDMA);\n }\n static uint64_t close() { return WRId::pack(nullptr, WRType::CLOSE); }\n static uint64_t check() { return WRId::pack(nullptr, WRType::CHECK); }\n\n static uint64_t pack(uint32_t val, WRType type) { return Base::pack((void *)(uint64_t)val, (uint16_t)type); }\n static uint64_t pack(void *ptr, WRType type) { return Base::pack(ptr, (uint16_t)type); }\n\n WRId(uint64_t raw)\n : Base{raw} {}\n\n WRType type() const { return static_cast(stamp()); }\n\n uint32_t sendSignalCount() const {\n assert(type() == WRType::SEND);\n return (uint32_t)(uint64_t)ptr();\n }\n uint32_t recvBufIndex() const {\n assert(type() == WRType::RECV);\n return (uint32_t)(uint64_t)ptr();\n }\n RDMAPostCtx *rdmaPostCtx() const {\n assert(type() == WRType::RDMA || type() == WRType::RDMA_LAST);\n return (RDMAPostCtx *)ptr();\n }\n\n std::string describe() const {\n switch (type()) {\n case WRType::SEND:\n return fmt::format(\"[WRType::SEND, signal {}]\", sendSignalCount());\n case WRType::RECV:\n return fmt::format(\"[WRType::RECV, bufIndex {}]\", recvBufIndex());\n case WRType::ACK:\n return fmt::format(\"[WRType::ACK]\");\n case WRType::RDMA:\n return fmt::format(\"[WRType::RDMA, ctx {}]\", ptr());\n case WRType::RDMA_LAST:\n return fmt::format(\"[WRTpe::RDMA_LAST, ctx {}]\", ptr());\n case WRType::CLOSE:\n return fmt::format(\"[WRType::CLOSE]\");\n case WRType::CHECK:\n return fmt::format(\"[WRType::CHECK]\");\n }\n assert(false);\n return fmt::format(\"[INVALID 0x{:016x}]\", raw);\n }\n\n bool operator==(const WRId &other) const { return raw == other.raw; }\n };\n\n class ImmData {\n static constexpr size_t kTypeOffset = 24;\n static constexpr uint32_t kValMax = (1 << kTypeOffset) - 1;\n static constexpr uint32_t kValMask = kValMax;\n uint32_t val;\n\n public:\n enum class Type : uint8_t {\n ACK,\n CLOSE,\n };\n\n ImmData(__be32 val = 0)\n : val(folly::Endian::big32(val)) {}\n\n static ImmData ack(uint32_t count) { return create(Type::ACK, count); }\n static ImmData close() { return create(Type::CLOSE, 0); }\n static ImmData create(Type type, uint32_t val) {\n assert(type == Type::ACK || type == Type::CLOSE);\n assert(val <= kValMax);\n return folly::Endian::big32(((uint8_t)type << kTypeOffset) | val);\n }\n\n Type type() const { return Type(val >> kTypeOffset); }\n uint32_t data() const { return val & kValMask; }\n\n std::string describe() const {\n switch (type()) {\n case Type::ACK:\n return fmt::format(\"[ACK, count {}]\", data());\n case Type::CLOSE:\n return fmt::format(\"[CLOSE]\");\n default:\n return fmt::format(\"[INVALID 0x{:08x}]\", val);\n }\n }\n\n operator __be32() const { return folly::Endian::big(val); }\n };\n static_assert(sizeof(ImmData) == sizeof(__be32));\n\n private:\n struct BufferMem : folly::MoveOnly {\n const IBDevice *dev = nullptr;\n int64_t total = 0;\n uint8_t *ptr = nullptr;\n ibv_mr *mr = nullptr;\n\n static Result create(const IBDevice *dev, size_t bufSize, size_t bufCnt, unsigned int flags);\n BufferMem() = default;\n BufferMem(BufferMem &&o)\n : dev(std::exchange(o.dev, nullptr)),\n total(std::exchange(o.total, 0)),\n ptr(std::exchange(o.ptr, nullptr)),\n mr(std::exchange(o.mr, nullptr)) {}\n ~BufferMem();\n };\n\n class Buffers {\n public:\n void init(uint8_t *ptr, ibv_mr *mr, size_t bufSize, size_t bufCnt) {\n ptr_ = ptr;\n mr_ = mr;\n bufSize_ = bufSize;\n bufCnt_ = bufCnt;\n }\n\n uint8_t *getBuf(size_t idx) { return ptr_ + idx * bufSize_; }\n ibv_mr *getMr() { return mr_; }\n size_t getBufCnt() const { return bufCnt_; }\n size_t getBufSize() const { return bufSize_; }\n\n protected:\n uint8_t *ptr_ = nullptr;\n ibv_mr *mr_ = nullptr;\n size_t bufSize_ = 0;\n size_t bufCnt_ = 0;\n };\n\n class SendBuffers : public Buffers {\n public:\n void init(uint8_t *ptr, ibv_mr *mr, size_t bufSize, size_t bufCnt);\n void push(size_t cnts);\n bool empty();\n std::pair front();\n void pop();\n\n private:\n alignas(folly::hardware_destructive_interference_size) std::atomic tailIdx_{0};\n alignas(folly::hardware_destructive_interference_size) std::atomic frontIdx_{0};\n std::pair front_;\n };\n\n class RecvBuffers : public Buffers {\n public:\n void init(uint8_t *ptr, ibv_mr *mr, size_t bufSize, size_t bufCnt);\n void push(uint32_t idx, uint32_t len);\n bool empty();\n std::pair front();\n bool pop();\n\n private:\n folly::MPMCQueue> queue_;\n std::optional> front_;\n };\n\n friend class IBConnectService;\n\n int checkConfig() const;\n Result checkPort() const;\n Result getConnectInfo() const;\n void setPeerInfo(folly::IPAddressV4 ip, const IBConnectInfo &info);\n\n // ibv_create_qp & ibv_modify_qp\n [[nodiscard]] int qpCreate();\n [[nodiscard]] int qpInit();\n [[nodiscard]] int qpReadyToRecv();\n [[nodiscard]] int qpReadyToSend();\n void qpError();\n\n Result checkState();\n\n void cqPoll(Events &events);\n int cqGetEvent();\n int cqRequestNotify();\n void wcError(const ibv_wc &wc);\n int wcSuccess(const ibv_wc &wc, Events &events);\n int onSended(const ibv_wc &wc, Events &events);\n int onRecved(const ibv_wc &wc, Events &events);\n int onAckSended(const ibv_wc &wc, Events &events);\n int onRDMAFinished(const ibv_wc &wc, Events &events);\n int onImmData(ImmData imm, Events &events);\n\n int initBufs();\n int postSend(uint32_t idx, size_t len, uint32_t flags = 0);\n int postRecv(uint32_t idx);\n int postAck();\n\n friend class IBSocketManager;\n class Drainer : public EventLoop::EventHandler, public std::enable_shared_from_this {\n public:\n using Ptr = std::shared_ptr;\n using WeakPtr = std::weak_ptr;\n\n static Ptr create(IBSocket::Ptr socket, std::weak_ptr manager);\n\n Drainer(IBSocket::Ptr socket, std::weak_ptr manager);\n ~Drainer() override;\n\n std::string describe() const { return socket_->describe(); }\n\n int fd() const override { return socket_->fd(); }\n void handleEvents(uint32_t /* epollEvents */) override;\n\n private:\n IBSocket::Ptr socket_;\n std::weak_ptr manager_;\n };\n bool closeGracefully();\n bool drain();\n\n CoTryTask rdma(ibv_wr_opcode opcode, const RDMARemoteBuf &remoteBuf, std::span localBufs) {\n RDMAReqBatch batch(this, opcode);\n CO_RETURN_ON_ERROR(batch.add(remoteBuf, localBufs));\n co_return co_await batch.post();\n }\n\n CoTryTask rdmaBatch(ibv_wr_opcode opcode,\n const std::span reqs,\n const std::span localBufs,\n std::chrono::nanoseconds &waitLatency,\n std::chrono::nanoseconds &transferLatency);\n CoTryTask rdmaPost(RDMAPostCtx &ctx);\n int rdmaPostWR(RDMAPostCtx &ctx);\n\n const Config &config_;\n IBConnectConfig connectConfig_;\n\n IBPort port_;\n std::unique_ptr channel_;\n std::unique_ptr cq_;\n std::unique_ptr qp_;\n\n folly::IPAddressV4 peerIP_; // IP of TCP socket to setup connection\n IBConnectInfo peerInfo_;\n folly::Synchronized describe_;\n\n monitor::TagSet tag_;\n monitor::TagSet peerTag_;\n\n SteadyTime acceptTimeout_;\n std::atomic state_ = State::INIT;\n std::atomic closed_ = false;\n std::atomic closeMsgSended_ = false;\n size_t unackedEvents_ = 0;\n\n // memory\n std::optional mem_;\n\n // socket send\n SendBuffers sendBufs_;\n size_t sendNotSignaled_ = 0;\n size_t sendSignaled_ = 0;\n size_t sendAcked_ = 0;\n std::atomic sendWaitBufBegin_ = 0;\n\n // socket recv\n RecvBuffers recvBufs_;\n uint32_t recvNotAcked_ = 0;\n std::atomic ackBufAvailable_ = 0;\n\n // RDMA\n folly::fibers::BatchSemaphore rdmaSem_{0};\n\n // check\n std::atomic checkMsgSended_ = false;\n};\n\nclass IBSocketManager : public EventLoop::EventHandler, public std::enable_shared_from_this {\n public:\n static std::shared_ptr create();\n\n IBSocketManager(int fd)\n : timer_(fd) {}\n\n void stopAndJoin();\n\n void close(IBSocket::Ptr socket);\n\n int fd() const override { return timer_; }\n void handleEvents(uint32_t /* events */) override;\n\n private:\n friend class IBSocket::Drainer;\n void remove(const IBSocket::Drainer::Ptr &drainer) { drainers_.lock()->erase(drainer); }\n\n FdWrapper timer_;\n folly::Synchronized, std::mutex> drainers_;\n folly::Synchronized, std::mutex> deadlines_;\n};\n\n} // namespace net\n} // namespace hf3fs\n"], ["/3FS/src/meta/service/MetaServer.h", "#pragma once\n\n#include \n\n#include \"client/mgmtd/MgmtdClientForServer.h\"\n#include \"client/storage/StorageClient.h\"\n#include \"common/logging/LogConfig.h\"\n#include \"common/net/Client.h\"\n#include \"common/net/Server.h\"\n#include \"common/utils/BackgroundRunner.h\"\n#include \"common/utils/ConfigBase.h\"\n#include \"core/app/ServerAppConfig.h\"\n#include \"core/app/ServerLauncher.h\"\n#include \"core/app/ServerLauncherConfig.h\"\n#include \"core/app/ServerMgmtdClientFetcher.h\"\n#include \"fdb/HybridKvEngineConfig.h\"\n#include \"meta/base/Config.h\"\n#include \"meta/service/MetaOperator.h\"\n\nnamespace hf3fs::meta::server {\n\nclass MetaServer : public net::Server {\n public:\n static constexpr auto kName = \"Meta\";\n static constexpr auto kNodeType = flat::NodeType::META;\n\n struct CommonConfig : public ApplicationBase::Config {\n CommonConfig() {\n using logging::LogConfig;\n log().set_categories({LogConfig::makeRootCategoryConfig(), LogConfig::makeEventCategoryConfig()});\n log().set_handlers({LogConfig::makeNormalHandlerConfig(),\n LogConfig::makeErrHandlerConfig(),\n LogConfig::makeFatalHandlerConfig(),\n LogConfig::makeEventHandlerConfig()});\n }\n };\n\n using AppConfig = core::ServerAppConfig;\n struct LauncherConfig : public core::ServerLauncherConfig {\n LauncherConfig() { mgmtd_client() = hf3fs::client::MgmtdClientForServer::Config{}; }\n };\n using RemoteConfigFetcher = core::launcher::ServerMgmtdClientFetcher;\n using Launcher = core::ServerLauncher;\n\n struct Config : public ConfigBase {\n CONFIG_ITEM(use_memkv, false); // deprecated\n\n CONFIG_OBJ(base, net::Server::Config, [](net::Server::Config &c) {\n c.set_groups_length(2);\n c.groups(0).listener().set_listen_port(8000);\n c.groups(0).set_services({\"MetaSerde\"});\n\n c.groups(1).set_network_type(net::Address::TCP);\n c.groups(1).listener().set_listen_port(9000);\n c.groups(1).set_use_independent_thread_pool(true);\n c.groups(1).set_services({\"Core\"});\n });\n CONFIG_OBJ(fdb, kv::fdb::FDBConfig); // deprecated\n CONFIG_OBJ(meta, meta::server::Config);\n CONFIG_OBJ(background_client, net::Client::Config);\n CONFIG_OBJ(mgmtd_client, ::hf3fs::client::MgmtdClientForServer::Config);\n CONFIG_OBJ(storage_client, storage::client::StorageClient::Config, [](storage::client::StorageClient::Config &cfg) {\n cfg.retry().set_init_wait_time(2_s);\n cfg.retry().set_max_wait_time(5_s);\n cfg.retry().set_max_retry_time(5_s);\n cfg.retry().set_max_failures_before_failover(1);\n });\n CONFIG_OBJ(kv_engine, kv::HybridKvEngineConfig);\n };\n\n MetaServer(const Config &config);\n ~MetaServer() override;\n\n using net::Server::start;\n Result start(const flat::AppInfo &info, std::shared_ptr kvEngine);\n Result start(const flat::AppInfo &info,\n std::unique_ptr client,\n std::shared_ptr<::hf3fs::client::MgmtdClient> mgmtdClient);\n\n // set up meta server.\n Result beforeStart() final;\n\n // tear down meta server.\n Result beforeStop() final;\n Result afterStop() final;\n\n private:\n const Config &config_;\n\n std::shared_ptr kvEngine_;\n std::unique_ptr backgroundClient_;\n std::shared_ptr<::hf3fs::client::MgmtdClientForServer> mgmtdClient_;\n std::unique_ptr metaOperator_;\n};\n\n} // namespace hf3fs::meta::server\n"], ["/3FS/src/storage/service/StorageOperator.h", "#pragma once\n\n#include \n#include \n\n#include \"analytics/StructuredTraceLog.h\"\n#include \"client/mgmtd/IMgmtdClientForServer.h\"\n#include \"client/mgmtd/RoutingInfo.h\"\n#include \"client/storage/StorageMessenger.h\"\n#include \"common/net/Server.h\"\n#include \"common/net/Transport.h\"\n#include \"common/net/ib/IBSocket.h\"\n#include \"common/net/ib/RDMABuf.h\"\n#include \"common/utils/Address.h\"\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/LockManager.h\"\n#include \"common/utils/Semaphore.h\"\n#include \"storage/aio/AioReadWorker.h\"\n#include \"storage/service/BufferPool.h\"\n#include \"storage/service/ReliableForwarding.h\"\n#include \"storage/service/ReliableUpdate.h\"\n#include \"storage/store/StorageTargets.h\"\n#include \"storage/update/UpdateWorker.h\"\n\nnamespace hf3fs::storage {\n\nstruct Components;\n\nclass StorageOperator {\n public:\n class Config : public ConfigBase {\n CONFIG_OBJ(write_worker, UpdateWorker::Config);\n CONFIG_OBJ(event_trace_log, analytics::StructuredTraceLog::Config);\n CONFIG_HOT_UPDATED_ITEM(max_num_results_per_query, uint32_t{100});\n CONFIG_HOT_UPDATED_ITEM(batch_read_job_split_size, uint32_t{1024});\n CONFIG_HOT_UPDATED_ITEM(post_buffer_per_bytes, 64_KB);\n CONFIG_HOT_UPDATED_ITEM(batch_read_ignore_chain_version, false);\n CONFIG_HOT_UPDATED_ITEM(max_concurrent_rdma_writes, 256U);\n CONFIG_HOT_UPDATED_ITEM(max_concurrent_rdma_reads, 256U);\n CONFIG_HOT_UPDATED_ITEM(read_only, false);\n CONFIG_HOT_UPDATED_ITEM(rdma_transmission_req_timeout, 0_ms);\n CONFIG_HOT_UPDATED_ITEM(apply_transmission_before_getting_semaphore, true);\n };\n\n StorageOperator(const Config &config, Components &components)\n : config_(config),\n components_(components),\n updateWorker_(config_.write_worker()),\n storageEventTrace_(config.event_trace_log()) {\n for (const auto &ibdev : net::IBDevice::all()) {\n concurrentRdmaWriteSemaphore_.emplace(ibdev->id(), config.max_concurrent_rdma_writes());\n concurrentRdmaReadSemaphore_.emplace(ibdev->id(), config.max_concurrent_rdma_reads());\n }\n\n onConfigUpdated_ = config_.addCallbackGuard([this]() {\n for (auto &[_, semaphore] : concurrentRdmaWriteSemaphore_) {\n semaphore.changeUsableTokens(config_.max_concurrent_rdma_writes());\n }\n for (auto &[_, semaphore] : concurrentRdmaReadSemaphore_) {\n semaphore.changeUsableTokens(config_.max_concurrent_rdma_reads());\n }\n });\n }\n\n Result init(uint32_t numberOfDisks);\n\n Result stopAndJoin();\n\n CoTryTask batchRead(ServiceRequestContext &requestCtx,\n const BatchReadReq &req,\n serde::CallContext &ctx);\n\n CoTryTask write(ServiceRequestContext &requestCtx, const WriteReq &req, net::IBSocket *ibSocket);\n\n CoTryTask update(ServiceRequestContext &requestCtx, const UpdateReq &req, net::IBSocket *ibSocket);\n\n CoTryTask queryLastChunk(ServiceRequestContext &requestCtx, const QueryLastChunkReq &req);\n\n CoTryTask truncateChunks(ServiceRequestContext &requestCtx, const TruncateChunksReq &req);\n\n CoTryTask removeChunks(ServiceRequestContext &requestCtx, const RemoveChunksReq &req);\n\n CoTryTask syncStart(const SyncStartReq &req);\n\n CoTryTask syncDone(const SyncDoneReq &req);\n\n CoTryTask spaceInfo(const SpaceInfoReq &req);\n\n CoTryTask createTarget(const CreateTargetReq &req);\n\n CoTryTask offlineTarget(const OfflineTargetReq &req);\n\n CoTryTask removeTarget(const RemoveTargetReq &req);\n\n CoTryTask queryChunk(const QueryChunkReq &req);\n\n CoTryTask getAllChunkMetadata(const GetAllChunkMetadataReq &req);\n\n protected:\n using ChunkMetadataProcessor = std::function(const ChunkId &, const ChunkMetadata &)>;\n\n CoTask handleUpdate(ServiceRequestContext &requestCtx,\n UpdateReq &req,\n net::IBSocket *ibSocket,\n TargetPtr &target);\n\n CoTask doUpdate(ServiceRequestContext &requestCtx,\n const UpdateIO &updateIO,\n const UpdateOptions &updateOptions,\n uint32_t featureFlags,\n const std::shared_ptr &target,\n net::IBSocket *ibSocket,\n BufferPool::Buffer &buffer,\n net::RDMARemoteBuf &remoteBuf,\n ChunkEngineUpdateJob &chunkEngineJob,\n bool allowToAllocate);\n\n CoTask doCommit(ServiceRequestContext &requestCtx,\n const CommitIO &commitIO,\n const UpdateOptions &updateOptions,\n ChunkEngineUpdateJob &chunkEngineJob,\n uint32_t featureFlags,\n const std::shared_ptr &target);\n\n Result>> doQuery(ServiceRequestContext &requestCtx,\n const VersionedChainId &vChainId,\n const ChunkIdRange &chunkIdRange);\n\n CoTryTask processQueryResults(ServiceRequestContext &requestCtx,\n const VersionedChainId &vChainId,\n const ChunkIdRange &chunkIdRanges,\n ChunkMetadataProcessor processor,\n bool &moreChunksInRange);\n\n CoTask doTruncate(ServiceRequestContext &requestCtx,\n const TruncateChunkOp &op,\n flat::UserInfo userInfo,\n uint32_t featureFlags);\n\n CoTask doRemove(ServiceRequestContext &requestCtx,\n const RemoveChunksOp &op,\n flat::UserInfo userInfo,\n uint32_t featureFlags);\n\n private:\n friend class ReliableUpdate;\n\n ConstructLog<\"storage::StorageOperator\"> constructLog_;\n const Config &config_;\n Components &components_;\n UpdateWorker updateWorker_;\n analytics::StructuredTraceLog storageEventTrace_;\n std::unique_ptr onConfigUpdated_;\n std::map concurrentRdmaWriteSemaphore_;\n std::map concurrentRdmaReadSemaphore_;\n std::atomic totalReadBytes_{};\n std::atomic totalReadIOs_{};\n};\n\n} // namespace hf3fs::storage\n"], ["/3FS/src/storage/service/Components.h", "#pragma once\n\n#include \n\n#include \"client/mgmtd/MgmtdClientForServer.h\"\n#include \"client/storage/StorageMessenger.h\"\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/DynamicCoroutinesPool.h\"\n#include \"common/utils/LockManager.h\"\n#include \"common/utils/RobinHood.h\"\n#include \"fbs/storage/Service.h\"\n#include \"storage/aio/AioReadWorker.h\"\n#include \"storage/service/BufferPool.h\"\n#include \"storage/service/StorageOperator.h\"\n#include \"storage/service/TargetMap.h\"\n#include \"storage/store/StorageTargets.h\"\n#include \"storage/sync/ResyncWorker.h\"\n#include \"storage/worker/AllocateWorker.h\"\n#include \"storage/worker/CheckWorker.h\"\n#include \"storage/worker/DumpWorker.h\"\n#include \"storage/worker/PunchHoleWorker.h\"\n#include \"storage/worker/SyncMetaKvWorker.h\"\n\nnamespace hf3fs::storage {\n\nclass ReliableForwarding;\n\nstruct Components {\n struct Config : public ConfigBase {\n CONFIG_OBJ(base, net::Server::Config, [](net::Server::Config &c) {\n c.set_groups_length(2);\n c.groups(0).listener().set_listen_port(8000);\n c.groups(0).set_network_type(net::Address::RDMA);\n c.groups(0).set_services({\"StorageSerde\"});\n\n c.groups(1).set_network_type(net::Address::TCP);\n c.groups(1).listener().set_listen_port(9000);\n c.groups(1).set_use_independent_thread_pool(true);\n c.groups(1).set_services({\"Core\"});\n\n c.thread_pool().set_num_io_threads(32);\n c.thread_pool().set_num_proc_threads(32);\n });\n\n CONFIG_OBJ(client, net::Client::Config);\n CONFIG_OBJ(mgmtd, hf3fs::client::MgmtdClientForServer::Config);\n CONFIG_OBJ(targets, StorageTargets::Config);\n CONFIG_OBJ(storage, StorageOperator::Config);\n CONFIG_OBJ(reliable_forwarding, ReliableForwarding::Config);\n CONFIG_OBJ(reliable_update, ReliableUpdate::Config);\n CONFIG_OBJ(buffer_pool, BufferPool::Config);\n CONFIG_OBJ(aio_read_worker, AioReadWorker::Config);\n CONFIG_OBJ(sync_worker, ResyncWorker::Config);\n CONFIG_OBJ(check_worker, CheckWorker::Config);\n CONFIG_OBJ(dump_worker, DumpWorker::Config);\n CONFIG_OBJ(allocate_worker, AllocateWorker::Config);\n CONFIG_OBJ(sync_meta_kv_worker, SyncMetaKvWorker::Config);\n CONFIG_OBJ(forward_client, net::Client::Config);\n CONFIG_OBJ(coroutines_pool_read, DynamicCoroutinesPool::Config);\n CONFIG_OBJ(coroutines_pool_update, DynamicCoroutinesPool::Config);\n CONFIG_OBJ(coroutines_pool_sync, DynamicCoroutinesPool::Config);\n CONFIG_OBJ(coroutines_pool_default, DynamicCoroutinesPool::Config);\n CONFIG_HOT_UPDATED_ITEM(use_coroutines_pool_read, true);\n CONFIG_HOT_UPDATED_ITEM(use_coroutines_pool_update, true);\n CONFIG_HOT_UPDATED_ITEM(speed_up_quit, true);\n };\n\n Components(const Config &config);\n\n Result start(const flat::AppInfo &appInfo, net::ThreadPoolGroup &tpg);\n Result waitRoutingInfo(const flat::AppInfo &appInfo, folly::CPUThreadPoolExecutor &executor);\n Result refreshRoutingInfo();\n Result stopAndJoin(CPUExecutorGroup &executor);\n Result stopMgmtdClient();\n const flat::AppInfo &getAppInfo() const { return appInfo; }\n\n Result> getActiveClientsList();\n void triggerHeartbeatIfNeed();\n\n inline DynamicCoroutinesPool &getCoroutinesPool(uint16_t methodId) {\n if (LIKELY(config.use_coroutines_pool_read()) && methodId == StorageSerde<>::batchReadMethodId) {\n return readPool;\n }\n if (LIKELY(config.use_coroutines_pool_update()) &&\n (methodId == StorageSerde<>::writeMethodId || methodId == StorageSerde<>::updateMethodId)) {\n return updatePool;\n }\n if (methodId == StorageSerde<>::syncStartMethodId || methodId == StorageSerde<>::getAllChunkMetadataMethodId) {\n return syncPool;\n }\n return defaultPool;\n }\n\n protected:\n void updateHeartbeatPayload(const TargetMap &map, bool offline = false);\n\n public:\n ConstructLog<\"storage::Components\"> constructLog_;\n const Config &config;\n flat::AppInfo appInfo;\n std::unique_ptr netClient;\n folly::atomic_shared_ptr mgmtdClient;\n BufferPool rdmabufPool;\n AtomicallyTargetMap targetMap;\n StorageTargets storageTargets;\n AioReadWorker aioReadWorker;\n client::StorageMessenger messenger;\n ResyncWorker resyncWorker;\n CheckWorker checkWorker;\n DumpWorker dumpWorker;\n AllocateWorker allocateWorker;\n PunchHoleWorker punchHoleWorker;\n SyncMetaKvWorker syncMetaKvWorker;\n ReliableForwarding reliableForwarding;\n DynamicCoroutinesPool readPool;\n DynamicCoroutinesPool updatePool;\n DynamicCoroutinesPool syncPool;\n DynamicCoroutinesPool defaultPool;\n StorageOperator storageOperator;\n ReliableUpdate reliableUpdate;\n std::atomic triggerHeartbeatFlag{};\n};\n\n} // namespace hf3fs::storage\n"], ["/3FS/src/meta/base/Config.h", "#pragma once\n\n#include \"analytics/StructuredTraceLog.h\"\n#include \"client/storage/StorageClient.h\"\n#include \"common/kv/TransactionRetry.h\"\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/CoroutinesPool.h\"\n#include \"common/utils/Duration.h\"\n#include \"common/utils/PriorityCoroutinePool.h\"\n#include \"common/utils/Size.h\"\n#include \"core/user/UserCache.h\"\n#include \"meta/components/Distributor.h\"\n#include \"meta/components/Forward.h\"\n#include \"meta/components/SessionManager.h\"\n#include \"meta/event/Event.h\"\n#include \"meta/store/Utils.h\"\n\nnamespace hf3fs::meta::server {\n\nusing kv::TransactionRetry;\n\nstruct GcConfig : ConfigBase {\n CONFIG_HOT_UPDATED_ITEM(enable, true);\n CONFIG_HOT_UPDATED_ITEM(scan_interval, 200_ms);\n CONFIG_HOT_UPDATED_ITEM(scan_batch, 4096);\n CONFIG_HOT_UPDATED_ITEM(remove_chunks_batch_size, 32);\n CONFIG_HOT_UPDATED_ITEM(gc_file_delay, 5_min);\n CONFIG_HOT_UPDATED_ITEM(gc_file_concurrent, 32ul);\n CONFIG_HOT_UPDATED_ITEM(gc_directory_delay, 0_s);\n CONFIG_HOT_UPDATED_ITEM(gc_directory_concurrent, 4ul);\n CONFIG_HOT_UPDATED_ITEM(gc_directory_entry_batch, 32ul);\n CONFIG_HOT_UPDATED_ITEM(gc_directory_entry_concurrent, 4ul);\n CONFIG_HOT_UPDATED_ITEM(retry_delay, 10_min);\n // disable gc delay if free space is below 5%\n CONFIG_HOT_UPDATED_ITEM(gc_delay_free_space_threshold, 5);\n CONFIG_HOT_UPDATED_ITEM(check_session, true);\n CONFIG_HOT_UPDATED_ITEM(distributed_gc, true); // random select a GC directory\n CONFIG_HOT_UPDATED_ITEM(txn_low_priority, false);\n\n // small file or large file\n CONFIG_HOT_UPDATED_ITEM(small_file_chunks, (uint64_t)32);\n CONFIG_HOT_UPDATED_ITEM(large_file_chunks, (uint64_t)128);\n\n CONFIG_HOT_UPDATED_ITEM(recursive_perm_check, true);\n\n CONFIG_OBJ(workers, PriorityCoroutinePoolConfig, [](auto &c) {\n c.set_coroutines_num(8);\n c.set_queue_size(1024);\n });\n CONFIG_OBJ(retry_remove_chunks, storage::client::RetryOptions, [](auto &c) {\n c.set_init_wait_time(10_s);\n c.set_max_wait_time(10_s);\n c.set_max_retry_time(30_s);\n });\n};\n\nstruct Config : ConfigBase {\n CONFIG_HOT_UPDATED_ITEM(readonly, false);\n CONFIG_HOT_UPDATED_ITEM(authenticate, false);\n CONFIG_HOT_UPDATED_ITEM(grv_cache, false);\n\n CONFIG_OBJ(gc, GcConfig);\n CONFIG_OBJ(session_manager, SessionManager::Config);\n CONFIG_OBJ(distributor, Distributor::Config);\n CONFIG_OBJ(forward, Forward::Config);\n CONFIG_OBJ(event_trace_log, analytics::StructuredTraceLog::Config);\n\n CONFIG_HOT_UPDATED_ITEM(max_symlink_depth, 4L, ConfigCheckers::checkPositive);\n CONFIG_HOT_UPDATED_ITEM(max_symlink_count, 10L, ConfigCheckers::checkPositive);\n CONFIG_HOT_UPDATED_ITEM(max_directory_depth, 64L, ConfigCheckers::checkPositive);\n CONFIG_HOT_UPDATED_ITEM(acl_cache_time, 15_s);\n CONFIG_HOT_UPDATED_ITEM(list_default_limit, 128);\n CONFIG_HOT_UPDATED_ITEM(sync_on_prune_session, false);\n CONFIG_HOT_UPDATED_ITEM(max_remove_chunks_per_request, 32u, ConfigCheckers::checkPositive);\n CONFIG_HOT_UPDATED_ITEM(allow_stat_deleted_inodes, true);\n CONFIG_HOT_UPDATED_ITEM(ignore_length_hint, false);\n CONFIG_HOT_UPDATED_ITEM(time_granularity, 1_s);\n CONFIG_HOT_UPDATED_ITEM(dynamic_stripe, false);\n CONFIG_HOT_UPDATED_ITEM(dynamic_stripe_initial, 16u, ConfigCheckers::checkPositive);\n CONFIG_HOT_UPDATED_ITEM(dynamic_stripe_growth, 2u);\n CONFIG_HOT_UPDATED_ITEM(batch_stat_concurrent, 8u);\n CONFIG_HOT_UPDATED_ITEM(batch_stat_by_path_concurrent, 4u);\n CONFIG_HOT_UPDATED_ITEM(max_batch_operations, 4096u);\n CONFIG_HOT_UPDATED_ITEM(enable_new_chunk_engine, false);\n CONFIG_HOT_UPDATED_ITEM(allow_owner_change_immutable, false);\n\n // deperated\n CONFIG_HOT_UPDATED_ITEM(check_file_hole, false);\n CONFIG_OBJ(background_hole_checker, CoroutinesPoolBase::Config, [](CoroutinesPoolBase::Config &c) {\n c.set_coroutines_num(16);\n c.set_queue_size(4096);\n });\n\n CONFIG_HOT_UPDATED_ITEM(inodeId_check_unique, true);\n CONFIG_HOT_UPDATED_ITEM(inodeId_abort_on_duplicate, false);\n\n // replace file with new inode on O_TRUNC\n CONFIG_HOT_UPDATED_ITEM(otrunc_replace_file, true);\n CONFIG_HOT_UPDATED_ITEM(otrunc_replace_file_threshold, 1_GB);\n\n // statfs\n CONFIG_HOT_UPDATED_ITEM(statfs_cache_time, 60_s);\n CONFIG_HOT_UPDATED_ITEM(statfs_update_interval, 5_s);\n CONFIG_HOT_UPDATED_ITEM(statfs_space_imbalance_threshold, 5);\n\n // iflags\n CONFIG_HOT_UPDATED_ITEM(iflags_chain_allocation, false);\n CONFIG_HOT_UPDATED_ITEM(iflags_chunk_engine, true);\n\n // recursive remove\n CONFIG_HOT_UPDATED_ITEM(recursive_remove_check_owner, true);\n CONFIG_HOT_UPDATED_ITEM(recursive_remove_perm_check, (size_t)1024);\n CONFIG_HOT_UPDATED_ITEM(allow_directly_move_to_trash, false);\n\n // idempotent operation\n CONFIG_HOT_UPDATED_ITEM(idempotent_record_expire, 30_min);\n CONFIG_HOT_UPDATED_ITEM(idempotent_record_clean, 1_min);\n CONFIG_HOT_UPDATED_ITEM(idempotent_remove, true);\n CONFIG_HOT_UPDATED_ITEM(idempotent_rename, false);\n\n CONFIG_HOT_UPDATED_ITEM(operation_timeout, 5_s);\n\n CONFIG_OBJ(retry_transaction, TransactionRetry);\n CONFIG_OBJ(retry_remove_chunks, storage::client::RetryOptions, [](auto &c) {\n c.set_init_wait_time(10_s);\n c.set_max_wait_time(10_s);\n c.set_max_retry_time(30_s);\n });\n\n CONFIG_OBJ(user_cache, core::UserCache::Config);\n};\n\n} // namespace hf3fs::meta::server\n"], ["/3FS/src/meta/store/ops/BatchOperation.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/kv/ITransaction.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/Result.h\"\n#include \"common/utils/Shards.h\"\n#include \"common/utils/UtcTime.h\"\n#include \"fbs/core/user/User.h\"\n#include \"fbs/meta/Common.h\"\n#include \"fbs/meta/Schema.h\"\n#include \"fbs/meta/Service.h\"\n#include \"meta/store/DirEntry.h\"\n#include \"meta/store/Inode.h\"\n#include \"meta/store/MetaStore.h\"\n#include \"meta/store/Operation.h\"\nnamespace hf3fs::meta::server {\n\nclass MetaOperator;\n\nclass BatchedOp : public Operation {\n public:\n template \n struct Waiter : folly::NonCopyableNonMovable {\n Req req;\n std::optional> result;\n folly::coro::Baton baton;\n bool newFile = false; /* for Create operation */\n\n Waiter(Req req)\n : req(std::move(req)) {}\n\n Result getResult() {\n XLOGF_IF(FATAL, !result.has_value(), \"result not set\");\n return *result;\n }\n\n bool hasError() const { return result.has_value() && result->hasError(); }\n\n void finish(BatchedOp &op, const Result &r);\n };\n\n BatchedOp(MetaStore &meta, InodeId inodeId)\n : Operation(meta),\n inodeId_(inodeId) {}\n\n std::string_view name() const override { return \"batchedOp\"; }\n\n flat::Uid user() const override { return user_; }\n\n template \n void add(Waiter &waiter);\n\n template <>\n void add(Waiter &waiter) {\n XLOGF_IF(FATAL, waiter.req.inode != inodeId_, \"{} != {}\", waiter.req.inode, inodeId_);\n addReq(syncs_, waiter);\n }\n\n template <>\n void add(Waiter &waiter) {\n XLOGF_IF(FATAL, waiter.req.inode != inodeId_, \"{} != {}\", waiter.req.inode, inodeId_);\n addReq(closes_, waiter);\n }\n\n template <>\n void add(Waiter &waiter) {\n XLOGF_IF(FATAL, waiter.req.path != PathAt(inodeId_), \"{} != {}\", waiter.req.path, PathAt(inodeId_));\n addReq(setattrs_, waiter);\n }\n\n template <>\n void add(Waiter &waiter) {\n XLOGF_IF(FATAL,\n (waiter.req.path.parent != inodeId_ || !waiter.req.path.path || waiter.req.path.path->has_parent_path()),\n \"path {}, inodeId {}\",\n waiter.req.path,\n inodeId_);\n addReq(creates_, waiter);\n }\n\n CoTryTask run(IReadWriteTransaction &txn) override;\n\n void retry(const Status &error) override;\n\n void finish(const Result &result) override;\n\n size_t numReqs() const { return numReqs_; }\n\n // for test\n static CoTryTask create(MetaStore &store, IReadWriteTransaction &txn, CreateReq req) {\n Waiter waiter(req);\n BatchedOp op(store, req.path.parent);\n op.add(waiter);\n op.finish(co_await op.run(txn));\n co_return waiter.getResult();\n }\n\n private:\n friend class MetaOperator;\n\n template \n using WaiterRef = std::reference_wrapper>;\n\n void addReq(auto &reqs, auto &waiter) {\n if (!user_) {\n user_ = waiter.req.user.uid;\n }\n reqs.emplace_back(waiter);\n numReqs_++;\n }\n\n CoTryTask setAttr(IReadWriteTransaction &txn, Inode &inode);\n\n CoTryTask syncAndClose(IReadWriteTransaction &txn, Inode &inode);\n\n CoTryTask sync(Inode &inode,\n const SyncReq &req,\n bool &updateLength,\n bool &truncate,\n std::optional &hintLength);\n\n CoTryTask close(Inode &inode,\n const CloseReq &req,\n bool &updateLength,\n std::optional &hintLength,\n std::vector &sessions);\n\n CoTryTask create(IReadWriteTransaction &txn, Inode &inode);\n\n CoTryTask create(IReadWriteTransaction &txn,\n const Inode &parent,\n folly::Synchronized &chainAllocCounter,\n auto begin,\n auto end);\n\n CoTryTask> create(IReadWriteTransaction &txn,\n const Inode &parent,\n folly::Synchronized &chainAllocCounter,\n const CreateReq &req);\n\n CoTryTask openExists(IReadWriteTransaction &txn, Inode &inode, const DirEntry &entry, auto begin, auto end);\n\n CoTryTask openExists(IReadWriteTransaction &txn, Inode &inode, const CreateReq &req);\n\n CoTryTask queryLength(const Inode &inode, std::optional hintLength, bool truncate);\n\n // requests\n InodeId inodeId_;\n flat::Uid user_; // use first uid\n std::vector> setattrs_;\n std::vector> syncs_;\n std::vector> closes_;\n std::vector> creates_;\n size_t numReqs_ = 0;\n\n // state\n std::optional versionstamp_;\n std::optional currLength_;\n std::optional nextLength_;\n};\n\n} // namespace hf3fs::meta::server"], ["/3FS/src/common/net/IOWorker.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/net/EventLoop.h\"\n#include \"common/net/Network.h\"\n#include \"common/net/Processor.h\"\n#include \"common/net/Transport.h\"\n#include \"common/net/TransportPool.h\"\n#include \"common/net/WriteItem.h\"\n#include \"common/net/ib/IBSocket.h\"\n#include \"common/utils/ConcurrencyLimiter.h\"\n#include \"common/utils/Duration.h\"\n\nnamespace hf3fs::net {\n\n// A worker that handles all I/O tasks.\nclass IOWorker {\n public:\n class Config : public ConfigBase {\n CONFIG_HOT_UPDATED_ITEM(read_write_tcp_in_event_thread, false);\n CONFIG_HOT_UPDATED_ITEM(read_write_rdma_in_event_thread, false);\n CONFIG_HOT_UPDATED_ITEM(tcp_connect_timeout, 1_s);\n CONFIG_HOT_UPDATED_ITEM(rdma_connect_timeout, 5_s);\n CONFIG_HOT_UPDATED_ITEM(wait_to_retry_send, 100_ms);\n CONFIG_ITEM(num_event_loop, 1u);\n\n CONFIG_OBJ(ibsocket, IBSocket::Config);\n CONFIG_OBJ(transport_pool, TransportPool::Config);\n CONFIG_OBJ(connect_concurrency_limiter, ConcurrencyLimiterConfig, [](auto &c) { c.set_max_concurrency(4); });\n };\n\n IOWorker(Processor &processor,\n CPUExecutorGroup &executor,\n folly::IOThreadPoolExecutor &connExecutor,\n const Config &config)\n : processor_(processor),\n executor_(executor),\n connExecutor_(connExecutor),\n config_(config),\n connExecutorShared_(std::make_shared>(&connExecutor_)),\n pool_(config_.transport_pool()),\n eventLoopPool_(config_.num_event_loop()),\n ibsocketConfigGuard_(config.ibsocket().addCallbackGuard([this] {\n auto newVal = config_.ibsocket().drop_connections();\n if (dropConnections_.exchange(newVal) != newVal) {\n XLOGF(INFO, \"ioworker@{} drop all connections\", fmt::ptr(this));\n dropConnections();\n }\n })),\n connectConcurrencyLimiter_(config_.connect_concurrency_limiter()) {}\n ~IOWorker() { stopAndJoin(); }\n\n // start and stop.\n Result start(const std::string &name);\n void stopAndJoin();\n\n // add TCP socket with ownership into this IO worker. [thread-safe]\n Result addTcpSocket(folly::NetworkSocket sock, bool isDomainSocket = false);\n\n // add IBSocket with ownership into this IO worker. [thread-safe]\n Result addIBSocket(std::unique_ptr sock);\n\n // send a batch of items asynchronously to specified address. [thread-safe]\n void sendAsync(Address addr, WriteList list);\n\n // retry a batch of items asynchronously to specified address. [thread-safe]\n void retryAsync(Address addr, WriteList list);\n\n // drop all connections.\n void dropConnections(bool dropAll = true, bool dropIncome = false) { pool_.dropConnections(dropAll, dropIncome); }\n\n // drop all connections to this addr\n void dropConnections(Address addr) { pool_.dropConnections(addr); }\n\n // drop connections to peer.\n void checkConnections(Address addr, Duration expiredTime) { return pool_.checkConnections(addr, expiredTime); }\n\n protected:\n friend class Transport;\n // get a valid transport.\n TransportPtr getTransport(Address addr);\n // remove a transport.\n void remove(TransportPtr transport) { pool_.remove(std::move(transport)); }\n\n // connect asynchronous.\n CoTryTask startConnect(TransportPtr transport, Address addr);\n\n // wait and retry.\n CoTryTask waitAndRetry(Address addr, WriteList list);\n\n // start a `Transport::doRead` task in current thread or thread pool.\n void startReadTask(Transport *transport, bool error, bool logError = true);\n // start a `Transport::doWrite` task in current thread or thread pool.\n void startWriteTask(Transport *transport, bool error, bool logError = true);\n\n // process a message received by transport.\n void processMsg(MessageWrapper wrapper, TransportPtr tr) { processor_.processMsg(std::move(wrapper), std::move(tr)); }\n\n std::weak_ptr> connExecutorWeak() { return connExecutorShared_.load(); }\n\n private:\n Processor &processor_;\n CPUExecutorGroup &executor_;\n folly::IOThreadPoolExecutor &connExecutor_;\n const Config &config_;\n std::atomic dropConnections_{0};\n\n // export a weak keep alive to Transport\n // note: folly's executor has a weakRef method, but the implementation seems have bug and will cause memory leak.\n folly::atomic_shared_ptr> connExecutorShared_;\n\n // keep transports alive.\n TransportPool pool_;\n // monitor I/O events for all transports.\n EventLoopPool eventLoopPool_;\n\n std::unique_ptr ibsocketConfigGuard_;\n\n ConcurrencyLimiter
connectConcurrencyLimiter_;\n\n constexpr static size_t kStopFlag = 1;\n constexpr static size_t kCountInc = 2;\n std::atomic flags_{0};\n};\n\n} // namespace hf3fs::net\n"], ["/3FS/src/meta/store/Operation.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/kv/ITransaction.h\"\n#include \"common/monitor/Recorder.h\"\n#include \"common/monitor/Sample.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/Duration.h\"\n#include \"common/utils/Result.h\"\n#include \"common/utils/UtcTime.h\"\n#include \"fbs/meta/Common.h\"\n#include \"fbs/meta/Service.h\"\n#include \"fbs/meta/Utils.h\"\n#include \"fdb/FDBRetryStrategy.h\"\n#include \"fdb/FDBTransaction.h\"\n#include \"meta/components/AclCache.h\"\n#include \"meta/components/GcManager.h\"\n#include \"meta/components/SessionManager.h\"\n#include \"meta/event/Event.h\"\n#include \"meta/store/Idempotent.h\"\n#include \"meta/store/MetaStore.h\"\n\n#define OPERATION_TAGS(reqName) \\\n std::string_view name() const override { return MetaSerde<>::getRpcName(reqName); } \\\n flat::Uid user() const override { return reqName.user.uid; }\n\n#define CHECK_REQUEST(reqName) \\\n do { \\\n if (auto result = reqName.valid(); UNLIKELY(result.hasError())) { \\\n auto rpcName = MetaSerde<>::getRpcName(reqName); \\\n XLOGF(WARN, \"{} get invalid req, error {}\", rpcName, result.error()); \\\n CO_RETURN_ERROR(result); \\\n } \\\n } while (0)\n\nnamespace hf3fs::meta::server {\n\ntemplate \nclass Operation : public IOperation {\n public:\n Operation(MetaStore &meta)\n : meta_(meta) {}\n\n bool isReadOnly() override { return false; }\n CoTryTask run(IReadWriteTransaction &) override = 0;\n\n void retry(const Status &) override { clearEvents(); }\n\n void finish(const Result &result) override {\n if (!result.hasError()) {\n // success\n for (const auto &event : events_) {\n event.log();\n }\n\n for (const auto &trace : traces_) {\n auto &traceLog = meta_.getEventTraceLog();\n traceLog.append(trace);\n }\n }\n }\n\n protected:\n const Config &config() const { return meta_.config_; }\n\n InodeIdAllocator &inodeIdAlloc() { return *meta_.inodeAlloc_; }\n ChainAllocator &chainAlloc() { return *meta_.chainAlloc_; }\n FileHelper &fileHelper() { return *meta_.fileHelper_; }\n SessionManager &sessionManager() { return *meta_.sessionManager_; }\n GcManager &gcManager() { return *meta_.gcManager_; }\n AclCache &aclCache() { return meta_.aclCache_; }\n Distributor &distributor() { return *meta_.distributor_; }\n\n UtcTime now() const { return UtcClock::now().castGranularity(config().time_granularity()); }\n\n PathResolveOp resolve(IReadOnlyTransaction &txn, const UserInfo &user, Path *path = nullptr) {\n return PathResolveOp(txn,\n aclCache(),\n user,\n path,\n config().max_symlink_count(),\n config().max_symlink_depth(),\n config().acl_cache_time());\n }\n\n CoTryTask allocateInodeId(IReadWriteTransaction &txn, bool newChunkEngine) {\n auto newId = co_await inodeIdAlloc().allocate();\n CO_RETURN_ON_ERROR(newId);\n\n if (newChunkEngine) {\n newId = InodeId::withNewChunkEngine(*newId);\n }\n\n if (config().inodeId_check_unique()) {\n auto loadResult = co_await Inode::load(txn, *newId);\n CO_RETURN_ON_ERROR(loadResult);\n if (loadResult->has_value()) {\n XLOGF_IF(FATAL,\n config().inodeId_abort_on_duplicate(),\n \"InodeIdAllocator get duplicated InodeId {}\",\n newId.value());\n XLOGF(DFATAL, \"InodeIdAllocator get duplicated InodeId {}\", newId.value());\n co_return makeError(MetaCode::kInodeIdAllocFailed);\n }\n } else {\n XLOGF_EVERY_MS(WARN, (300 * 1000), \"inodeId_check_unique is disabled\");\n }\n\n co_return newId;\n }\n\n void clearEvents() { events_.clear(); }\n Event &addEvent(Event::Type type) {\n events_.emplace_back(type);\n return *events_.rbegin();\n }\n void addEvent(Event event) { events_.emplace_back(std::move(event)); }\n\n void addTrace(MetaEventTrace &&trace) { traces_.emplace_back(std::move(trace)); }\n\n MetaStore &meta_;\n std::vector events_;\n std::vector traces_;\n};\n\ntemplate \nclass ReadOnlyOperation : public Operation {\n public:\n ReadOnlyOperation(MetaStore &meta)\n : Operation(meta) {}\n\n bool isReadOnly() final { return true; }\n\n virtual CoTryTask run(IReadOnlyTransaction &) = 0;\n CoTryTask run(IReadWriteTransaction &txn) final {\n co_return co_await run(static_cast(txn));\n }\n};\n\ntemplate \nclass OperationDriver {\n public:\n OperationDriver(MetaStore::Op &operation, const ReqInfo &req, std::optional deadline = std::nullopt)\n : operation_(operation),\n req_(req),\n deadline_(deadline) {}\n\n CoTryTask run(std::unique_ptr txn,\n kv::FDBRetryStrategy::Config config,\n bool readonly,\n bool enableGrvCache) {\n config.retryMaybeCommitted = operation_.retryMaybeCommitted();\n kv::FDBRetryStrategy strategy(config);\n CO_RETURN_ON_ERROR(strategy.init(txn.get()));\n\n OperationRecorder::Guard recorder(OperationRecorder::server(), operation_.name(), operation_.user());\n\n if (readonly && !operation_.isReadOnly()) {\n co_return makeError(StatusCode::kReadOnlyMode, \"FileSystem is in readonly mode.\");\n }\n\n auto grvCache = operation_.isReadOnly() && enableGrvCache;\n if (grvCache && dynamic_cast(txn.get())) {\n auto fdbTxn = dynamic_cast(txn.get());\n CO_RETURN_ON_ERROR(fdbTxn->setOption(FDBTransactionOption::FDB_TR_OPTION_USE_GRV_CACHE, {}));\n }\n\n Result result = makeError(MetaCode::kOperationTimeout);\n auto duplicate = false;\n while (true) {\n // check timeout\n if (deadline_ && deadline_.value() <= SteadyClock::now()) {\n XLOGF(ERR, \"Request {} timeout, return error {}\", describe(), result);\n break;\n }\n // run operation\n result = co_await runAndCommit(*txn, operation_, duplicate);\n if (ErrorHandling::success(result)) {\n break;\n }\n // retry\n XLOGF(WARN, \"Request {} failed, error {}\", describe(), result.error());\n operation_.retry(result.error());\n auto retry = co_await strategy.onError(txn.get(), result.error());\n if (retry.hasError()) {\n result = makeError(retry.error());\n break;\n }\n recorder.retry()++;\n }\n\n if (result.hasError() && result.error().code() == StatusCode::kOK) {\n XLOGF(DFATAL, \"Has error but error code is kOK, {}, {}\", describe(), result);\n result = makeError(MetaCode::kFoundBug);\n }\n\n recorder.finish(result, duplicate);\n operation_.finish(result);\n co_return result;\n }\n\n private:\n#define IDEMPOTENT_CHECK() \\\n do { \\\n auto idemCheck = co_await Idempotent::load(txn, clientId, requestId, req_); \\\n CO_RETURN_ON_ERROR(idemCheck); \\\n duplicate = idemCheck->has_value(); \\\n if (duplicate) { \\\n co_return idemCheck->value(); \\\n } \\\n } while (0)\n\n template \n std::invoke_result_t runAndCommit(IReadWriteTransaction &txn,\n Handler &&handler,\n bool &duplicate) {\n Uuid clientId, requestId;\n auto readonly = handler.isReadOnly();\n auto idem = !readonly && operation_.needIdempotent(clientId, requestId);\n if (idem) {\n OperationRecorder::server().addIdempotentCount();\n IDEMPOTENT_CHECK();\n auto result = co_await handler(txn);\n if (result) {\n CO_RETURN_ON_ERROR(co_await Idempotent::store(txn, clientId, requestId, result));\n CO_RETURN_ON_ERROR(co_await txn.commit());\n } else if (ErrorHandling::success(result) || !ErrorHandling::retryable(result.error())) {\n // this is final result, discard other modifications and save result\n txn.reset();\n IDEMPOTENT_CHECK();\n CO_RETURN_ON_ERROR(co_await Idempotent::store(txn, clientId, requestId, result));\n CO_RETURN_ON_ERROR(co_await txn.commit());\n }\n co_return result;\n } else {\n auto result = co_await handler(txn);\n if (!result.hasError() && !readonly) {\n CO_RETURN_ON_ERROR(co_await txn.commit());\n }\n co_return result;\n }\n }\n\n std::string describe() const {\n if constexpr (std::is_base_of_v) {\n return fmt::format(\"{}{}\", operation_.name(), req_);\n } else {\n return std::string(operation_.name());\n }\n }\n\n MetaStore::Op &operation_;\n const ReqInfo &req_;\n std::optional deadline_;\n};\n\n} // namespace hf3fs::meta::server"], ["/3FS/src/storage/sync/ResyncWorker.h", "#pragma once\n\n#include \n#include \n#include \n#include \n\n#include \"client/storage/UpdateChannelAllocator.h\"\n#include \"common/serde/Serde.h\"\n#include \"common/utils/ConcurrencyLimiter.h\"\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/CoroutinesPool.h\"\n#include \"common/utils/Duration.h\"\n#include \"common/utils/Shards.h\"\n#include \"fbs/storage/Common.h\"\n#include \"storage/service/TargetMap.h\"\n\nnamespace hf3fs::storage {\n\nstruct Components;\n\nclass ResyncWorker {\n public:\n enum FullSyncLevel {\n NONE,\n HEAVY, // sync all.\n };\n struct Config : ConfigBase {\n CONFIG_ITEM(num_threads, 16ul);\n CONFIG_ITEM(num_channels, 1024u);\n CONFIG_HOT_UPDATED_ITEM(batch_size, 16u);\n CONFIG_HOT_UPDATED_ITEM(sync_start_timeout, 10_s);\n CONFIG_HOT_UPDATED_ITEM(full_sync_chains, std::set{}); // full sync all chains if it is empty.\n CONFIG_HOT_UPDATED_ITEM(full_sync_level, FullSyncLevel::NONE);\n CONFIG_OBJ(pool, CoroutinesPoolBase::Config);\n CONFIG_OBJ(batch_concurrency_limiter, ConcurrencyLimiterConfig, [](auto &c) { c.set_max_concurrency(64); });\n };\n ResyncWorker(const Config &config, Components &components);\n\n // start resync worker.\n Result start();\n\n // stop resync worker. End all sync tasks immediately.\n Result stopAndJoin();\n\n protected:\n void loop();\n\n // handle sync job.\n CoTryTask handleSync(VersionedChainId vChainId);\n\n // forward sync request.\n CoTryTask forward(const TargetPtr &target,\n const monitor::TagSet &tag,\n const ClientId &clientId,\n ChunkId chunkId,\n UpdateType updateType,\n uint32_t chunkSize);\n\n private:\n ConstructLog<\"storage::ResyncWorker\"> constructLog_;\n const Config &config_;\n Components &components_;\n folly::CPUThreadPoolExecutor executors_;\n CoroutinesPool pool_;\n client::UpdateChannelAllocator updateChannelAllocator_;\n ConcurrencyLimiter batchConcurrencyLimiter_;\n\n std::mutex mutex_;\n std::condition_variable cond_;\n std::atomic stopping_ = false;\n std::atomic started_ = false;\n std::atomic stopped_ = false;\n\n struct SyncingStatus {\n SERDE_STRUCT_FIELD(isSyncing, false);\n SERDE_STRUCT_FIELD(lastSyncingTime, RelativeTime{});\n };\n using SyncingChainIds = robin_hood::unordered_map;\n Shards shards_;\n std::atomic_uint64_t requestId_;\n};\n\n} // namespace hf3fs::storage\n"], ["/3FS/src/meta/components/InodeIdAllocator.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/kv/IKVEngine.h\"\n#include \"common/monitor/Recorder.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/FaultInjection.h\"\n#include \"common/utils/IdAllocator.h\"\n#include \"common/utils/Result.h\"\n#include \"fbs/meta/Common.h\"\n#include \"fdb/FDBRetryStrategy.h\"\n\nnamespace hf3fs::meta::server {\n\n/**\n * Generate InodeId range from 0x00000000_00001000 to 0x01ffffff_ffffffff.\n *\n * Generated InodeId format: [ high 52bits: generated by IdAllocator ][ low 12 bits: local generated ].\n * InodeIdAllocator first use IdAllocator to generate a 52bits value, then left shift 12 bits and generate lower 12 bits\n * locally. So it only need to access the FoundationDB after generate 4096 InodeIds.\n */\nclass InodeIdAllocator : public std::enable_shared_from_this {\n // These values are used in FoundationDB\n static std::string kAllocatorKeyPrefix;\n static constexpr size_t kAllocatorShard = 32; // avoid txn conflictation\n static constexpr uint64_t kAllocatorShift = 12; // shift 12 bit\n static constexpr uint64_t kAllocatorBit =\n 64 - kAllocatorShift; // IdAllocator generated values only have 52bits valid.\n static constexpr uint64_t kAllocatorMask = (1ULL << kAllocatorBit) - 1;\n static constexpr uint64_t kAllocateBatch = 1 << kAllocatorShift;\n\n struct Tag {};\n\n public:\n InodeIdAllocator(Tag, std::shared_ptr kvEngine)\n : engine_(std::move(kvEngine)),\n allocator_(*engine_, createRetryStrategy(), kAllocatorKeyPrefix, kAllocatorShard),\n allocating_(false),\n queue_(2 * kAllocateBatch) {}\n\n static std::shared_ptr create(std::shared_ptr kvEngine) {\n return std::make_shared(Tag{}, std::move(kvEngine));\n }\n\n CoTryTask allocate(std::chrono::microseconds timeout = std::chrono::seconds(2)) {\n static monitor::CountRecorder failed(\"meta_inodeid_alloc_failed\");\n\n auto id = queue_.try_dequeue();\n if (LIKELY(id.has_value())) {\n if (queue_.size() < kAllocateBatch / 2) {\n tryStartAllocateTask(co_await folly::coro::co_current_executor);\n }\n co_return id.value();\n }\n auto result = co_await allocateSlow(timeout);\n if (result.hasError()) {\n failed.addSample(1);\n co_return result;\n }\n if (result->u64() >= InodeId::kNewChunkEngineMask) {\n failed.addSample(1);\n XLOGF(DFATAL, \"InodeId {} is larger than\", *result, InodeId(InodeId::kNewChunkEngineMask));\n co_return makeError(MetaCode::kInodeIdAllocFailed, \"InodeId too large, shouldn't happen\");\n }\n co_return result;\n }\n\n private:\n static kv::FDBRetryStrategy createRetryStrategy() { return kv::FDBRetryStrategy({.retryMaybeCommitted = true}); }\n\n static CoTask allocateTask(std::weak_ptr weak,\n std::optional delay = std::nullopt) {\n if (delay.has_value()) {\n co_await folly::coro::sleep(delay.value());\n }\n\n auto ptr = weak.lock();\n if (ptr) {\n co_await ptr->allocateFromDB();\n }\n co_return;\n }\n\n void tryStartAllocateTask(folly::Executor *exec) {\n if (!allocating_.exchange(true)) {\n startAllocateTask(exec);\n }\n }\n\n void startAllocateTask(folly::Executor *exec) {\n folly::RequestContextScopeGuard guard;\n allocateTask(weak_from_this()).scheduleOn(exec).start();\n }\n\n CoTryTask allocateSlow(std::chrono::microseconds timeout);\n CoTask allocateFromDB();\n\n std::shared_ptr engine_;\n IdAllocator allocator_;\n std::atomic allocating_;\n folly::coro::BoundedQueue queue_;\n};\n\n} // namespace hf3fs::meta::server\n"], ["/3FS/src/common/utils/CoroutinesPool.h", "#pragma once\n\n#include \n#include \n#include \n#include \n\n#include \"common/utils/BoundedQueue.h\"\n#include \"common/utils/CPUExecutorGroup.h\"\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/Coroutine.h\"\n\nnamespace hf3fs {\n\nstruct CoroutinesPoolBase {\n class Config : public ConfigBase {\n CONFIG_ITEM(coroutines_num, 64u);\n CONFIG_ITEM(queue_size, 1024u);\n CONFIG_ITEM(enable_work_stealing, false);\n\n public:\n Config() = default;\n Config(uint32_t coroutinesNum, uint32_t queueSize, bool enableWorkStealing = false) {\n set_coroutines_num(coroutinesNum);\n set_queue_size(queueSize);\n set_enable_work_stealing(enableWorkStealing);\n }\n };\n};\n\ntemplate \nclass CoroutinesPool : public CoroutinesPoolBase {\n public:\n CoroutinesPool(const Config &config, std::optional> executor = std::nullopt)\n : config_(config),\n executor_(std::move(executor)) {\n if (config_.enable_work_stealing()) {\n auto coroutinesNum = config_.coroutines_num();\n auto queueSizePerCoroutine = (config_.queue_size() + coroutinesNum - 1) / coroutinesNum;\n for (auto i = 0u; i < coroutinesNum; ++i) {\n funcQueues_.push_back(std::make_unique(queueSizePerCoroutine));\n }\n } else {\n funcQueues_.push_back(std::make_unique(config_.queue_size()));\n }\n }\n ~CoroutinesPool() { stopAndJoin(); }\n\n using Handler = std::function(Job job)>;\n Result start(Handler handler) {\n if (UNLIKELY(!executor_.has_value())) {\n auto msg = fmt::format(\"CoroutinesPool@{} does not have an executor\", fmt::ptr(this));\n XLOG(ERR, msg);\n return makeError(StatusCode::kInvalidConfig, std::move(msg));\n }\n auto coroutinesNum = config_.coroutines_num();\n for (auto i = 0u; i < coroutinesNum; ++i) {\n futures_.push_back(run(handler, i).scheduleOn(*executor_).start());\n }\n return Void{};\n }\n\n Result start(Handler handler, CPUExecutorGroup &executor) {\n auto coroutinesNum = config_.coroutines_num();\n for (auto i = 0u; i < coroutinesNum; ++i) {\n futures_.push_back(run(handler, i).scheduleOn(&executor.pickNext()).start());\n }\n return Void{};\n }\n\n void stopAndJoin() {\n if (stopped_.test_and_set()) {\n XLOGF(DBG, \"coroutines pool {} is already stopped.\", fmt::ptr(this));\n return;\n }\n cancel_.requestCancellation();\n for (auto &future : futures_) {\n future.wait();\n }\n futures_.clear();\n if (executor_.has_value()) {\n executor_->reset();\n }\n XLOGF(INFO, \"coroutines pool {} is stopped\", fmt::ptr(this));\n }\n\n void enqueueSync(Job job) { pickQueue().enqueue(std::move(job)); }\n CoTask enqueue(Job job) { co_await pickQueue().co_enqueue(std::move(job)); }\n\n protected:\n using Queue = BoundedQueue;\n using QueuePtr = std::unique_ptr;\n\n Queue &pickQueue() {\n auto n = folly::Random::rand32(0, funcQueues_.size());\n return *funcQueues_[n];\n }\n\n struct WorkStealingJobTaker {\n WorkStealingJobTaker(bool enableWorkStealing,\n size_t selfIndex,\n size_t totalRunners,\n const std::vector &qs)\n : self(enableWorkStealing ? selfIndex : 0),\n queues(qs) {\n if (enableWorkStealing) {\n for (size_t i = 0; i < totalRunners; ++i) {\n if (i != selfIndex) {\n others.push_back(i);\n }\n }\n std::shuffle(others.begin(), others.end(), folly::ThreadLocalPRNG{});\n }\n }\n\n CoTask take() {\n if (others.empty()) {\n co_return co_await queues[self]->co_dequeue();\n }\n\n while (true) {\n if (auto maybeJob = co_await timedWait(*queues[self]); maybeJob) {\n co_return std::move(*maybeJob);\n }\n\n auto otherIndex = others[nextIndex++ % others.size()];\n if (auto maybeJob = queues[otherIndex]->try_dequeue(); maybeJob) {\n co_return std::move(*maybeJob);\n }\n }\n __builtin_unreachable();\n }\n\n CoTask> timedWait(Queue &queue) {\n static constexpr auto timeout = std::chrono::milliseconds(5);\n auto [sleepResult, dequeueResult] =\n co_await folly::coro::collectAnyNoDiscard(folly::coro::sleep(timeout), queue.co_dequeue());\n if (!dequeueResult.hasValue() && !dequeueResult.hasException()) {\n co_return std::nullopt;\n }\n co_return std::move(*dequeueResult);\n }\n\n size_t self;\n size_t nextIndex = 0;\n std::vector others;\n const std::vector &queues;\n };\n\n CoTask run(Handler handler, size_t queueIndex) {\n WorkStealingJobTaker taker(config_.enable_work_stealing(), queueIndex, config_.coroutines_num(), funcQueues_);\n while (true) {\n auto result = co_await co_awaitTry(co_withCancellation(cancel_.getToken(), taker.take()));\n if (UNLIKELY(result.template hasException())) {\n XLOGF(DBG, \"a coroutine in pool {} is stopped\", fmt::ptr(this));\n break;\n } else if (result.hasException()) {\n XLOGF(ERR, \"a coroutine in pool {} is stopped (exception: {})\", fmt::ptr(this), result.exception().what());\n break;\n }\n co_await handler(std::move(*result));\n }\n }\n\n private:\n const Config &config_;\n std::optional> executor_;\n std::vector funcQueues_;\n\n CancellationSource cancel_;\n std::vector> futures_;\n std::atomic_flag stopped_{false};\n};\n\n} // namespace hf3fs\n"], ["/3FS/src/mgmtd/service/MockMgmtd.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/Result.h\"\n#include \"mgmtd/service/MgmtdConfig.h\"\n#include \"mgmtd/service/MgmtdOperator.h\"\n#include \"mgmtd/service/MgmtdService.h\"\n\nnamespace hf3fs::mgmtd {\n\nclass MockMgmtd {\n public:\n struct Config : ConfigBase {\n CONFIG_OBJ(mgmtd, MgmtdConfig);\n CONFIG_ITEM(node_id, 1u);\n CONFIG_ITEM(name, \"mock-mgmtd\");\n CONFIG_ITEM(cluster_id, \"mock-cluster\");\n };\n\n static CoTryTask> create(Config config,\n std::shared_ptr kvEngine,\n CPUExecutorGroup *exec) {\n flat::ServiceGroupInfo groupInfo;\n groupInfo.services.emplace(mgmtd::MgmtdService::kServiceName);\n groupInfo.endpoints.push_back(net::Address::from(\"TCP://127.0.0.1:8000\").value());\n\n flat::AppInfo info;\n info.nodeId = flat::NodeId(config.node_id());\n info.pid = static_cast(getpid());\n info.serviceGroups = {groupInfo};\n info.clusterId = config.cluster_id();\n\n auto env = std::make_shared();\n env->setAppInfo(info);\n env->setKvEngine(kvEngine);\n env->setBackgroundExecutor(exec);\n\n auto mgmtd = std::make_unique();\n mgmtd->config_ = config;\n mgmtd->mgmtdOperator_ = std::make_unique(std::move(env), mgmtd->config_.mgmtd());\n\n mgmtd->mgmtdOperator_->start();\n co_return mgmtd;\n }\n\n void stop() { mgmtdOperator_.reset(); }\n\n std::unique_ptr getService() { return std::make_unique(*mgmtdOperator_); }\n\n MgmtdOperator &getOperator() { return *mgmtdOperator_; }\n\n private:\n Config config_;\n std::unique_ptr mgmtdOperator_;\n};\n\n} // namespace hf3fs::mgmtd\n"], ["/3FS/src/common/utils/DynamicCoroutinesPool.h", "#pragma once\n\n#include \n#include \n\n#include \"common/monitor/Recorder.h\"\n#include \"common/utils/BoundedQueue.h\"\n#include \"common/utils/CPUExecutorGroup.h\"\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/Coroutine.h\"\n\nnamespace hf3fs {\n\nclass DynamicCoroutinesPool {\n public:\n class Config : public ConfigBase {\n CONFIG_ITEM(queue_size, 1024u);\n CONFIG_HOT_UPDATED_ITEM(threads_num, 8ul, ConfigCheckers::checkPositive);\n CONFIG_HOT_UPDATED_ITEM(coroutines_num, 64u, ConfigCheckers::checkPositive);\n };\n\n DynamicCoroutinesPool(const Config &config, std::string_view name = \"pool\");\n\n ~DynamicCoroutinesPool() { stopAndJoin(); }\n\n Result start();\n\n Result stopAndJoin();\n\n void enqueue(CoTask &&task) { queue_.enqueue(std::make_unique>(std::move(task))); }\n\n protected:\n Result setCoroutinesNum(uint32_t num);\n\n CoTask run();\n\n void afterCoroutineStop();\n\n private:\n const Config &config_;\n BoundedQueue>> queue_;\n std::unique_ptr guard_;\n\n std::mutex mutex_;\n folly::CPUThreadPoolExecutor executor_;\n monitor::Recorder::TagRef coroutinesNumRecorder_;\n\n std::atomic_flag stopped_{false};\n folly::coro::Baton baton_;\n uint32_t coroutinesNum_{};\n folly::Synchronized currentRunning_{1};\n};\n\n} // namespace hf3fs\n"], ["/3FS/src/client/meta/ServerSelectionStrategy.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"client/mgmtd/ICommonMgmtdClient.h\"\n#include \"client/mgmtd/RoutingInfo.h\"\n#include \"common/app/NodeId.h\"\n#include \"common/utils/Address.h\"\n#include \"common/utils/MagicEnum.hpp\"\n\nnamespace hf3fs::meta::client {\n\nusing hf3fs::client::ICommonMgmtdClient;\nusing hf3fs::client::RoutingInfo;\n\nenum ServerSelectionMode {\n RoundRobin,\n UniformRandom,\n RandomFollow,\n};\n\nstruct ServerSelectionStrategy : folly::NonCopyableNonMovable {\n struct NodeInfo {\n flat::NodeId nodeId;\n net::Address address;\n std::string hostname;\n };\n\n static std::unique_ptr create(ServerSelectionMode mode,\n std::shared_ptr mgmtd,\n net::Address::Type addrType);\n\n virtual ~ServerSelectionStrategy() = default;\n\n virtual ServerSelectionMode mode() = 0;\n virtual net::Address::Type addrType() = 0;\n virtual Result select(const std::set &skipNodes) = 0;\n virtual std::optional get(flat::NodeId node) = 0;\n};\n\nstruct ServerList {\n std::shared_ptr routing;\n std::vector nodeList;\n std::map nodeAddress;\n\n bool update(std::shared_ptr newRouting, net::Address::Type addrType);\n std::optional get(flat::NodeId nodeId) const;\n};\n\nclass BaseSelectionStrategy : public ServerSelectionStrategy {\n public:\n BaseSelectionStrategy(std::shared_ptr mgmtd, net::Address::Type addrType);\n ~BaseSelectionStrategy() override;\n\n Result select(const std::set &skipNodes) override;\n std::optional get(flat::NodeId node) override { return servers_.rlock()->get(node); }\n net::Address::Type addrType() override { return addrType_; }\n\n virtual flat::NodeId selectFrom(const std::vector &nodes, const std::set &skipHint) = 0;\n virtual void onUpdate(ServerList &);\n\n protected:\n // NOTE: must call this in subclass\n void registerListener();\n void update(std::shared_ptr routing);\n\n std::string name_;\n net::Address::Type addrType_;\n std::shared_ptr mgmtd_;\n folly::Synchronized servers_;\n};\n\nstruct RoundRobinServerSelection : public BaseSelectionStrategy {\n RoundRobinServerSelection(std::shared_ptr mgmtd, net::Address::Type addrType)\n : BaseSelectionStrategy(mgmtd, addrType) {\n registerListener();\n }\n ~RoundRobinServerSelection() override = default;\n\n ServerSelectionMode mode() override { return ServerSelectionMode::RoundRobin; }\n flat::NodeId selectFrom(const std::vector &nodes, const std::set &skipHint) override;\n\n private:\n std::atomic next_{0};\n};\n\nstruct UniformRandomServerSelection : public BaseSelectionStrategy {\n UniformRandomServerSelection(std::shared_ptr mgmtd, net::Address::Type addrType)\n : BaseSelectionStrategy(mgmtd, addrType),\n mutex_(),\n gen_(std::random_device{}()) {\n registerListener();\n }\n ~UniformRandomServerSelection() override = default;\n\n ServerSelectionMode mode() override { return ServerSelectionMode::UniformRandom; }\n flat::NodeId selectFrom(const std::vector &nodes, const std::set &skipHint) override;\n\n private:\n using index_range = std::uniform_int_distribution::param_type;\n std::mutex mutex_;\n std::mt19937_64 gen_;\n std::uniform_int_distribution dist_;\n};\n\nstruct RandomFollowServerSelection : public BaseSelectionStrategy {\n RandomFollowServerSelection(std::shared_ptr mgmtd, net::Address::Type addrType)\n : BaseSelectionStrategy(mgmtd, addrType),\n token_(Uuid::random()) {\n registerListener();\n }\n ~RandomFollowServerSelection() override = default;\n\n ServerSelectionMode mode() override { return ServerSelectionMode::RandomFollow; }\n flat::NodeId selectFrom(const std::vector &nodes, const std::set &skipHint) override;\n std::optional get(flat::NodeId node) override { return servers_.rlock()->get(node); }\n void onUpdate(ServerList &servers) override;\n\n private:\n Uuid token_;\n std::vector prefer_;\n};\n} // namespace hf3fs::meta::client\n\nFMT_BEGIN_NAMESPACE\n\ntemplate <>\nstruct formatter : formatter {\n template \n auto format(const hf3fs::meta::client::ServerSelectionStrategy::NodeInfo &node, FormatContext &ctx) const {\n return fmt::format_to(ctx.out(), \"[{}]@{}.{}\", node.address, node.nodeId, node.hostname);\n }\n};\n\nFMT_END_NAMESPACE\n"], ["/3FS/src/common/utils/PriorityCoroutinePool.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/app/ApplicationBase.h\"\n#include \"common/utils/CPUExecutorGroup.h\"\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/PriorityUnboundedQueue.h\"\n\nnamespace hf3fs {\n\n/** Like CoroutinePool, but use PriorityUnboundedQueue in order to support tasks with priority. */\nstruct PriorityCoroutinePoolConfig : public ConfigBase {\n // todo: support hot update coroutine numbers\n CONFIG_HOT_UPDATED_ITEM(coroutines_num, 64u, ConfigCheckers::checkPositive);\n // unused, just for compatibility\n CONFIG_HOT_UPDATED_ITEM(queue_size, 1024u);\n CONFIG_HOT_UPDATED_ITEM(enable_work_stealing, false);\n};\n\ntemplate \nclass PriorityCoroutinePool {\n public:\n using Config = PriorityCoroutinePoolConfig;\n\n PriorityCoroutinePool(const Config &config, uint8_t numPriorities = 3)\n : config_(config),\n queue_(numPriorities),\n cancel_(),\n futures_() {}\n ~PriorityCoroutinePool() { stopAndJoin(); }\n\n using Handler = std::function(Job job)>;\n Result start(Handler handler, CPUExecutorGroup &grp) {\n auto coroutines = config_.coroutines_num();\n for (auto i = 0u; i < coroutines; ++i) {\n futures_.push_back(run(handler, i).scheduleOn(&grp.pickNext()).start());\n }\n return Void{};\n }\n\n void stopAndJoin() {\n if (stopped_.test_and_set()) {\n XLOGF(DBG, \"coroutines pool {} is already stopped.\", fmt::ptr(this));\n return;\n }\n cancel_.requestCancellation();\n for (auto &future : futures_) {\n future.wait();\n }\n futures_.clear();\n XLOGF(INFO, \"coroutines pool {} is stopped\", fmt::ptr(this));\n }\n\n void enqueue(Job job, int8_t priority) { queue_.addWithPriority(std::move(job), priority); }\n\n private:\n CoTask run(Handler handler, size_t queueIndex) {\n while (true) {\n auto result = co_await co_awaitTry(co_withCancellation(cancel_.getToken(), queue_.co_dequeue()));\n if (UNLIKELY(result.template hasException())) {\n XLOGF(DBG, \"a coroutine in pool {} is stopped\", fmt::ptr(this));\n break;\n } else if (result.hasException()) {\n XLOGF(ERR, \"a coroutine in pool {} is stopped (exception: {})\", fmt::ptr(this), result.exception().what());\n break;\n }\n co_await handler(std::move(*result));\n }\n }\n\n const Config &config_;\n PriorityUnboundedQueue queue_;\n CancellationSource cancel_;\n std::vector> futures_;\n std::atomic_flag stopped_{false};\n};\n\n} // namespace hf3fs"], ["/3FS/src/storage/store/StorageTargets.h", "#pragma once\n\n#include \n\n#include \"chunk_engine/src/cxx.rs.h\"\n#include \"common/utils/CPUExecutorGroup.h\"\n#include \"common/utils/CoLockManager.h\"\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/RobinHood.h\"\n#include \"fbs/mgmtd/HeartbeatInfo.h\"\n#include \"fbs/storage/Common.h\"\n#include \"storage/service/TargetMap.h\"\n#include \"storage/store/StorageTarget.h\"\n\nnamespace hf3fs::test {\nstruct StorageTargetsHelper;\n}\n\nnamespace hf3fs::storage {\n\nclass StorageTargets {\n public:\n class Config : public ConfigBase {\n CONFIG_ITEM(target_paths, std::vector{}, [](auto &vec) { return !vec.empty(); });\n CONFIG_ITEM(target_num_per_path, 0u);\n CONFIG_HOT_UPDATED_ITEM(collect_all_fds, true);\n CONFIG_HOT_UPDATED_ITEM(space_info_cache_timeout, 5_s);\n CONFIG_HOT_UPDATED_ITEM(allow_disk_without_uuid, false);\n CONFIG_HOT_UPDATED_ITEM(create_engine_path, true);\n CONFIG_OBJ(storage_target, StorageTarget::Config);\n };\n\n class CreateConfig : public ConfigBase {\n CONFIG_ITEM(target_ids, std::vector{});\n CONFIG_ITEM(physical_file_count, 256u);\n CONFIG_ITEM(allow_disk_without_uuid, false);\n CONFIG_ITEM(allow_existing_targets, false);\n CONFIG_ITEM(chunk_size_list, (std::vector{512_KB, 1_MB, 2_MB, 4_MB, 16_MB, 64_MB}));\n CONFIG_ITEM(only_chunk_engine, false);\n };\n\n StorageTargets(const Config &config, AtomicallyTargetMap &targetMap)\n : config_(config),\n targetMap_(targetMap) {}\n ~StorageTargets();\n\n Result init(CPUExecutorGroup &executor);\n\n // create a batch of storage targets.\n Result create(const CreateConfig &createConfig);\n\n // create new storage target.\n Result create(const CreateTargetReq &req);\n\n // open a batch of storage targets.\n Result load(CPUExecutorGroup &executor);\n\n // load a target.\n Result loadTarget(const Path &targetPath);\n\n // get fd list.\n auto &fds() const { return fds_; }\n\n // get space info.\n Result> spaceInfos(bool force);\n\n // get target paths.\n auto &targetPaths() const { return targetPaths_; }\n\n // get manufacturers.\n auto &manufacturers() const { return manufacturers_; }\n\n // global file store.\n auto &globalFileStore() { return globalFileStore_; }\n\n // chunk engines.\n auto &engines() const { return engines_; }\n\n // remove target.\n Result removeChunkEngineTarget(ChainId chainId, uint32_t diskIndex) {\n auto &engine = *engines_[diskIndex];\n return ChunkEngine::removeAllChunks(engine, chainId);\n }\n\n private:\n friend struct test::StorageTargetsHelper;\n ConstructLog<\"storage::StorageTargets\"> constructLog_;\n const Config &config_;\n AtomicallyTargetMap &targetMap_;\n GlobalFileStore globalFileStore_;\n\n std::vector targetPaths_;\n std::vector manufacturers_;\n std::map pathToDiskIndex_;\n std::vector> engines_;\n\n CoLockManager<> targetLocks_;\n RelativeTime spaceInfoUpdatedTime_;\n std::vector cachedSpaceInfos_;\n\n std::vector fds_;\n};\n\n} // namespace hf3fs::storage\n"], ["/3FS/src/mgmtd/service/MgmtdState.h", "#pragma once\n\n#include \n\n#include \"MgmtdData.h\"\n#include \"common/utils/BackgroundRunner.h\"\n#include \"common/utils/CoroSynchronized.h\"\n#include \"common/utils/DefaultRetryStrategy.h\"\n#include \"core/app/ServerEnv.h\"\n#include \"core/user/UserStoreEx.h\"\n#include \"fbs/mgmtd/NodeInfo.h\"\n#include \"fbs/mgmtd/PersistentNodeInfo.h\"\n#include \"fdb/FDBRetryStrategy.h\"\n#include \"mgmtd/store/MgmtdStore.h\"\n\nnamespace hf3fs::mgmtd {\nstruct MgmtdConfig;\n\nusing ClientSessionMap = RHStringHashMap;\n\nstruct MgmtdState {\n MgmtdState(std::shared_ptr env, const MgmtdConfig &config);\n ~MgmtdState();\n\n UtcTime utcNow();\n Result validateClusterId(const core::ServiceOperation &ctx, std::string_view clusterId);\n CoTryTask validateAdmin(const core::ServiceOperation &ctx, const flat::UserInfo &userInfo);\n CoTask> currentLease(UtcTime now);\n flat::NodeId selfId() const;\n kv::FDBRetryStrategy createRetryStrategy();\n\n const std::shared_ptr env_;\n flat::NodeInfo selfNodeInfo_;\n flat::PersistentNodeInfo selfPersistentNodeInfo_;\n const MgmtdConfig &config_;\n\n MgmtdStore store_;\n core::UserStoreEx userStore_;\n\n class WriterMutexGuard {\n public:\n WriterMutexGuard(std::unique_lock mu, std::string_view m)\n : mu_(std::move(mu)),\n method_(m) {}\n WriterMutexGuard(WriterMutexGuard &&other) = default;\n ~WriterMutexGuard();\n\n private:\n std::unique_lock mu_;\n std::string_view method_;\n SteadyTime start_ = SteadyClock::now();\n };\n\n template \n CoTask coScopedLock() {\n auto mu = co_await writerMu_.co_scoped_lock();\n co_return WriterMutexGuard(std::move(mu), method);\n }\n\n CoroSynchronized data_;\n CoroSynchronized clientSessionMap_;\n\n private:\n // logical lock for protecting the whole processing of a writer operation\n // during which read-modify-write will be performed on `data_`\n folly::coro::Mutex writerMu_;\n};\n} // namespace hf3fs::mgmtd\n"], ["/3FS/src/client/storage/StorageClient.h", "#pragma once\n\n#include \n#include \n\n#include \"TargetSelection.h\"\n#include \"UpdateChannelAllocator.h\"\n#include \"client/mgmtd/ICommonMgmtdClient.h\"\n#include \"common/net/Client.h\"\n#include \"common/utils/Address.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/Result.h\"\n#include \"common/utils/Semaphore.h\"\n#include \"fbs/mgmtd/RoutingInfo.h\"\n#include \"fbs/storage/Common.h\"\n\nnamespace hf3fs::storage::client {\n\n/* Dynamic routing info for accessing a storage target */\n\nclass RoutingTarget {\n public:\n RoutingTarget(ChainId chainId)\n : chainId(chainId) {}\n\n ~RoutingTarget() {\n XLOGF_IF(DFATAL,\n channel.id != ChannelId{0},\n \"Leaked update channel, routing target: {}, stack trace: {}\",\n *this,\n folly::symbolizer::getStackTraceStr());\n }\n\n const hf3fs::storage::VersionedChainId getVersionedChainId() const { return {chainId, chainVer}; };\n\n public:\n ChainId chainId;\n ChainVer chainVer;\n flat::RoutingInfoVersion routingInfoVer;\n SlimTargetInfo targetInfo;\n UpdateChannel channel;\n};\n\n/* Read/write IOs */\n\nclass IOBuffer : public folly::MoveOnly {\n public:\n uint8_t *data() const { return const_cast(rdmabuf.ptr()); }\n\n size_t size() const { return rdmabuf.size(); }\n\n bool contains(const uint8_t *data, uint32_t len) const { return rdmabuf.contains(data, len); }\n\n net::RDMABuf subrange(size_t offset, size_t length) const { return rdmabuf.subrange(offset, length); }\n\n IOBuffer(hf3fs::net::RDMABuf rdmabuf)\n : rdmabuf(rdmabuf) {}\n\n private:\n const hf3fs::net::RDMABuf rdmabuf;\n\n friend class IOBase;\n friend class StorageClient;\n friend class StorageClientImpl;\n friend class StorageClientInMem;\n};\n\nclass IOBase : public folly::MoveOnly {\n private:\n IOBase(ChainId chainId,\n const ChunkId &chunkId,\n uint32_t offset,\n uint32_t length,\n uint32_t chunkSize,\n uint8_t *data,\n IOBuffer *buffer,\n void *userCtx)\n : routingTarget(chainId),\n chunkId(chunkId),\n offset(offset),\n length(length),\n chunkSize(chunkSize),\n data(data),\n buffer(buffer),\n userCtx(userCtx) {}\n\n public:\n Status status() const { return result.lengthInfo ? Status(StatusCode::kOK) : result.lengthInfo.error(); }\n status_code_t statusCode() const { return hf3fs::getStatusCode(result.lengthInfo); }\n uint32_t resultLen() const { return result.lengthInfo ? *result.lengthInfo : 0; }\n uint32_t dataLen() const { return length; }\n uint8_t *dataEnd() const { return data + length; }\n ChunkIdRange chunkRange() const { return {chunkId, chunkId, 1}; }\n uint32_t numProcessedChunks() const { return bool(result.lengthInfo); }\n void resetResult() { result = IOResult{}; }\n\n public:\n RoutingTarget routingTarget;\n ChunkId chunkId;\n const uint32_t offset;\n const uint32_t length;\n const uint32_t chunkSize;\n uint8_t *const data;\n IOBuffer *const buffer;\n void *const userCtx;\n IOResult result;\n\n friend class ReadIO;\n friend class WriteIO;\n};\n\nclass ReadIO : public IOBase {\n private:\n ReadIO(ChainId chainId,\n const ChunkId &chunkId,\n uint32_t offset,\n uint32_t length,\n uint8_t *data,\n IOBuffer *buffer,\n void *userCtx)\n : IOBase(chainId, chunkId, offset, length, 0 /*chunkSize*/, data, buffer, userCtx) {}\n\n friend class StorageClient;\n friend class StorageClientImpl;\n friend class StorageClientInMem;\n\n public:\n RequestId requestId;\n std::vector splittedIOs;\n};\n\nclass WriteIO : public IOBase {\n private:\n WriteIO(RequestId requestId,\n ChainId chainId,\n const ChunkId &chunkId,\n uint32_t offset,\n uint32_t length,\n uint32_t chunkSize,\n uint8_t *data,\n IOBuffer *buffer,\n void *userCtx)\n : IOBase(chainId, chunkId, offset, length, chunkSize, data, buffer, userCtx),\n requestId(requestId) {}\n\n public:\n const ChecksumInfo &localChecksum() const { return checksum; }\n\n private:\n friend class StorageClient;\n friend class StorageClientImpl;\n friend class StorageClientInMem;\n\n public:\n const RequestId requestId;\n ChecksumInfo checksum;\n};\n\n/* Read/write options */\n\nclass DebugOptions : public hf3fs::ConfigBase {\n CONFIG_HOT_UPDATED_ITEM(bypass_disk_io, false);\n CONFIG_HOT_UPDATED_ITEM(bypass_rdma_xmit, false);\n CONFIG_HOT_UPDATED_ITEM(inject_random_server_error, false);\n CONFIG_HOT_UPDATED_ITEM(inject_random_client_error, false);\n CONFIG_HOT_UPDATED_ITEM(max_num_of_injection_points, 100);\n\n public:\n DebugFlags toDebugFlags() const {\n#ifndef NDEBUG\n return DebugFlags{\n .injectRandomServerError = inject_random_server_error(),\n .injectRandomClientError = inject_random_client_error(),\n .numOfInjectPtsBeforeFail = (uint16_t)folly::Random::rand32(1, max_num_of_injection_points() + 1)};\n#else\n return DebugFlags{};\n#endif\n }\n};\n\nclass RetryOptions : public hf3fs::ConfigBase {\n CONFIG_HOT_UPDATED_ITEM(init_wait_time, Duration::zero()); // if set to zero, use the value from client config\n CONFIG_HOT_UPDATED_ITEM(max_wait_time, Duration::zero()); // if set to zero, use the value from client config\n CONFIG_HOT_UPDATED_ITEM(max_retry_time, Duration::zero()); // if set to zero, use the value from client config\n CONFIG_HOT_UPDATED_ITEM(retry_permanent_error, false);\n};\n\nclass ReadOptions : public hf3fs::ConfigBase {\n CONFIG_OBJ(debug, DebugOptions);\n CONFIG_OBJ(retry, RetryOptions);\n CONFIG_OBJ(targetSelection, TargetSelectionOptions);\n CONFIG_HOT_UPDATED_ITEM(enableChecksum, false);\n CONFIG_HOT_UPDATED_ITEM(allowReadUncommitted, false);\n\n public:\n bool verifyChecksum() const {\n#ifndef NDEBUG\n bool enabled = true;\n#else\n bool enabled = enableChecksum();\n#endif\n\n return enabled && !debug().bypass_disk_io() && !debug().bypass_rdma_xmit();\n }\n};\n\nclass WriteOptions : public hf3fs::ConfigBase {\n CONFIG_OBJ(debug, DebugOptions);\n CONFIG_OBJ(retry, RetryOptions);\n CONFIG_OBJ(targetSelection, TargetSelectionOptions); // for test only\n CONFIG_HOT_UPDATED_ITEM(enableChecksum, true);\n\n public:\n bool verifyChecksum() const {\n#ifndef NDEBUG\n bool enabled = true;\n#else\n bool enabled = enableChecksum();\n#endif\n\n return enabled && !debug().bypass_disk_io() && !debug().bypass_rdma_xmit();\n }\n};\n\nclass IoOptions : public ConfigBase {\n CONFIG_OBJ(read, ReadOptions);\n CONFIG_OBJ(write, WriteOptions);\n};\n\n/* queryLastChunk */\n\nclass QueryLastChunkOp : public folly::MoveOnly {\n private:\n QueryLastChunkOp(ChainId chainId, ChunkIdRange range, void *userCtx)\n : requestId(0),\n routingTarget(chainId),\n range(range),\n userCtx(userCtx) {}\n\n public:\n Status status() const { return result.statusCode ? Status(StatusCode::kOK) : result.statusCode.error(); }\n status_code_t statusCode() const { return hf3fs::getStatusCode(result.statusCode); }\n uint32_t resultLen() const { return 0; }\n uint32_t dataLen() const { return 0; }\n ChunkIdRange chunkRange() const { return range; }\n uint32_t numProcessedChunks() const { return result.statusCode ? result.totalNumChunks : 0; }\n void resetResult() { result = QueryLastChunkResult{}; }\n\n public:\n RequestId requestId;\n RoutingTarget routingTarget;\n const ChunkIdRange range;\n void *const userCtx;\n QueryLastChunkResult result;\n\n public:\n friend class StorageClient;\n friend class StorageClientImpl;\n friend class StorageClientInMem;\n};\n\n/* removeChunks */\n\nclass RemoveChunksOp : public folly::MoveOnly {\n private:\n RemoveChunksOp(RequestId requestId, ChainId chainId, ChunkIdRange range, void *userCtx)\n : requestId(requestId),\n routingTarget(chainId),\n range(range),\n userCtx(userCtx) {}\n\n public:\n Status status() const { return result.statusCode ? Status(StatusCode::kOK) : result.statusCode.error(); }\n status_code_t statusCode() const { return hf3fs::getStatusCode(result.statusCode); }\n uint32_t resultLen() const { return 0; }\n uint32_t dataLen() const { return 0; }\n ChunkIdRange chunkRange() const { return range; }\n uint32_t numProcessedChunks() const { return result.statusCode ? result.numChunksRemoved : 0; }\n void resetResult() { result = RemoveChunksResult{}; }\n\n public:\n const RequestId requestId;\n RoutingTarget routingTarget;\n const ChunkIdRange range;\n void *const userCtx;\n RemoveChunksResult result;\n\n friend class StorageClient;\n friend class StorageClientImpl;\n friend class StorageClientInMem;\n};\n\n/* truncateChunks */\n\nclass TruncateChunkOp : public folly::MoveOnly {\n private:\n TruncateChunkOp(RequestId requestId,\n ChainId chainId,\n const ChunkId &chunkId,\n uint32_t chunkLen,\n uint32_t chunkSize,\n bool onlyExtendChunk,\n void *userCtx)\n : requestId(requestId),\n routingTarget(chainId),\n chunkId(chunkId),\n chunkLen(chunkLen),\n chunkSize(chunkSize),\n onlyExtendChunk(onlyExtendChunk),\n userCtx(userCtx) {}\n\n public:\n Status status() const { return result.lengthInfo ? Status(StatusCode::kOK) : result.lengthInfo.error(); }\n status_code_t statusCode() const { return hf3fs::getStatusCode(result.lengthInfo); }\n uint32_t resultLen() const { return 0; }\n uint32_t dataLen() const { return 0; }\n ChunkIdRange chunkRange() const { return {chunkId, chunkId, 1}; }\n uint32_t numProcessedChunks() const { return bool(result.lengthInfo); }\n void resetResult() { result = IOResult{}; }\n\n public:\n const RequestId requestId;\n RoutingTarget routingTarget;\n const ChunkId chunkId;\n const uint32_t chunkLen;\n const uint32_t chunkSize;\n bool onlyExtendChunk;\n void *const userCtx;\n IOResult result; // result.lengthInfo == chunkLen if the op succeeds\n\n friend class StorageClient;\n friend class StorageClientImpl;\n friend class StorageClientInMem;\n};\n\n/* Storage client */\n\nclass StorageClient : public folly::MoveOnly {\n public:\n enum class ImplementationType {\n RPC,\n InMem,\n };\n\n enum class MethodType {\n batchRead = 1,\n batchWrite,\n read,\n write,\n queryLastChunk,\n removeChunks,\n truncateChunks,\n querySpaceInfo,\n createTarget,\n offlineTarget,\n removeTarget,\n queryChunk,\n getAllChunkMetadata,\n };\n\n class RetryConfig : public hf3fs::ConfigBase {\n public:\n CONFIG_HOT_UPDATED_ITEM(init_wait_time, 10_s);\n CONFIG_HOT_UPDATED_ITEM(max_wait_time, 30_s);\n CONFIG_HOT_UPDATED_ITEM(max_retry_time, 60_s);\n CONFIG_HOT_UPDATED_ITEM(max_failures_before_failover,\n 1U); // the max number of failed retries before switching to alternative targets\n\n public:\n RetryOptions mergeWith(RetryOptions options) const {\n if (options.init_wait_time() == Duration::zero()) options.set_init_wait_time(this->init_wait_time());\n if (options.max_wait_time() == Duration::zero()) options.set_max_wait_time(this->max_wait_time());\n if (options.max_retry_time() == Duration::zero()) options.set_max_retry_time(this->max_retry_time());\n return options;\n }\n };\n\n class OperationConcurrency : public hf3fs::ConfigBase {\n CONFIG_ITEM(max_batch_size, 128U);\n CONFIG_ITEM(max_batch_bytes, 4_MB);\n CONFIG_ITEM(max_concurrent_requests, 32U);\n CONFIG_ITEM(max_concurrent_requests_per_server, 8U);\n CONFIG_HOT_UPDATED_ITEM(random_shuffle_requests, true);\n CONFIG_HOT_UPDATED_ITEM(process_batches_in_parallel, true);\n };\n\n class HotLoadOperationConcurrency : public hf3fs::ConfigBase {\n CONFIG_HOT_UPDATED_ITEM(max_batch_size, 128U);\n CONFIG_HOT_UPDATED_ITEM(max_batch_bytes, 4_MB);\n CONFIG_HOT_UPDATED_ITEM(max_concurrent_requests, 32U);\n CONFIG_HOT_UPDATED_ITEM(max_concurrent_requests_per_server, 8U);\n CONFIG_HOT_UPDATED_ITEM(random_shuffle_requests, true);\n CONFIG_HOT_UPDATED_ITEM(process_batches_in_parallel, true);\n };\n\n class TrafficControlConfig : public hf3fs::ConfigBase {\n CONFIG_OBJ(read, HotLoadOperationConcurrency);\n CONFIG_OBJ(write, OperationConcurrency);\n CONFIG_OBJ(query, HotLoadOperationConcurrency);\n CONFIG_OBJ(remove, OperationConcurrency);\n CONFIG_OBJ(truncate, OperationConcurrency);\n\n public:\n size_t max_concurrent_updates() const {\n return write().max_concurrent_requests() * write().max_batch_size() +\n remove().max_concurrent_requests() * remove().max_batch_size() +\n truncate().max_concurrent_requests() * truncate().max_batch_size();\n }\n };\n\n class Config : public hf3fs::ConfigBase {\n public:\n CONFIG_OBJ(net_client, hf3fs::net::Client::Config);\n CONFIG_OBJ(net_client_for_updates, hf3fs::net::Client::Config);\n CONFIG_OBJ(retry, RetryConfig);\n CONFIG_OBJ(traffic_control, TrafficControlConfig);\n CONFIG_ITEM(implementation_type, ImplementationType::RPC);\n CONFIG_ITEM(chunk_checksum_type, ChecksumType::CRC32C);\n CONFIG_ITEM(create_net_client_for_updates, false);\n CONFIG_HOT_UPDATED_ITEM(check_overlapping_read_buffers, true);\n CONFIG_HOT_UPDATED_ITEM(check_overlapping_write_buffers, false);\n CONFIG_HOT_UPDATED_ITEM(max_inline_read_bytes, Size{0});\n CONFIG_HOT_UPDATED_ITEM(max_inline_write_bytes, Size{0});\n CONFIG_HOT_UPDATED_ITEM(max_read_io_bytes, Size{0});\n };\n\n public:\n StorageClient(const ClientId &clientId, const Config &config)\n : clientId_(clientId),\n config_(config) {}\n\n StorageClient()\n : StorageClient(ClientId::random(), kDefaultConfig) {}\n\n virtual ~StorageClient() = default;\n\n static std::shared_ptr create(ClientId clientId,\n const Config &config,\n hf3fs::client::ICommonMgmtdClient &mgmtdClient);\n\n virtual hf3fs::client::ICommonMgmtdClient &getMgmtdClient() = 0;\n\n virtual Result start() { return Void{}; }\n\n // If the user does not call `stop()', the client is stopped in destructor.\n virtual void stop() {}\n\n /* Read `length' bytes from `offset' of the chunk.\n The memory pointed by `data' should be large enough to store the data, fall in the range of\n the registered `buffer' and does not overlap with other IOs in the same batch (can be disable by\n setting `check_overlapping_read_buffers').\n */\n virtual ReadIO createReadIO(ChainId chainId,\n const ChunkId &chunkId,\n uint32_t offset,\n uint32_t length,\n uint8_t *data,\n IOBuffer *buffer,\n void *userCtx = nullptr);\n\n /* Write `length' bytes of data at `offset' of the chunk.\n The memory pointed by `data' should be large enough to store the data, fall in the range of\n the registered `buffer' and does not overlap with other IOs in the same batch (can be disable by\n setting `check_overlapping_write_buffers').\n If option `chunk_checksum_type' is not none, a checksum will be calculated for the write buffer.\n */\n virtual WriteIO createWriteIO(ChainId chainId,\n const ChunkId &chunkId,\n uint32_t offset,\n uint32_t length,\n uint32_t chunkSize,\n uint8_t *data,\n IOBuffer *buffer,\n void *userCtx = nullptr);\n\n /* Query the chunk with largest lexicographical id in range [chunkIdBegin, chunkIdEnd).\n `totalChunkLen' and `totalNumChunks' of chunks in the range are calculated and included in\n `QueryLastChunkResult'.\n If `moreChunksInRange' in `QueryLastChunkResult' is true, there exist more than\n `maxNumChunkIdsToProcess' chunks in range [chunkIdBegin, chunkIdEnd).\n */\n virtual QueryLastChunkOp createQueryOp(ChainId chainId,\n ChunkId chunkIdBegin,\n ChunkId chunkIdEnd,\n uint32_t maxNumChunkIdsToProcess = 1,\n void *userCtx = nullptr);\n\n /* Remove chunks in the range [chunkIdBegin, chunkIdEnd).\n Note that the `numChunksRemoved' in `RemoveChunksResult' might be less or equal to\n the number of chunks actually removed by storage service if the request fails and is\n automatically retried until it succeeds.\n If `moreChunksInRange' in `RemoveChunksResult' is true, there exist more than\n `maxNumChunkIdsToProcess' chunks in range [chunkIdBegin, chunkIdEnd).\n */\n virtual RemoveChunksOp createRemoveOp(ChainId chainId,\n ChunkId chunkIdBegin,\n ChunkId chunkIdEnd,\n uint32_t maxNumChunkIdsToProcess = 1,\n void *userCtx = nullptr);\n\n /* Truncate the chunk to `chunkLen' and create the chunk if it does not exist.\n `chunkSize' must equal to the size when the chunk was created if it already exists.\n A chunk of size `chunkSize' is created if does not exist.\n If `onlyExtendChunk' = true, extend the chunk if its length is less than `chunkLen';\n noop if its length is already greater or equal to `chunkLen'.\n The truncated/extended chunk size is returned as `lengthInfo' in the IO result;\n the user should check if the chunk size is expected.\n */\n virtual TruncateChunkOp createTruncateOp(ChainId chainId,\n const ChunkId &chunkId,\n uint32_t chunkLen,\n uint32_t chunkSize,\n bool onlyExtendChunk = false,\n void *userCtx = nullptr);\n\n // delete the returned IOBuffer object to deregister the buffer\n virtual Result registerIOBuffer(uint8_t *buf, size_t len);\n\n virtual CoTryTask batchRead(std::span readIOs,\n const flat::UserInfo &userInfo,\n const ReadOptions &options = ReadOptions(),\n std::vector *failedIOs = nullptr) = 0;\n\n virtual CoTryTask batchWrite(std::span writeIOs,\n const flat::UserInfo &userInfo,\n const WriteOptions &options = WriteOptions(),\n std::vector *failedIOs = nullptr) = 0;\n\n virtual CoTryTask read(ReadIO &readIO,\n const flat::UserInfo &userInfo,\n const ReadOptions &options = ReadOptions()) = 0;\n\n virtual CoTryTask write(WriteIO &writeIO,\n const flat::UserInfo &userInfo,\n const WriteOptions &options = WriteOptions()) = 0;\n\n // the following interfaces are assumed to be used at server-side (e.g. in meta service)\n\n virtual CoTryTask queryLastChunk(std::span ops,\n const flat::UserInfo &userInfo,\n const ReadOptions &options = ReadOptions(),\n std::vector *failedOps = nullptr) = 0;\n\n virtual CoTryTask removeChunks(std::span ops,\n const flat::UserInfo &userInfo,\n const WriteOptions &options = WriteOptions(),\n std::vector *failedOps = nullptr) = 0;\n\n virtual CoTryTask truncateChunks(std::span ops,\n const flat::UserInfo &userInfo,\n const WriteOptions &options = WriteOptions(),\n std::vector *failedOps = nullptr) = 0;\n\n virtual CoTryTask querySpaceInfo(NodeId nodeId) = 0;\n\n virtual CoTryTask createTarget(NodeId nodeId, const CreateTargetReq &req) = 0;\n\n virtual CoTryTask offlineTarget(NodeId nodeId, const OfflineTargetReq &req) = 0;\n\n virtual CoTryTask removeTarget(NodeId nodeId, const RemoveTargetReq &req) = 0;\n\n virtual CoTryTask>> queryChunk(const QueryChunkReq &req) = 0;\n\n virtual CoTryTask getAllChunkMetadata(const ChainId &chainId, const TargetId &targetId) = 0;\n\n protected:\n static const Config kDefaultConfig;\n const ClientId clientId_;\n const Config &config_;\n std::atomic_uint64_t nextRequestId_ = 1;\n};\n\n} // namespace hf3fs::storage::client\n\nFMT_BEGIN_NAMESPACE\n\ntemplate <>\nstruct formatter : formatter {\n template \n auto format(const hf3fs::storage::client::RoutingTarget &routingTarget, FormatContext &ctx) const {\n return fmt::format_to(ctx.out(),\n \"{}@{}@{}:{}@{}:{}#{}\",\n routingTarget.chainId,\n routingTarget.chainVer,\n routingTarget.routingInfoVer,\n routingTarget.targetInfo.targetId,\n routingTarget.targetInfo.nodeId,\n routingTarget.channel.id,\n routingTarget.channel.seqnum);\n }\n};\n\nFMT_END_NAMESPACE\n"], ["/3FS/src/common/utils/IdAllocator.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/kv/IKVEngine.h\"\n#include \"common/kv/ITransaction.h\"\n#include \"common/kv/WithTransaction.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/Result.h\"\n#include \"common/utils/String.h\"\n\nnamespace hf3fs {\n\n/**\n * Generate 64bits unique id range from 1 to uint64_t::max.\n *\n * The uniqueness of generated ids is guaranteed by transaction. IdAllocator can use multiple keys in FoundationDB to\n * avoid transaction conflict, strictly monotonically increasing isn't guaranteed when numShard > 1.\n */\ntemplate \nclass IdAllocator : folly::MoveOnly {\n public:\n IdAllocator(kv::IKVEngine &kvEngine, RetryStrategy strategy, String keyPrefix, uint8_t numShard)\n : kvEngine_(kvEngine),\n strategy_(strategy),\n keyPrefix_(std::move(keyPrefix)),\n numShard_(numShard),\n shardIdx_(0),\n shardList_() {\n XLOGF_IF(FATAL, numShard_ == 0, \"Shared shouldn't be zero!!!\");\n shardList_.reserve(numShard_);\n for (uint8_t i = 0; i < numShard_; i++) {\n shardList_.push_back(i);\n }\n std::shuffle(shardList_.begin(), shardList_.end(), std::mt19937_64(folly::Random::rand64()));\n }\n\n CoTryTask allocate() {\n auto txn = kvEngine_.createReadWriteTransaction();\n auto result = co_await kv::WithTransaction(strategy_).run(\n *txn,\n [&](kv::IReadWriteTransaction &txn) -> CoTryTask { co_return co_await allocateTxn(txn); });\n\n XLOGF_IF(ERR, result.hasError(), \"Failed to allocate ID, error {}\", result.error());\n co_return result;\n }\n\n CoTryTask> status() {\n auto txn = kvEngine_.createReadonlyTransaction();\n auto result = co_await kv::WithTransaction(strategy_).run(\n *txn,\n [&](kv::IReadOnlyTransaction &txn) -> CoTryTask> { co_return co_await statusTxn(txn); });\n\n XLOGF_IF(ERR, result.hasError(), \"Failed to query status, error {}\", result.error());\n co_return result;\n }\n\n private:\n std::string getShardKey(uint8_t shard) {\n XLOGF_IF(FATAL, shard > numShard_, \"{} > {}\", shard, numShard_);\n return fmt::format(\"{}-{}\", keyPrefix_, shard);\n }\n\n Result unpackShardValue(uint8_t shard, std::optional value) {\n uint64_t minVal = shard == 0 ? 1 : 0;\n uint64_t val = minVal;\n if (value.has_value()) {\n if (UNLIKELY(value->size() != sizeof(uint64_t))) {\n XLOGF(CRITICAL,\n \"Value of shard {} key {} has a unexpected length {} != 8.\",\n shard,\n getShardKey(shard),\n value->size());\n return makeError(StatusCode::kDataCorruption);\n }\n val = folly::Endian::little64(folly::loadUnaligned(value->data()));\n if (UNLIKELY(val < minVal)) {\n XLOGF(CRITICAL, \"Value of shard {} key {} has a val {} < minVal {}.\", shard, getShardKey(shard), val, minVal);\n return makeError(StatusCode::kDataCorruption);\n }\n }\n\n return val;\n }\n\n CoTryTask allocateTxn(kv::IReadWriteTransaction &txn) {\n auto shardIdx = shardIdx_++;\n auto shard = shardList_[shardIdx % shardList_.size()];\n auto shardKey = getShardKey(shard);\n\n // load old value\n auto getResult = co_await txn.get(shardKey);\n CO_RETURN_ON_ERROR(getResult);\n auto unpackResult = unpackShardValue(shard, getResult.value());\n CO_RETURN_ON_ERROR(unpackResult);\n uint64_t val = unpackResult.value();\n\n // set new value\n auto bytes = folly::bit_cast>(folly::Endian::little64(val + 1));\n auto setResult = co_await txn.set(shardKey, std::string_view(bytes.begin(), bytes.size()));\n CO_RETURN_ON_ERROR(setResult);\n\n XLOGF(DBG, \"IdAllocator allocate from shard {}, val {}, id {}\\n\", shard, val, val * numShard_ + shard);\n\n co_return (val * numShard_) + shard;\n }\n\n CoTryTask> statusTxn(kv::IReadOnlyTransaction &txn) {\n std::vector vec;\n for (uint8_t shard = 0; shard < numShard_; shard++) {\n auto shardKey = getShardKey(shard);\n auto getResult = co_await txn.snapshotGet(shardKey);\n CO_RETURN_ON_ERROR(getResult);\n auto unpackResult = unpackShardValue(shard, getResult.value());\n CO_RETURN_ON_ERROR(unpackResult);\n vec.push_back(unpackResult.value());\n }\n\n co_return vec;\n }\n\n kv::IKVEngine &kvEngine_;\n RetryStrategy strategy_;\n String keyPrefix_;\n uint8_t numShard_;\n std::atomic shardIdx_;\n std::vector shardList_;\n};\n\n} // namespace hf3fs\n"], ["/3FS/src/storage/store/ChunkMetaStore.h", "#pragma once\n\n#include \n#include \n#include \n\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/Path.h\"\n#include \"common/utils/UtcTime.h\"\n#include \"kv/KVStore.h\"\n#include \"storage/store/ChunkFileStore.h\"\n#include \"storage/store/ChunkMetadata.h\"\n#include \"storage/store/PhysicalConfig.h\"\n\nnamespace hf3fs::storage {\n\nclass ChunkMetaStore {\n public:\n class Config : public ConfigBase {\n CONFIG_HOT_UPDATED_ITEM(allocate_size, 256_MB, [](Size s) { return s && s % kMaxChunkSize == 0; });\n CONFIG_HOT_UPDATED_ITEM(recycle_batch_size, 256u, ConfigCheckers::checkPositive);\n CONFIG_HOT_UPDATED_ITEM(punch_hole_batch_size, 16u, ConfigCheckers::checkPositive);\n CONFIG_HOT_UPDATED_ITEM(removed_chunk_expiration_time, 3_d);\n CONFIG_HOT_UPDATED_ITEM(removed_chunk_force_recycled_time, 1_h);\n };\n\n ChunkMetaStore(const Config &config, ChunkFileStore &fileStore)\n : config_(config),\n fileStore_(fileStore),\n allocateState_(16) {}\n\n ~ChunkMetaStore();\n\n // create chunk meta store.\n Result create(const kv::KVStore::Config &config, const PhysicalConfig &targetConfig);\n\n // load chunk meta store.\n Result load(const kv::KVStore::Config &config,\n const PhysicalConfig &targetConfig,\n bool createIfMissing = false);\n\n // add new chunk size.\n Result addChunkSize(const std::vector &sizeList);\n\n // migrate chunk meta store.\n Result migrate(const kv::KVStore::Config &config, const PhysicalConfig &targetConfig);\n\n // get metadata of chunk. [thread-safe]\n Result get(const ChunkId &chunkId, ChunkMetadata &meta);\n\n // set metadata of chunk. [thread-safe]\n Result set(const ChunkId &chunkId, const ChunkMetadata &meta);\n\n // remove metadata of chunk. [thread-safe]\n Result remove(const ChunkId &chunkId, const ChunkMetadata &meta);\n\n // create a chunk. [thread-safe]\n Result createChunk(const ChunkId &chunkId,\n ChunkMetadata &meta,\n uint32_t chunkSize,\n folly::CPUThreadPoolExecutor &executor,\n bool allowToAllocate);\n\n // recycle a batch of chunks, return true if has more. [thread-safe]\n Result punchHole();\n\n // sync the LOG of kv.\n Result sync();\n\n // get used size.\n uint64_t usedSize() const { return std::max(int64_t(createdSize_.load() - removedSize_.load()), 0l); }\n\n // get reserved and unrecycled size.\n Result unusedSize(int64_t &reservedSize, int64_t &unrecycledSize);\n\n // get all uncommitted chunk ids.\n auto &uncommitted() { return uncommitted_; }\n\n // enable or disable emergency recycling.\n void setEmergencyRecycling(bool enable) { emergencyRecycling_ = enable; }\n\n // iterator.\n class Iterator {\n public:\n explicit Iterator(kv::KVStore::IteratorPtr it, std::string_view chunkIdPrefix);\n // seek a chunk id prefix.\n void seek(std::string_view chunkIdPrefix);\n // return valid or not.\n bool valid() const;\n // get current chunk id.\n ChunkId chunkId() const;\n // get current metadata.\n Result meta() const;\n // next metadata.\n void next();\n // check status.\n Result status() const;\n\n private:\n kv::KVStore::IteratorPtr it_;\n };\n Result iterator(std::string_view chunkIdPrefix = {});\n\n protected:\n Result checkSentinel(std::string_view key);\n\n Result getSize(std::string_view key, std::atomic &size);\n\n struct AllocateState {\n std::mutex createMutex;\n std::mutex recycleMutex;\n std::mutex allocateMutex;\n std::atomic loaded{};\n std::atomic allocating{};\n std::atomic recycling{};\n uint32_t chunkSize{};\n uint32_t allocateIndex{}; // createMutex.\n std::atomic startingPoint{}; // createMutex.\n std::atomic createdCount{}; // createMutex.\n std::atomic usedCount{}; // createMutex.\n std::atomic removedCount{};\n std::atomic recycledCount{}; // recycleMutex\n std::atomic reusedCount{}; // createMutex\n std::atomic holeCount{}; // recycleMutex\n std::atomic oldestRemovedTimestamp{}; // recycleMutex\n std::vector createdChunks; // createMutex\n std::vector recycledChunks; // createMutex\n robin_hood::unordered_map fileSize; // createMutex\n };\n void createAllocateState(uint32_t chunkSize);\n\n Result loadAllocateState(uint32_t chunkSize);\n\n Result allocateChunks(AllocateState &state, bool withLock = false);\n\n bool needRecycleRemovedChunks(AllocateState &state);\n\n Result recycleRemovedChunks(AllocateState &state, bool withLock = false);\n\n Result punchHoleRemovedChunks(AllocateState &state, uint64_t expirationUs);\n\n private:\n const Config &config_;\n ChunkFileStore &fileStore_;\n\n std::unique_ptr kv_;\n std::string sentinel_;\n std::string kvName_;\n bool hasSentinel_ = false;\n uint32_t physicalFileCount_ = 256;\n\n std::atomic createdSize_ = 0;\n std::atomic removedSize_ = 0;\n std::vector uncommitted_;\n\n std::atomic emergencyRecycling_ = false;\n\n folly::AtomicUnorderedInsertMap> allocateState_;\n};\n\n} // namespace hf3fs::storage\n"], ["/3FS/src/storage/aio/AioReadWorker.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"common/utils/BoundedQueue.h\"\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/Result.h\"\n#include \"storage/aio/AioStatus.h\"\n#include \"storage/aio/BatchReadJob.h\"\n#include \"storage/store/StorageTargets.h\"\n\nnamespace hf3fs::storage {\n\nclass AioReadWorker {\n public:\n enum class IoEngine {\n libaio,\n io_uring,\n random,\n };\n\n class Config : public ConfigBase {\n CONFIG_ITEM(num_threads, 32ul);\n CONFIG_ITEM(queue_size, 4096u);\n CONFIG_ITEM(max_events, 512u);\n CONFIG_ITEM(enable_io_uring, true);\n CONFIG_HOT_UPDATED_ITEM(min_complete, 128u);\n CONFIG_HOT_UPDATED_ITEM(wait_all_inflight, false); // deprecated.\n CONFIG_HOT_UPDATED_ITEM(inflight_control_offset, 128); // deprecated.\n CONFIG_HOT_UPDATED_ITEM(ioengine, IoEngine::libaio);\n\n public:\n inline bool useIoUring() const {\n if (!enable_io_uring()) {\n return false;\n }\n switch (ioengine()) {\n case IoEngine::io_uring:\n return true;\n case IoEngine::libaio:\n return false;\n case IoEngine::random:\n return folly::Random::rand32() & 1;\n }\n }\n };\n\n AioReadWorker(const Config &config)\n : config_(config),\n queue_(config.queue_size()),\n executors_(std::make_pair(config_.num_threads(), config_.num_threads()),\n std::make_shared(\"AioRead\")) {}\n ~AioReadWorker();\n\n CoTask enqueue(AioReadJobIterator job) { co_await queue_.co_enqueue(job); }\n\n Result start(const std::vector &fds, const std::vector &iovecs);\n\n Result stopAndJoin();\n\n protected:\n Result run(AioStatus &aioStatus, IoUringStatus &ioUringStatus);\n\n private:\n ConstructLog<\"storage::AioReadWorker\"> constructLog_;\n const Config &config_;\n BoundedQueue queue_;\n\n folly::CPUThreadPoolExecutor executors_;\n std::atomic initialized_{};\n folly::Synchronized, std::mutex> initResult_{Void{}};\n};\n\n} // namespace hf3fs::storage\n"], ["/3FS/src/meta/components/ChainAllocator.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"client/mgmtd/ICommonMgmtdClient.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/Result.h\"\n#include \"fbs/meta/Schema.h\"\n#include \"fbs/mgmtd/MgmtdTypes.h\"\n\nnamespace hf3fs::meta::server {\n\nclass ChainAllocator {\n public:\n ChainAllocator(std::shared_ptr mgmtdClient)\n : mgmtdClient_(std::move(mgmtdClient)) {}\n\n CoTryTask checkLayoutValid(const Layout &layout) {\n CO_RETURN_ON_ERROR(layout.valid(true));\n\n if (!layout.empty()) {\n auto routing = getRoutingInfo();\n\n const auto &chains = layout.getChainIndexList();\n for (auto index : chains) {\n auto ref = flat::ChainRef{layout.tableId, layout.tableVersion, index};\n if (auto chain = routing->getChain(ref); !chain) {\n XLOGF(ERR, \"Layout contains a not found ChainRef {}\", ref);\n co_return makeError(MetaCode::kInvalidFileLayout, fmt::format(\"{} not found\", ref));\n } else if (chain->targets.empty()) {\n XLOGF(ERR, \"Chain {} has no target\", chain->chainId);\n co_return makeError(MetaCode::kInvalidFileLayout, fmt::format(\"Chain {} has no target\", chain->chainId));\n }\n }\n }\n co_return Void{};\n }\n\n CoTryTask allocateChainsForLayout(Layout &layout) {\n co_return co_await allocateChainsForLayout(layout, [&](size_t chainCnt) {\n auto tableId = layout.tableId;\n auto stripeSize = layout.stripeSize;\n auto key = AllocType(tableId, stripeSize);\n auto guard = roundRobin_.lock();\n auto iter = guard->find(key);\n if (iter == guard->end()) {\n // start with random value\n auto initial = folly::Random::rand32(chainCnt) / stripeSize * stripeSize;\n iter = guard->insert({key, initial}).first;\n }\n auto res = (iter->second % chainCnt) + 1;\n iter->second = (iter->second + stripeSize) % chainCnt;\n return res;\n });\n }\n\n CoTryTask allocateChainsForLayout(Layout &layout, folly::Synchronized &chainAllocCounter) {\n co_return co_await allocateChainsForLayout(layout, [&](size_t chainCnt) {\n auto guard = chainAllocCounter.wlock();\n auto stripeSize = layout.stripeSize;\n if (*guard == (uint32_t)-1) {\n // start with random value\n *guard = folly::Random::rand32(chainCnt) / stripeSize * stripeSize;\n }\n // add and return.\n auto res = (*guard % chainCnt) + 1;\n *guard = (*guard + stripeSize) % chainCnt;\n return res;\n });\n }\n\n CoTryTask allocateChainsForLayout(Layout &layout, auto &&roundRobin) {\n CO_RETURN_ON_ERROR(co_await checkLayoutValid(layout));\n if (!layout.empty()) {\n co_return Void{};\n }\n\n auto tableId = layout.tableId;\n auto tableVersion = layout.tableVersion;\n\n auto routing = getRoutingInfo();\n const auto *table = routing->raw()->getChainTable(tableId, tableVersion);\n if (!table) {\n XLOGF(ERR, \"Failed to find ChainTable with {} and {}\", tableId, tableVersion);\n co_return makeError(MetaCode::kInvalidFileLayout,\n fmt::format(\"ChainTable with {} and {} not found\", tableId, tableVersion));\n } else if (!table->chainTableVersion) {\n XLOGF(ERR, \"Invalid table {} version {}\", tableId, tableVersion);\n co_return makeError(MetaCode::kInvalidFileLayout,\n fmt::format(\"Invalid chain table {} version {}\", tableId, tableVersion));\n }\n auto chainCnt = table->chains.size();\n if (chainCnt < layout.stripeSize || chainCnt == 0) {\n XLOGF(ERR,\n \"Failed to allocate for layout {}, chain table {} have only {} chains.\",\n layout,\n tableId.toUnderType(),\n chainCnt);\n co_return makeError(\n MetaCode::kInvalidFileLayout,\n fmt::format(\"try to allocate {} chains from {}, found {}\", layout.stripeSize, tableId, chainCnt));\n }\n auto chainBegin = roundRobin(chainCnt);\n layout.tableVersion = table->chainTableVersion;\n layout.chains = Layout::ChainRange(chainBegin, Layout::ChainRange::STD_SHUFFLE_MT19937, folly::Random::rand64());\n if (auto valid = layout.valid(false); valid.hasError()) {\n XLOGF(DFATAL, \"Layout is not valid after alloc {}, error {}\", layout, valid.error());\n CO_RETURN_ERROR(valid);\n }\n\n co_return Void{};\n }\n\n private:\n std::shared_ptr getRoutingInfo() { return mgmtdClient_->getRoutingInfo(); }\n\n using AllocType = std::pair;\n folly::Synchronized, std::mutex> roundRobin_;\n std::shared_ptr mgmtdClient_;\n};\n\n} // namespace hf3fs::meta::server\n"], ["/3FS/src/common/net/Processor.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"common/net/MessageHeader.h\"\n#include \"common/net/Network.h\"\n#include \"common/net/Transport.h\"\n#include \"common/net/Waiter.h\"\n#include \"common/serde/CallContext.h\"\n#include \"common/serde/MessagePacket.h\"\n#include \"common/serde/Serde.h\"\n#include \"common/serde/Services.h\"\n#include \"common/utils/CPUExecutorGroup.h\"\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/CoroutinesPool.h\"\n#include \"common/utils/DynamicCoroutinesPool.h\"\n#include \"common/utils/Uuid.h\"\n#include \"common/utils/ZSTD.h\"\n\nnamespace hf3fs::net {\n\nclass IOWorker;\n\nclass Processor {\n public:\n struct Config : public ConfigBase {\n // TODO: directly use CoroutinesPool::Config\n CONFIG_ITEM(max_processing_requests_num, 4096ul);\n CONFIG_ITEM(max_coroutines_num, 256ul);\n CONFIG_HOT_UPDATED_ITEM(enable_coroutines_pool, true);\n CONFIG_HOT_UPDATED_ITEM(response_compression_level, 1u);\n CONFIG_HOT_UPDATED_ITEM(response_compression_threshold, 128_KB);\n };\n\n struct Job {\n IOBufPtr buf;\n serde::MessagePacket<> packet;\n TransportPtr tr;\n };\n\n explicit Processor(serde::Services &serdeServices, CPUExecutorGroup &executor, const Config &config)\n : serdeServices_(serdeServices),\n executor_(executor),\n config_(config) {}\n\n void processMsg(MessageWrapper wrapper, TransportPtr tr) {\n auto num = processingRequestsNum(flags_.load(std::memory_order_acquire));\n if (UNLIKELY(num >= config_.max_processing_requests_num())) {\n XLOGF(WARN, \"Too many processing requests: {}, unpack message in current thread.\", num);\n unpackMsg(wrapper, tr);\n } else {\n executor_.pickNext().add(\n [this, wrapper = std::move(wrapper), tr = std::move(tr)]() mutable { unpackMsg(wrapper, tr); });\n }\n }\n\n void setCoroutinesPoolGetter(auto &&g) { coroutinesPoolGetter_ = std::forward(g); }\n\n Result start(std::string_view = {}) { return Void{}; }\n\n void stopAndJoin() {\n // Mark as stopped, and refuse new requests.\n auto flags = flags_.fetch_or(kStopFlag);\n while (processingRequestsNum(flags) != 0) {\n XLOGF(INFO, \"Waiting for {} requests to finish...\", processingRequestsNum(flags));\n std::this_thread::sleep_for(100ms);\n flags = flags_.load(std::memory_order_acquire);\n }\n }\n\n void setFrozen(bool frozen, bool isRDMA) {\n auto flags = (isRDMA ? kFrozenRDMA : kFrozenTCP);\n if (frozen) {\n flags_ |= flags;\n } else {\n flags_ &= ~flags;\n }\n }\n\n protected:\n void unpackMsg(MessageWrapper &wrapper, TransportPtr &tr) {\n while (wrapper.length()) {\n // 1. check the message is complete.\n if (UNLIKELY(!wrapper.headerComplete() || !wrapper.messageComplete())) {\n XLOGF(ERR,\n \"Message is not complete! {} < {}, peer: {}\",\n wrapper.length(),\n wrapper.headerComplete() ? wrapper.header().size : 0,\n tr->describe());\n tr->invalidate();\n return;\n }\n\n if (LIKELY(wrapper.isSerdeMessage())) {\n unpackSerdeMsg(wrapper.cloneMessage(), wrapper.header().checksum, tr);\n wrapper.next();\n continue;\n }\n\n XLOGF(ERR, \"Message is invalid\", tr->describe());\n tr->invalidate();\n return;\n }\n }\n\n Result decompressSerdeMsg(IOBufPtr &buf, TransportPtr &tr);\n\n void unpackSerdeMsg(IOBufPtr buf, uint32_t checksumIn, TransportPtr tr) {\n // 1. check checksum. (without timestamp part)\n bool isCompressed = MessageHeader::isCompressed(checksumIn);\n auto checksum = Checksum::calcSerde(buf->data(), buf->length(), isCompressed);\n if (UNLIKELY(checksumIn != checksum)) {\n XLOGF(ERR, \"checksum is not matched! {:X} != {:X}, peer: {}\", checksumIn, checksum, tr->describe());\n tr->invalidate();\n return;\n }\n // message is verified by checksum and serde deserialize.\n\n if (isCompressed) {\n auto result = decompressSerdeMsg(buf, tr);\n if (UNLIKELY(!result)) {\n return;\n }\n }\n\n auto view = std::string_view{reinterpret_cast(buf->data()), buf->length()};\n serde::MessagePacket<> packet;\n auto deserializeResult = serde::deserialize(packet, view);\n if (UNLIKELY(!deserializeResult)) {\n XLOGF(ERR, \"Message buffer deserialize failed {}!, peer: {}\", deserializeResult.error(), tr->describe());\n tr->invalidate();\n return;\n }\n\n // 2. check this message is request or response.\n if (packet.timestamp) {\n if (packet.isRequest()) {\n packet.timestamp->serverReceived = UtcClock::now().time_since_epoch().count();\n } else {\n packet.timestamp->clientReceived = UtcClock::now().time_since_epoch().count();\n }\n }\n if (packet.flags & serde::EssentialFlags::IsReq) {\n // is request.\n XLOGF(DBG, \"receive request {}:{}\", packet.serviceId, packet.methodId);\n tryToProcessSerdeRequest(std::move(buf), packet, std::move(tr));\n } else {\n // is response.\n XLOGF(DBG, \"receive response {}:{}\", packet.serviceId, packet.methodId);\n Waiter::instance().post(packet, std::move(buf));\n }\n }\n\n CoTask processSerdeRequest(IOBufPtr buf, serde::MessagePacket<> packet, TransportPtr tr) {\n // decrease the count in any case.\n auto guard = folly::makeGuard([&] { flags_ -= kCountInc; });\n\n (void)buf; // keep alive.\n auto &service = serdeServices_.getServiceById(packet.serviceId, tr->isRDMA());\n serde::CallContext ctx(packet, std::move(tr), service);\n if (packet.useCompress()) {\n ctx.responseOptions().compression = {config_.response_compression_level(),\n config_.response_compression_threshold()};\n }\n co_await ctx.handle();\n }\n\n void tryToProcessSerdeRequest(IOBufPtr buff, serde::MessagePacket<> &packet, TransportPtr tr) {\n auto flags = flags_.load(std::memory_order_acquire);\n if (UNLIKELY(needRefuse(flags))) {\n refuseSerdeRequest(packet, std::move(tr), flags);\n return;\n }\n if (UNLIKELY(isFrozen(flags, tr->isRDMA()))) {\n // do nothing and return.\n return;\n }\n\n flags = flags_.fetch_add(kCountInc);\n if (UNLIKELY(needRefuse(flags))) {\n refuseSerdeRequest(packet, std::move(tr), flags);\n flags_ -= kCountInc; // resume count.\n return;\n }\n\n if (coroutinesPoolGetter_) {\n coroutinesPoolGetter_(packet).enqueue(processSerdeRequest(std::move(buff), packet, std::move(tr)));\n } else {\n processSerdeRequest(std::move(buff), packet, std::move(tr)).scheduleOn(&executor_.pickNext()).start();\n }\n }\n\n void refuseSerdeRequest(serde::MessagePacket<> &packet, TransportPtr tr, size_t flags) {\n auto msg =\n fmt::format(\"Refuse requests, stopped: {}, processing: {}\", isStopped(flags), processingRequestsNum(flags));\n XLOG(WARN, msg);\n auto &service = serdeServices_.getServiceById(packet.serviceId, tr->isRDMA());\n serde::CallContext ctx(packet, std::move(tr), service);\n ctx.onError(makeError(RPCCode::kRequestRefused, msg));\n }\n\n inline bool needRefuse(size_t flags) const {\n return isStopped(flags) || processingRequestsNum(flags) >= config_.max_processing_requests_num();\n }\n inline bool isStopped(size_t flags) const { return flags & kStopFlag; }\n inline bool isFrozen(size_t flags, bool isRDMA) const { return flags & (isRDMA ? kFrozenRDMA : kFrozenTCP); }\n inline size_t processingRequestsNum(size_t flags) const { return flags / kCountInc; }\n\n private:\n serde::Services &serdeServices_;\n CPUExecutorGroup &executor_;\n const Config &config_;\n using CoroutinesPoolGetter = std::function &)>;\n CoroutinesPoolGetter coroutinesPoolGetter_{};\n\n constexpr static size_t kStopFlag = 1;\n constexpr static size_t kFrozenTCP = 2;\n constexpr static size_t kFrozenRDMA = 4;\n constexpr static size_t kCountInc = 8;\n std::atomic flags_{0};\n};\n\n} // namespace hf3fs::net\n"], ["/3FS/src/analytics/StructuredTraceLog.h", "#pragma once\n\n#include \n#include \n#include \n\n#include \"SerdeObjectWriter.h\"\n#include \"common/monitor/Recorder.h\"\n#include \"common/monitor/ScopedMetricsWriter.h\"\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/Path.h\"\n#include \"common/utils/SysResource.h\"\n#include \"common/utils/UtcTime.h\"\n\nnamespace hf3fs::analytics {\n\ntemplate \nclass StructuredTraceLog : public folly::MoveOnly {\n struct TraceMeta {\n SERDE_STRUCT_FIELD(timestamp, std::time_t{});\n SERDE_STRUCT_FIELD(hostname, String{});\n };\n\n struct StructuredTrace {\n SERDE_STRUCT_FIELD(trace_meta, TraceMeta{});\n SERDE_STRUCT_FIELD(_, SerdeType{});\n };\n\n using WriterType = SerdeObjectWriter;\n using WriterPtr = std::shared_ptr;\n\n public:\n class Config : public hf3fs::ConfigBase {\n public:\n CONFIG_ITEM(trace_file_dir, Path{\".\"});\n#ifndef NDEBUG\n CONFIG_HOT_UPDATED_ITEM(enabled, false);\n CONFIG_HOT_UPDATED_ITEM(dump_interval, 60_min);\n#else\n CONFIG_HOT_UPDATED_ITEM(enabled, true);\n CONFIG_HOT_UPDATED_ITEM(dump_interval, 30_s);\n#endif\n CONFIG_HOT_UPDATED_ITEM(max_num_writers, size_t{1}, ConfigCheckers::checkPositive);\n CONFIG_HOT_UPDATED_ITEM(max_row_group_length, size_t{100'000});\n };\n\n public:\n StructuredTraceLog(const Config &config)\n : config_(config),\n enabled_(config.enabled()),\n typename_(nameof::nameof_short_type()),\n hostname_(SysResource::hostname().value_or(\"unknown_host\")),\n latencyTagSet_({{\"tag\", typename_}, {\"instance\", fmt::to_string(fmt::ptr(this))}}),\n createLatency_(\"trace_log.create_latency\", latencyTagSet_),\n appendLatency_(\"trace_log.append_latency\", latencyTagSet_),\n flushLatency_(\"trace_log.flush_latency\", latencyTagSet_),\n maxNumWriters_(config.max_num_writers()) {\n onConfigUpdated_ = config_.addCallbackGuard([this]() {\n bool enabled = config_.enabled();\n if (enabled_ != enabled) {\n enableTraceLog(enabled);\n if (!enabled) flush(false /*async*/);\n }\n\n if (maxNumWriters_ != config_.max_num_writers()) {\n updateMaxNumWriters(config_.max_num_writers());\n }\n });\n\n uint64_t secsUntilFirstDump =\n folly::Random::rand64(config_.dump_interval().asSec().count() / 2, config_.dump_interval().asSec().count());\n nextDumpTime_ = microsecondsSinceEpoch(UtcClock::now() + std::chrono::seconds{secsUntilFirstDump});\n }\n\n ~StructuredTraceLog() { close(); }\n\n bool open() {\n auto writer = getOrCreateWriter();\n if (!writer) return false;\n writerPool_.enqueue(writer);\n return true;\n }\n\n std::shared_ptr newEntry(const SerdeType &init = SerdeType{}) {\n auto ptr = new SerdeType(init);\n return std::shared_ptr(ptr, [this](SerdeType *ptr) {\n this->append(*ptr);\n delete ptr;\n });\n }\n\n void append(const SerdeType &msg) {\n if (!enabled_) return;\n\n {\n monitor::ScopedLatencyWriter appendLatency(appendLatency_);\n StructuredTrace trace{\n .trace_meta = TraceMeta{.timestamp = UtcClock::secondsSinceEpoch(), .hostname = hostname_},\n ._ = msg,\n };\n\n WriterPtr writer = getOrCreateWriter();\n\n if (UNLIKELY(writer == nullptr)) {\n XLOGF(CRITICAL, \"Cannot get a writer of {} trace log in directory {}\", typename_, config_.trace_file_dir());\n enableTraceLog(false);\n return;\n }\n\n *writer << trace;\n auto writerOk = writer->ok();\n writerPool_.enqueue(std::move(writer));\n if (UNLIKELY(!writerOk)) enableTraceLog(false);\n }\n\n auto currentTime = microsecondsSinceEpoch(UtcClock::now());\n\n if (UNLIKELY(currentTime >= nextDumpTime_)) {\n nextDumpTime_ = currentTime + config_.dump_interval().asUs().count();\n flush(true /*async*/);\n }\n }\n\n void flush(bool async, bool shutdown = false) {\n auto running = dumpingTrace_.test_and_set();\n if (running) return;\n\n monitor::ScopedLatencyWriter flushLatency(flushLatency_);\n if (asyncFlush_.valid()) asyncFlush_.wait();\n\n asyncFlush_ = std::async(\n std::launch::async,\n [this](bool shutdown) {\n size_t numWritersToClose = numWriters_.load();\n auto now = UtcClock::now();\n\n XLOGF(INFO,\n \"Flushing {} {} log writers in directory {}\",\n numWritersToClose,\n typename_,\n config_.trace_file_dir());\n\n for (size_t i = 0; numWritersToClose > 0; i++) {\n // give up flushing old writers after trying for too many loops\n if (i >= 10 * maxNumWriters_) {\n break;\n }\n\n auto writer = writerPool_.dequeue();\n if (!writer) continue;\n\n if (writer->createTime() > now) {\n writerPool_.enqueue(writer);\n continue;\n }\n\n if (writer->ok()) {\n // add an empty trace at the end of log\n *writer << StructuredTrace{\n .trace_meta = {.timestamp = UtcClock::secondsSinceEpoch(), .hostname = hostname_}};\n }\n\n try {\n writer.reset();\n } catch (const std::exception &ex) {\n XLOGF(ERR,\n \"Failed to close {} log writer in directory {}, error: {}\",\n typename_,\n config_.trace_file_dir(),\n ex.what());\n }\n\n if (shutdown)\n numWriters_--;\n else\n writerPool_.enqueue(createNewWriter());\n\n numWritersToClose--;\n }\n\n if (numWritersToClose > 0) {\n XLOGF(WARN,\n \"Still have {} {} log writers not closed in directory {}\",\n numWritersToClose,\n typename_,\n config_.trace_file_dir());\n } else {\n XLOGF(INFO, \"Flushed {} trace log in directory {}\", typename_, config_.trace_file_dir());\n }\n },\n shutdown);\n\n if (!async) asyncFlush_.wait();\n dumpingTrace_.clear();\n }\n\n void close() {\n enableTraceLog(false);\n flush(false /*async*/, true /*shutdown*/);\n XLOGF(INFO, \"Closed {} trace log in directory {}\", typename_, config_.trace_file_dir());\n }\n\n private:\n uint64_t microsecondsSinceEpoch(const UtcTime &time) const {\n return std::chrono::duration_cast((time).time_since_epoch()).count();\n }\n\n WriterPtr getOrCreateWriter() {\n WriterPtr writer;\n if (writerPool_.try_dequeue(writer)) return writer;\n\n auto currentNumWriters = numWriters_.load();\n if (currentNumWriters < maxNumWriters_) {\n bool create = numWriters_.compare_exchange_strong(currentNumWriters, currentNumWriters + 1);\n if (create) return createNewWriter();\n }\n\n return writerPool_.dequeue();\n }\n\n WriterPtr createNewWriter() {\n monitor::ScopedLatencyWriter createLatency(createLatency_);\n auto timestamp = fmt::localtime(UtcClock::to_time_t(UtcClock::now()));\n Path logfilePath =\n config_.trace_file_dir() / Path{fmt::format(\"{:%Y-%m-%d}\", timestamp)} / Path{hostname_} /\n Path{\n fmt::format(\"{}.{}.{:%Y-%m-%d-%H-%M-%S}.{}.parquet\", typename_, hostname_, timestamp, nextLogFileIndex_++)};\n\n if (!boost::filesystem::exists(logfilePath.parent_path())) {\n boost::system::error_code err{};\n boost::filesystem::create_directories(logfilePath.parent_path(), err);\n if (UNLIKELY(err.failed())) {\n XLOGF(CRITICAL, \"Failed to create directory {}, error: {}\", logfilePath.parent_path(), err.message());\n return nullptr;\n }\n }\n\n XLOGF(INFO, \"Opening {} trace log: {}\", typename_, logfilePath);\n return WriterType::open(logfilePath, false /*append*/, config_.max_row_group_length());\n }\n\n void enableTraceLog(bool enable) {\n enabled_ = enable;\n XLOGF(INFO,\n \"{} {} trace log in directory {}\",\n enable ? \"Enabled\" : \"Disabled\",\n typename_,\n config_.trace_file_dir());\n }\n\n void updateMaxNumWriters(size_t newMaxNumWriters) {\n XLOGF(INFO,\n \"Update max num of writers from {} to {} for {} trace log in directory {}\",\n maxNumWriters_.load(),\n newMaxNumWriters,\n typename_,\n config_.trace_file_dir());\n bool doFlush = maxNumWriters_ > newMaxNumWriters;\n maxNumWriters_ = newMaxNumWriters;\n if (doFlush) flush(false /*async*/);\n }\n\n private:\n const Config &config_;\n bool enabled_ = false;\n const std::string typename_;\n const std::string hostname_;\n\n const monitor::TagSet latencyTagSet_;\n monitor::LatencyRecorder createLatency_;\n monitor::LatencyRecorder appendLatency_;\n monitor::LatencyRecorder flushLatency_;\n\n std::unique_ptr onConfigUpdated_;\n std::atomic_size_t maxNumWriters_;\n std::atomic_size_t numWriters_ = 0;\n std::atomic_size_t nextLogFileIndex_ = 1;\n folly::UnboundedQueue writerPool_;\n\n std::atomic_uint64_t nextDumpTime_;\n std::atomic_flag dumpingTrace_;\n std::future asyncFlush_;\n};\n\n} // namespace hf3fs::analytics\n"], ["/3FS/src/fbs/meta/Schema.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/app/ClientId.h\"\n#include \"common/serde/Serde.h\"\n#include \"common/serde/SerdeComparisons.h\"\n#include \"common/utils/MagicEnum.hpp\"\n#include \"common/utils/Path.h\"\n#include \"common/utils/Result.h\"\n#include \"common/utils/StrongType.h\"\n#include \"common/utils/UtcTimeSerde.h\"\n#include \"common/utils/Uuid.h\"\n#include \"fbs/core/user/User.h\"\n#include \"fbs/meta/Common.h\"\n#include \"fbs/mgmtd/ChainRef.h\"\n#include \"fbs/mgmtd/ChainTable.h\"\n#include \"fbs/mgmtd/MgmtdTypes.h\"\n#include \"fbs/mgmtd/RoutingInfo.h\"\n\n#define SETATTR_TIME_NOW hf3fs::UtcTime::fromMicroseconds(-1)\n\nnamespace hf3fs::meta {\n\nusing flat::ChainId;\nusing flat::ChainRef;\nusing flat::ChainTableId;\nusing flat::ChainTableVersion;\n\nstruct Acl {\n SERDE_STRUCT_FIELD(uid, Uid(0));\n SERDE_STRUCT_FIELD(gid, Gid(0));\n SERDE_STRUCT_FIELD(perm, Permission(0));\n SERDE_STRUCT_FIELD(iflags, IFlags(0));\n\n public:\n Acl() = default;\n Acl(Uid uid, Gid gid, Permission perm, IFlags iflags = IFlags(0))\n : uid(uid),\n gid(gid),\n perm(perm),\n iflags(iflags) {}\n\n static Acl root() { return Acl(Uid(0), Gid(0), Permission(0755), IFlags(FS_IMMUTABLE_FL)); }\n static Acl gcRoot() { return Acl(Uid(0), Gid(0), Permission(0700), IFlags(FS_IMMUTABLE_FL)); }\n\n Result checkPermission(const UserInfo &user, AccessType type) const;\n\n Result checkRecursiveRmPerm(const UserInfo &user, bool owner) const;\n\n bool operator==(const Acl &o) const { return serde::equals(*this, o); }\n};\n\nstruct Inode;\nstruct Layout {\n enum class Type {\n Empty,\n ChainRange,\n ChainList,\n };\n struct Empty {\n static constexpr auto kType = Type::Empty;\n using is_serde_copyable = void;\n std::string serdeToReadable() const { return \"empty\"; }\n static Result serdeFromReadable(std::string_view) { return Empty{}; }\n bool operator==(const Empty &) const { return true; }\n };\n\n struct ChainRange {\n enum Shuffle : uint8_t { NO_SHUFFLE = 0, STD_SHUFFLE_MT19937 };\n\n SERDE_STRUCT_FIELD(baseIndex, uint32_t(0));\n SERDE_STRUCT_FIELD(shuffle, Shuffle(0));\n SERDE_STRUCT_FIELD(seed, uint64_t(0));\n mutable folly::DelayedInit> chains;\n\n public:\n static constexpr auto kType = Type::ChainRange;\n ChainRange() = default;\n ChainRange(uint32_t baseIndex, Shuffle shuffle, uint64_t seed)\n : baseIndex(baseIndex),\n shuffle(shuffle),\n seed(seed),\n chains() {}\n ChainRange(const ChainRange &o)\n : ChainRange(o.baseIndex, o.shuffle, o.seed) {}\n ChainRange &operator=(const ChainRange &o) {\n if (&o != this) {\n new (this) ChainRange(o);\n }\n return *this;\n }\n\n std::span getChainIndexList(size_t stripe) const;\n bool operator==(const ChainRange &o) const { return serde::equals(*this, o); }\n };\n\n struct ChainList {\n SERDE_STRUCT_FIELD(chainIndexes, std::vector());\n\n public:\n static constexpr auto kType = Type::ChainList;\n bool operator==(const ChainList &o) const { return serde::equals(*this, o); }\n };\n\n // make sure uint64_t is used in file length/offset calculate\n class ChunkSize {\n public:\n using is_serde_copyable = void;\n ChunkSize(uint32_t val = 0)\n : val_(val) {}\n\n uint32_t u32() const { return val_; }\n uint64_t u64() const { return val_; }\n operator uint64_t() const { return val_; }\n constexpr uint32_t serdeToReadable() const { return val_; }\n static Result serdeFromReadable(uint32_t val) { return ChunkSize(val); }\n\n private:\n uint32_t val_;\n };\n static_assert(sizeof(ChunkSize) == sizeof(uint32_t));\n\n SERDE_STRUCT_FIELD(tableId, ChainTableId());\n SERDE_STRUCT_FIELD(tableVersion, ChainTableVersion());\n SERDE_STRUCT_FIELD(chunkSize, ChunkSize(0));\n SERDE_STRUCT_FIELD(stripeSize, uint32_t(0));\n SERDE_STRUCT_FIELD(chains, (std::variant{}));\n\n public:\n static Layout newEmpty(ChainTableId table, uint32_t chunk, uint32_t stripe);\n static Layout newEmpty(ChainTableId table, ChainTableVersion tableVer, uint32_t chunk, uint32_t stripe);\n static Layout newChainList(ChainTableId table,\n ChainTableVersion tableVer,\n uint32_t chunk,\n std::vector chains);\n static Layout newChainList(uint32_t chunk, std::vector chains);\n static Layout newChainRange(ChainTableId table,\n ChainTableVersion tableVer,\n uint32_t chunk,\n uint32_t stripe,\n uint32_t baseChainIndex);\n\n std::span getChainIndexList() const;\n ChainRef getChainOfChunk(const Inode &inode, size_t chunkIndex) const;\n bool empty() const { return std::holds_alternative(chains); }\n Result valid(bool allowEmpty) const;\n Type type() const {\n XLOGF_IF(FATAL, chains.valueless_by_exception(), \"Chains is valueless\");\n return folly::variant_match(chains, [](const auto &v) { return std::decay_t::kType; });\n }\n bool operator==(const Layout &o) const { return serde::equals(*this, o); }\n};\n\nenum class InodeType : uint8_t {\n File = 0,\n Directory,\n Symlink,\n};\n\nclass ChunkId {\n /**\n * Use big endian form to keep order.\n * format: [tenent id (0x00)] + [ unused 0x_00] + [ 64bits inode id ] + [ 16bits track id ] + [ 32bits chunk num ]\n */\n FOLLY_MAYBE_UNUSED std::array tenent_;\n FOLLY_MAYBE_UNUSED std::array reserved_;\n std::array inode_;\n FOLLY_MAYBE_UNUSED std::array track_; // reserve for multitrack files.\n std::array chunk_;\n\n public:\n // ChunkId(InodeId inode = InodeId(-1), uint32_t chunk = 0)\n // : ChunkId(inode, 0, chunk) {}\n // ChunkId()\n // : ChunkId(InodeId(-1), 0, 0) {}\n ChunkId(InodeId inode, uint16_t track, uint32_t chunk)\n : tenent_({0}),\n reserved_({0}),\n inode_(folly::bit_cast>(folly::Endian::big64(inode.u64()))),\n track_(folly::bit_cast>(folly::Endian::big16(track))),\n chunk_(folly::bit_cast>(folly::Endian::big32(chunk))) {}\n\n std::string pack() const { return std::string((char *)this, sizeof(ChunkId)); }\n static ChunkId unpack(std::string_view data) {\n ChunkId id(InodeId(-1), 0, 0);\n if (data.size() == sizeof(ChunkId)) {\n memcpy(&id, data.data(), sizeof(ChunkId));\n }\n return id;\n }\n static Result> range(InodeId inodeId, uint32_t chunkBegin = 0) {\n if (inodeId.u64() == std::numeric_limits::max()) {\n return makeError(MetaCode::kNotFile, \"InodeId is uint64_max\");\n }\n auto begin = ChunkId(inodeId, 0, chunkBegin);\n auto end = ChunkId(inodeId, 1, 0);\n return std::pair{begin, end};\n }\n\n InodeId inode() const { return InodeId(folly::Endian::big64(folly::bit_cast(inode_))); }\n uint16_t track() const { return folly::Endian::big16(folly::bit_cast(track_)); }\n // use uint64_t to prevent error when calculate file offset or length\n uint64_t chunk() const { return folly::Endian::big32(folly::bit_cast(chunk_)); }\n\n operator std::string() const { return pack(); }\n explicit operator bool() const { return *this != ChunkId(InodeId(-1), 0, 0); }\n bool operator==(const ChunkId &o) const { return memcmp(this, &o, sizeof(*this)) == 0; }\n};\nstatic_assert(sizeof(ChunkId) == 16);\n\nstruct VersionedLength {\n SERDE_STRUCT_FIELD(length, uint64_t(0));\n SERDE_STRUCT_FIELD(truncateVer, uint64_t(0));\n\n public:\n static std::optional mergeHint(std::optional h1,\n std::optional h2) {\n if (!h1 || !h2) {\n return std::nullopt;\n } else {\n return h1->length >= h2->length ? h1 : h2;\n }\n }\n\n bool operator==(const VersionedLength &o) const { return serde::equals(*this, o); }\n};\n\nstruct File {\n struct Flags : BitFlags {\n using Base = BitFlags;\n using Base::Base;\n static constexpr uint32_t kHasHole = 1;\n };\n SERDE_STRUCT_FIELD(length, uint64_t(0));\n SERDE_STRUCT_FIELD(truncateVer, uint64_t(0));\n SERDE_STRUCT_FIELD(layout, Layout());\n SERDE_STRUCT_FIELD(flags, Flags(0));\n SERDE_STRUCT_FIELD(dynStripe, uint32_t(0)); // dynStripe = 0 means dynamic stripe size is not enabled for this file\n\n public:\n File() = default;\n File(Layout layout, uint32_t dynStripe = 0)\n : layout(std::move(layout)),\n dynStripe(dynStripe) {}\n static constexpr auto kType = InodeType::File;\n Result valid() const { return layout.valid(false); }\n bool hasHole() const { return flags.contains(File::Flags::kHasHole); }\n Result getChunkId(InodeId id, uint64_t offset) const;\n Result getChainId(const Inode &inode,\n size_t offset,\n const flat::RoutingInfo &routingInfo,\n uint16_t track = 0) const;\n VersionedLength getVersionedLength() const { return VersionedLength{length, truncateVer}; }\n void setVersionedLength(VersionedLength v) {\n length = v.length;\n truncateVer = v.truncateVer;\n }\n bool operator==(const File &o) const { return serde::equals(*this, o); }\n};\n\nstruct Directory {\n struct Lock {\n SERDE_STRUCT_FIELD(client, ClientId(Uuid::zero(), \"\"));\n\n public:\n bool operator==(const Lock &o) const { return serde::equals(*this, o); }\n };\n\n SERDE_STRUCT_FIELD(parent, InodeId());\n SERDE_STRUCT_FIELD(layout, Layout());\n SERDE_STRUCT_FIELD(name, std::string());\n SERDE_STRUCT_FIELD(chainAllocCounter, uint32_t(-1));\n SERDE_STRUCT_FIELD(lock, std::optional());\n\n public:\n static constexpr auto kType = InodeType::Directory;\n Result valid() const { return layout.valid(true); }\n Result checkLock(const ClientId &client) const {\n if (lock && lock->client.uuid != client.uuid) {\n return makeError(MetaCode::kNoLock, fmt::format(\"locked by {}\", lock->client));\n }\n return Void{};\n }\n bool operator==(const Directory &o) const { return serde::equals(*this, o); }\n};\n\nstruct Symlink {\n SERDE_STRUCT_FIELD(target, Path());\n\n public:\n static constexpr auto kType = InodeType::Symlink;\n Result valid() const {\n if (target.empty()) return INVALID(\"target is empty\");\n return VALID;\n }\n bool operator==(const Symlink &o) const { return serde::equals(*this, o); }\n};\n\nstruct InodeData {\n SERDE_STRUCT_FIELD(type, (std::variant()));\n SERDE_STRUCT_FIELD(acl, Acl());\n SERDE_STRUCT_FIELD(nlink, uint16_t(1));\n // 2023/6/1 as default inode timestamps\n SERDE_STRUCT_FIELD(atime, UtcTime(std::chrono::microseconds(1685548800ull * 1000 * 1000)));\n SERDE_STRUCT_FIELD(ctime, UtcTime(std::chrono::microseconds(1685548800ull * 1000 * 1000)));\n SERDE_STRUCT_FIELD(mtime, UtcTime(std::chrono::microseconds(1685548800ull * 1000 * 1000)));\n\n public:\n InodeType getType() const {\n XLOGF_IF(FATAL, type.valueless_by_exception(), \"InodeType is valueless\");\n return folly::variant_match(type, [](const auto &v) { return std::decay_t::kType; });\n }\n\n#define INODE_TYPE_FUNC(type_name) \\\n bool is##type_name() const { return std::holds_alternative(type); } \\\n type_name &as##type_name() { \\\n XLOGF_IF(FATAL, type.valueless_by_exception(), \"InodeType is valueless\"); \\\n XLOGF_IF(FATAL, \\\n !std::holds_alternative(type), \\\n \"Inode type {} != \" #type_name, \\\n magic_enum::enum_name(getType())); \\\n return std::get(type); \\\n } \\\n const type_name &as##type_name() const { \\\n XLOGF_IF(FATAL, type.valueless_by_exception(), \"InodeType is valueless\"); \\\n XLOGF_IF(FATAL, \\\n !std::holds_alternative(type), \\\n \"Inode type {} != \" #type_name, \\\n magic_enum::enum_name(getType())); \\\n return std::get(type); \\\n }\n INODE_TYPE_FUNC(File)\n INODE_TYPE_FUNC(Directory)\n INODE_TYPE_FUNC(Symlink)\n#undef INODE_TYPE_FUNC\n\n Result valid() const {\n XLOGF_IF(FATAL, type.valueless_by_exception(), \"InodeType is valueless\");\n return folly::variant_match(type, [](const auto &v) { return v.valid(); });\n }\n bool operator==(const InodeData &o) const { return serde::equals(*this, o); }\n};\n\nstruct Inode : InodeData {\n SERDE_STRUCT_FIELD(id, InodeId());\n\n public:\n Inode() = default;\n explicit Inode(InodeId id)\n : Inode(id, {}) {}\n Inode(InodeId id, InodeData data)\n : InodeData(std::move(data)),\n id(id) {}\n InodeData &data() { return *this; }\n const InodeData &data() const { return *this; }\n Result valid() const { return data().valid(); }\n bool operator==(const Inode &o) const { return serde::equals(*this, o); }\n};\n\nstruct GcInfo {\n SERDE_STRUCT_FIELD(user, flat::Uid(0));\n SERDE_STRUCT_FIELD(origPath, Path());\n\n public:\n bool operator==(const GcInfo &o) const { return serde::equals(*this, o); }\n};\n\nstruct DirEntryData {\n SERDE_STRUCT_FIELD(id, InodeId());\n SERDE_STRUCT_FIELD(type, InodeType::File);\n SERDE_STRUCT_FIELD(dirAcl, std::optional());\n SERDE_STRUCT_FIELD(uuid, Uuid::zero());\n SERDE_STRUCT_FIELD(gcInfo, std::optional());\n\n public:\n#define INODE_TYPE_FUNC(type_name) \\\n bool is##type_name() const { return type == InodeType::type_name; }\n\n INODE_TYPE_FUNC(File)\n INODE_TYPE_FUNC(Directory)\n INODE_TYPE_FUNC(Symlink)\n#undef INODE_TYPE_FUNC\n\n Result valid() const {\n if (!magic_enum::enum_contains(type)) return INVALID(fmt::format(\"invalid type {}\", (int)type));\n if ((type == InodeType::Directory) != dirAcl.has_value())\n return INVALID(fmt::format(\"type {}, dirAcl {}\", (type == InodeType::Directory), dirAcl.has_value()));\n return VALID;\n }\n bool operator==(const DirEntryData &o) const { return serde::equals(*this, o); }\n};\n\nstruct DirEntry : DirEntryData {\n SERDE_STRUCT_FIELD(parent, InodeId());\n SERDE_STRUCT_FIELD(name, std::string());\n\n public:\n DirEntry() = default;\n DirEntry(InodeId parent, std::string name, DirEntryData data = {})\n : DirEntryData(std::move(data)),\n parent(parent),\n name(std::move(name)) {}\n DirEntryData &data() { return *this; }\n const DirEntryData &data() const { return *this; }\n Result valid() const { return data().valid(); }\n bool operator==(const DirEntry &o) const { return serde::equals(*this, o); }\n};\n\n} // namespace hf3fs::meta\n\ntemplate <>\nstruct hf3fs::serde::SerdeMethod {\n static constexpr std::string_view serdeToReadable(hf3fs::meta::InodeType t) { return magic_enum::enum_name(t); }\n};\n\nFMT_BEGIN_NAMESPACE\n\ntemplate <>\nstruct formatter : formatter {\n template \n auto format(hf3fs::meta::InodeType type, FormatContext &ctx) const {\n return fmt::format_to(ctx.out(), \"{}\", magic_enum::enum_name(type));\n }\n};\n\ntemplate <>\nstruct formatter : formatter {\n template \n auto format(hf3fs::meta::ChunkId chunk, FormatContext &ctx) const {\n return fmt::format_to(ctx.out(), \"{}-{}-{}\", chunk.inode(), chunk.track(), chunk.chunk());\n }\n};\n\ntemplate <>\nstruct formatter : formatter {\n template \n auto format(hf3fs::meta::Layout::ChunkSize chunk, FormatContext &ctx) const {\n return fmt::format_to(ctx.out(), \"{}\", (uint64_t)chunk);\n }\n};\n\ntemplate <>\nstruct formatter : formatter {\n template \n auto format(hf3fs::meta::VersionedLength v, FormatContext &ctx) const {\n return fmt::format_to(ctx.out(), \"{}@{}\", v.length, v.truncateVer);\n }\n};\n\nFMT_END_NAMESPACE\n"], ["/3FS/src/client/storage/StorageClientImpl.h", "#pragma once\n\n#include \n#include \n\n#include \"StorageClient.h\"\n#include \"StorageMessenger.h\"\n#include \"UpdateChannelAllocator.h\"\n#include \"common/net/Client.h\"\n#include \"common/utils/Address.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/Result.h\"\n#include \"fbs/storage/Common.h\"\n\nnamespace hf3fs::storage::client {\n\nclass ClientRequestContext;\n\nclass StorageClientImpl : public StorageClient {\n public:\n StorageClientImpl(const ClientId &clientId, const Config &config, hf3fs::client::ICommonMgmtdClient &mgmtdClient);\n\n ~StorageClientImpl() override;\n\n Result start() override;\n\n hf3fs::client::ICommonMgmtdClient &getMgmtdClient() override { return mgmtdClient_; }\n void stop() override;\n\n CoTryTask batchRead(std::span readIOs,\n const flat::UserInfo &userInfo,\n const ReadOptions &options = ReadOptions(),\n std::vector *failedIOs = nullptr) override;\n\n CoTryTask batchWrite(std::span writeIOs,\n const flat::UserInfo &userInfo,\n const WriteOptions &options = WriteOptions(),\n std::vector *failedIOs = nullptr) override;\n\n CoTryTask read(ReadIO &readIO,\n const flat::UserInfo &userInfo,\n const ReadOptions &options = ReadOptions()) override;\n\n CoTryTask write(WriteIO &writeIO,\n const flat::UserInfo &userInfo,\n const WriteOptions &options = WriteOptions()) override;\n\n CoTryTask queryLastChunk(std::span ops,\n const flat::UserInfo &userInfo,\n const ReadOptions &options = ReadOptions(),\n std::vector *failedOps = nullptr) override;\n\n CoTryTask removeChunks(std::span ops,\n const flat::UserInfo &userInfo,\n const WriteOptions &options = WriteOptions(),\n std::vector *failedOps = nullptr) override;\n\n CoTryTask truncateChunks(std::span ops,\n const flat::UserInfo &userInfo,\n const WriteOptions &options = WriteOptions(),\n std::vector *failedOps = nullptr) override;\n\n CoTryTask querySpaceInfo(NodeId nodeId) override;\n\n CoTryTask createTarget(NodeId nodeId, const CreateTargetReq &req) override;\n\n CoTryTask offlineTarget(NodeId nodeId, const OfflineTargetReq &req) override;\n\n CoTryTask removeTarget(NodeId nodeId, const RemoveTargetReq &req) override;\n\n CoTryTask>> queryChunk(const QueryChunkReq &req) override;\n\n CoTryTask getAllChunkMetadata(const ChainId &chainId, const TargetId &targetId) override;\n\n private:\n CoTryTask batchReadWithRetry(ClientRequestContext &requestCtx,\n const std::vector &readIOs,\n const flat::UserInfo &userInfo,\n const ReadOptions &options,\n std::vector &failedIOs);\n\n CoTryTask batchReadWithoutRetry(ClientRequestContext &requestCtx,\n const std::vector &readIOs,\n const flat::UserInfo &userInfo,\n const ReadOptions &options);\n\n CoTryTask batchWriteWithRetry(ClientRequestContext &requestCtx,\n const std::vector &writeIOs,\n const flat::UserInfo &userInfo,\n const WriteOptions &options,\n std::vector &failedIOs);\n\n CoTryTask batchWriteWithoutRetry(ClientRequestContext &requestCtx,\n const std::vector &writeIOs,\n const flat::UserInfo &userInfo,\n const WriteOptions &options);\n\n CoTryTask sendWriteRequest(ClientRequestContext &requestCtx,\n WriteIO *writeIO,\n const hf3fs::flat::NodeInfo &nodeInfo,\n const flat::UserInfo &userInfo,\n const WriteOptions &options);\n\n CoTryTask sendWriteRequestsSequentially(ClientRequestContext &requestCtx,\n const std::vector &writeIOs,\n std::shared_ptr routingInfo,\n NodeId nodeId,\n const flat::UserInfo &userInfo,\n const WriteOptions &options);\n\n CoTryTask queryLastChunkWithoutRetry(ClientRequestContext &requestCtx,\n const std::vector &ops,\n const flat::UserInfo &userInfo,\n const ReadOptions &options);\n\n CoTryTask removeChunksWithoutRetry(ClientRequestContext &requestCtx,\n const std::vector &ops,\n const flat::UserInfo &userInfo,\n const WriteOptions &options);\n\n CoTryTask truncateChunksWithoutRetry(ClientRequestContext &requestCtx,\n const std::vector &ops,\n const flat::UserInfo &userInfo,\n const WriteOptions &options);\n\n private:\n void setCurrentRoutingInfo(std::shared_ptr latestRoutingInfo);\n\n std::shared_ptr getCurrentRoutingInfo() { return currentRoutingInfo_.load(); }\n\n StorageMessenger &getStorageMessengerForUpdates() {\n return config_.create_net_client_for_updates() ? messengerForUpdates_ : messenger_;\n }\n\n template \n CoTryTask callMessengerMethod(StorageMessenger &messenger,\n ClientRequestContext &requestCtx,\n const hf3fs::flat::NodeInfo &nodeInfo,\n const Req &request);\n\n template \n CoTryTask sendBatchRequest(StorageMessenger &messenger,\n ClientRequestContext &requestCtx,\n std::shared_ptr routingInfo,\n const NodeId &nodeId,\n const BatchReq &batchReq,\n const std::vector &ops);\n\n private:\n class OperationConcurrencyLimit {\n public:\n OperationConcurrencyLimit(size_t maxConcurrentRequests, size_t maxConcurrentRequestsPerServer)\n : maxConcurrentRequests_(maxConcurrentRequests),\n maxConcurrentRequestsPerServer_(maxConcurrentRequestsPerServer),\n concurrencySemaphore_(maxConcurrentRequests_) {}\n\n OperationConcurrencyLimit(const OperationConcurrency &config)\n : OperationConcurrencyLimit(config.max_concurrent_requests(), config.max_concurrent_requests_per_server()) {}\n\n virtual ~OperationConcurrencyLimit() = default;\n\n hf3fs::Semaphore &getConcurrencySemaphore() { return concurrencySemaphore_; }\n\n virtual std::shared_ptr getPerServerSemaphore(const NodeId &nodeId) {\n return getPerServerSemaphore(nodeId, maxConcurrentRequestsPerServer_);\n }\n\n protected:\n std::shared_ptr getPerServerSemaphore(const NodeId &nodeId, size_t initTokens) {\n {\n std::shared_lock rlock(perServerSemaphoreMutex_);\n auto iter = perServerSemaphore_.find(nodeId);\n if (iter != perServerSemaphore_.end()) {\n return iter->second;\n }\n }\n\n std::unique_lock wlock(perServerSemaphoreMutex_);\n\n auto iter = perServerSemaphore_.find(nodeId);\n if (iter != perServerSemaphore_.end()) {\n return iter->second;\n }\n\n auto semaphore = std::make_shared(initTokens);\n perServerSemaphore_.emplace(nodeId, semaphore);\n return semaphore;\n }\n\n protected:\n const size_t maxConcurrentRequests_;\n const size_t maxConcurrentRequestsPerServer_;\n hf3fs::Semaphore concurrencySemaphore_;\n std::shared_mutex perServerSemaphoreMutex_; // protect the following maps\n std::unordered_map> perServerSemaphore_;\n };\n\n class HotLoadOperationConcurrencyLimit : public OperationConcurrencyLimit {\n public:\n HotLoadOperationConcurrencyLimit(const HotLoadOperationConcurrency &config)\n : OperationConcurrencyLimit(config.max_concurrent_requests(), config.max_concurrent_requests_per_server()),\n config_(config),\n onConfigUpdated_(config_.addCallbackGuard([this]() { updateUsableTokens(); })) {}\n\n std::shared_ptr getPerServerSemaphore(const NodeId &nodeId) override {\n return OperationConcurrencyLimit::getPerServerSemaphore(nodeId, config_.max_concurrent_requests_per_server());\n }\n\n private:\n void updateUsableTokens() {\n concurrencySemaphore_.changeUsableTokens(config_.max_concurrent_requests());\n\n std::shared_lock rlock(perServerSemaphoreMutex_);\n for (auto &[_, semaphore] : perServerSemaphore_) {\n semaphore->changeUsableTokens(config_.max_concurrent_requests_per_server());\n }\n }\n\n private:\n const HotLoadOperationConcurrency &config_;\n std::unique_ptr onConfigUpdated_;\n };\n\n private:\n bool clientStarted_;\n hf3fs::client::ICommonMgmtdClient &mgmtdClient_;\n StorageMessenger messenger_;\n StorageMessenger messengerForUpdates_;\n UpdateChannelAllocator chanAllocator_;\n folly::atomic_shared_ptr currentRoutingInfo_;\n\n HotLoadOperationConcurrencyLimit readConcurrencyLimit_;\n OperationConcurrencyLimit writeConcurrencyLimit_;\n HotLoadOperationConcurrencyLimit queryConcurrencyLimit_;\n OperationConcurrencyLimit removeConcurrencyLimit_;\n OperationConcurrencyLimit truncateConcurrencyLimit_;\n};\n\n} // namespace hf3fs::storage::client\n"], ["/3FS/src/meta/store/DirEntry.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/kv/ITransaction.h\"\n#include \"common/monitor/Recorder.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/Result.h\"\n#include \"common/utils/SerDeser.h\"\n#include \"fbs/core/user/User.h\"\n#include \"fbs/meta/Common.h\"\n#include \"fbs/meta/Schema.h\"\n#include \"fbs/meta/Service.h\"\n#include \"meta/store/Inode.h\"\n\nnamespace hf3fs::meta::server {\nusing hf3fs::kv::IReadOnlyTransaction;\nusing hf3fs::kv::IReadWriteTransaction;\n\nstruct DirEntryList;\n\nclass DirEntry : public meta::DirEntry {\n public:\n using Base = meta::DirEntry;\n using Base::Base;\n\n DirEntry(Base base)\n : Base(std::move(base)) {}\n\n static Result newUnpacked(const std::string_view key, const std::string_view value);\n\n static CoTryTask> snapshotLoad(IReadOnlyTransaction &txn,\n InodeId parent,\n std::string_view name);\n\n static CoTryTask> load(IReadOnlyTransaction &txn, InodeId parent, std::string_view name);\n\n static CoTryTask checkExist(IReadOnlyTransaction &txn, InodeId parent, std::string_view name) {\n co_return (co_await DirEntry::load(txn, parent, name)).then([](auto &v) { return v.has_value(); });\n }\n\n static DirEntry newFile(InodeId parent, std::string name, InodeId inode) {\n return meta::DirEntry(parent, name, {inode, InodeType::File});\n }\n static DirEntry newSymlink(InodeId parent, std::string name, InodeId inode) {\n return meta::DirEntry(parent, name, {inode, InodeType::Symlink});\n }\n static DirEntry newDirectory(InodeId parent, std::string name, InodeId inode, Acl acl) {\n return meta::DirEntry(parent, name, {inode, InodeType::Directory, acl});\n }\n static DirEntry root() {\n return meta::DirEntry(InodeId::root(), \".\", {InodeId::root(), InodeType::Directory, Acl::root()});\n }\n\n /** Key format: prefix + parent-InodeId.key + name */\n std::string packKey() const;\n static std::string packKey(InodeId parent, std::string_view name);\n Result unpackKey(const std::string_view key);\n\n // load inode from dir entry\n CoTryTask loadInode(IReadOnlyTransaction &txn) const;\n CoTryTask snapshotLoadInode(IReadOnlyTransaction &txn) const;\n CoTryTask addIntoReadConflict(IReadWriteTransaction &txn) const {\n#ifndef NDEBUG\n snapshotLoaded_ = false;\n#endif\n co_return co_await txn.addReadConflict(packKey());\n }\n CoTryTask store(IReadWriteTransaction &txn) const;\n CoTryTask remove(IReadWriteTransaction &txn, bool ignoreSnapshotCheck = false) const;\n\n private:\n friend struct DirEntryList;\n friend class MetaTestHelper;\n\n template \n static CoTryTask> loadImpl(IReadOnlyTransaction &txn, InodeId parent, std::string_view name);\n\n#ifndef NDEBUG\n mutable bool snapshotLoaded_ = false;\n#endif\n};\n\nstruct DirEntryList {\n std::vector entries;\n std::vector inodes;\n bool more;\n\n // (prev, end)\n static CoTryTask snapshotLoad(IReadOnlyTransaction &txn,\n InodeId parent,\n std::string_view prev,\n int32_t limit,\n bool loadInodes = false,\n size_t loadInodesConcurrent = 0);\n\n // (begin, end)\n static CoTryTask snapshotLoad(IReadOnlyTransaction &txn,\n InodeId parent,\n std::string_view begin,\n std::string_view end,\n int32_t limit,\n bool loadInodes = false,\n size_t loadInodesConcurrent = 0);\n\n static CoTryTask load(IReadWriteTransaction &txn, InodeId parent, std::string_view prev, int32_t limit);\n\n static CoTryTask checkEmpty(IReadWriteTransaction &txn, InodeId parent);\n\n // For recursive remove and move to the trash, permission checks are required.\n // However, because the directory may be very large, we may not able to check permissions for entire\n // directory tree. This method is best effort.\n static CoTryTask recursiveCheckRmPerm(IReadWriteTransaction &txn,\n InodeId parent,\n flat::UserInfo user,\n int32_t limit,\n size_t listBatchSize) {\n static monitor::CountRecorder failed(\"meta_server.recursive_check_rm_perm_failed\");\n auto guard = folly::makeGuard([&]() {\n failed.addSample(1, {{\"uid\", folly::to(user.uid.toUnderType())}});\n });\n\n auto queue = std::queue();\n queue.push(parent);\n while (!queue.empty()) {\n auto currDir = queue.front();\n queue.pop();\n\n auto prev = std::string();\n auto foundDir = false;\n auto numEntries = 0;\n while (true) {\n if (limit-- <= 0) {\n break;\n }\n auto list = co_await DirEntryList::snapshotLoad(txn, currDir, prev, std::max(listBatchSize, 32ul));\n CO_RETURN_ON_ERROR(list);\n numEntries += list->entries.size();\n for (auto &entry : list->entries) {\n prev = entry.name;\n if (!entry.isDirectory()) {\n continue;\n }\n foundDir = true;\n if ((int64_t)queue.size() < limit) {\n queue.push(entry.id);\n }\n auto &acl = *entry.dirAcl;\n if (auto res = acl.checkRecursiveRmPerm(user, false); res.hasError()) {\n auto msg = fmt::format(\"user {} recursive remove {}, found {} without permission, msg {}\",\n user.uid,\n parent,\n entry,\n res.error().message());\n XLOG(ERR, msg);\n co_return makeError(MetaCode::kNoPermission, msg);\n }\n }\n if (!list->more || (numEntries > 1024 && !foundDir)) {\n break;\n }\n }\n }\n guard.dismiss();\n co_return Void{};\n }\n\n DirEntry &entry(size_t i) { return entries.at(i); }\n const DirEntry &entry(size_t i) const { return entries.at(i); }\n\n const Inode &inode(size_t i) const { return inodes.at(i); }\n Inode &inode(size_t i) { return inodes.at(i); }\n\n operator ListRsp() && {\n ListRsp rsp;\n rsp.more = more;\n rsp.entries.reserve(entries.size());\n rsp.inodes.reserve(inodes.size());\n for (auto &entry : entries) {\n rsp.entries.emplace_back(std::move(entry));\n }\n for (auto &inode : inodes) {\n rsp.inodes.emplace_back(std::move(inode));\n }\n return rsp;\n }\n\n private:\n template \n static CoTryTask loadImpl(IReadOnlyTransaction &txn,\n InodeId parent,\n IReadOnlyTransaction::KeySelector begin,\n IReadOnlyTransaction::KeySelector end,\n int32_t limit,\n bool loadInodes,\n size_t loadInodesConcurrent);\n};\n\n} // namespace hf3fs::meta::server\n"], ["/3FS/src/common/monitor/Monitor.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"common/monitor/ClickHouseClient.h\"\n#include \"common/monitor/LogReporter.h\"\n#include \"common/monitor/MonitorCollectorClient.h\"\n#include \"common/monitor/Recorder.h\"\n#include \"common/monitor/Sample.h\"\n#include \"common/utils/Address.h\"\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/ObjectPool.h\"\n\nnamespace hf3fs::monitor {\n\nclass MonitorInstance;\nclass Collector {\n public:\n Collector();\n ~Collector();\n\n void add(const std::string &name, Recorder &var);\n void del(const std::string &name, Recorder &var);\n void collectAll(size_t bucketIndex, std::vector &samples, bool cleanInactive);\n\n private:\n void resize(size_t n);\n\n struct Impl;\n std::unique_ptr impl;\n\n friend class MonitorInstance;\n};\n\nclass Monitor {\n public:\n class ReporterConfig : public ConfigBase {\n CONFIG_VARIANT_TYPE(\"clickhouse\");\n CONFIG_OBJ(clickhouse, ClickHouseClient::Config);\n CONFIG_OBJ(log, LogReporter::Config);\n CONFIG_OBJ(monitor_collector, MonitorCollectorClient::Config);\n };\n\n class Config : public ConfigBase {\n CONFIG_OBJ_ARRAY(reporters, ReporterConfig, 4, [](auto &) { return 0; });\n CONFIG_ITEM(num_collectors, 1);\n CONFIG_HOT_UPDATED_ITEM(collect_period, 1_s);\n };\n\n static Result start(const Config &config, String hostnameExtra = {});\n static void stop();\n\n static std::unique_ptr createMonitorInstance();\n static MonitorInstance &getDefaultInstance();\n};\n\nclass MonitorInstance {\n public:\n ~MonitorInstance();\n Result start(const Monitor::Config &config, String hostnameExtra = {});\n void stop();\n\n size_t getCollectorCount() const { return collectorContexts_.size(); }\n\n Collector &getCollector() {\n static Collector collector;\n return collector;\n }\n\n private:\n static constexpr size_t kMaxNumSampleBatches = 60;\n using SampleBatch = std::vector;\n using SampleBatchPool = ObjectPool;\n\n struct CollectorContext {\n folly::ProducerConsumerQueue samplesQueue_ =\n folly::ProducerConsumerQueue(kMaxNumSampleBatches);\n\n size_t bucketIndex = 0;\n std::mutex mutex_;\n std::condition_variable collectorCond_;\n std::condition_variable reporterCond_;\n std::jthread collectThread_;\n std::jthread reportThread_;\n };\n\n void periodicallyCollect(CollectorContext &context, const Monitor::Config &config);\n void reportSamples(CollectorContext &context, std::vector> reporters);\n\n std::atomic stop_ = true;\n\n std::vector> collectorContexts_;\n};\n\n} // namespace hf3fs::monitor\n"], ["/3FS/src/common/net/ServiceGroup.h", "#pragma once\n\n#include \n#include \n#include \n\n#include \"common/net/IOWorker.h\"\n#include \"common/net/Listener.h\"\n#include \"common/net/Processor.h\"\n#include \"common/net/ThreadPoolGroup.h\"\n#include \"common/serde/ClientContext.h\"\n#include \"common/serde/Services.h\"\n#include \"common/utils/Address.h\"\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/Duration.h\"\n#include \"common/utils/Result.h\"\n\nnamespace hf3fs::net {\n\nclass ServiceGroup : public folly::MoveOnly {\n public:\n class Config : public ConfigBase {\n CONFIG_ITEM(services, std::set{});\n CONFIG_ITEM(use_independent_thread_pool, false);\n CONFIG_ITEM(network_type, Address::RDMA);\n CONFIG_HOT_UPDATED_ITEM(check_connections_interval, 60_s);\n CONFIG_HOT_UPDATED_ITEM(connection_expiration_time, 1_d);\n CONFIG_OBJ(io_worker, IOWorker::Config);\n CONFIG_OBJ(processor, Processor::Config);\n CONFIG_OBJ(listener, Listener::Config);\n };\n\n explicit ServiceGroup(const Config &config, ThreadPoolGroup &tpg);\n\n ~ServiceGroup();\n\n // add normal service.\n template \n Result addSerdeService(std::unique_ptr &&obj, std::optional type = {}) {\n return serdeServices_.addService(std::move(obj), type.value_or(config_.network_type()) == Address::RDMA);\n }\n\n // setup this group.\n Result setup();\n\n // start this group.\n Result start();\n\n // stop and wait.\n void stopAndJoin();\n\n // set processor frozen.\n void setFrozen(bool frozen = true) { processor_.setFrozen(frozen, config_.network_type() == Address::RDMA); }\n\n // get listening address list.\n auto &addressList() const { return listener_.addressList(); }\n\n // get service name list.\n auto &serviceNameList() const { return config_.services(); }\n\n // get io worker.\n auto &ioWorker() { return ioWorker_; }\n\n // set coroutines pool getter for processor.\n void setCoroutinesPoolGetter(auto &&g) { processor_.setCoroutinesPoolGetter(std::forward(g)); }\n\n protected:\n CoTask checkConnectionsRegularly();\n\n private:\n ConstructLog<\"net::ServiceGroup\"> constructLog_;\n const Config &config_;\n ThreadPoolGroup &tpg_;\n serde::Services serdeServices_;\n Processor processor_;\n IOWorker ioWorker_;\n Listener listener_;\n\n CancellationSource cancel_;\n folly::SemiFuture future_;\n};\n\n} // namespace hf3fs::net\n"], ["/3FS/src/storage/service/BufferPool.h", "#pragma once\n\n#include \n#include \n#include \n#include \n\n#include \"common/net/ib/RDMABuf.h\"\n#include \"common/utils/CPUExecutorGroup.h\"\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/ConstructLog.h\"\n#include \"common/utils/Size.h\"\n\nnamespace hf3fs::storage {\n\nstruct BufferIndex {\n uint32_t registerIndex;\n net::RDMABuf buffer;\n};\n\nclass BufferPool {\n public:\n class Config : public ConfigBase {\n CONFIG_ITEM(rdmabuf_size, 4_MB);\n CONFIG_ITEM(rdmabuf_count, 1024u);\n CONFIG_ITEM(big_rdmabuf_size, 64_MB);\n CONFIG_ITEM(big_rdmabuf_count, 64u);\n };\n BufferPool(const Config &config)\n : config_(config),\n rdmabufSize_(config_.rdmabuf_size()),\n semaphore_(config_.rdmabuf_count()),\n bigRdmabufSize_(config_.big_rdmabuf_size()),\n bigSemaphore_(config_.big_rdmabuf_count()) {}\n\n Result init(CPUExecutorGroup &executor);\n\n auto &iovecs() const { return iovecs_; }\n\n class Buffer {\n public:\n explicit Buffer(BufferPool &pool)\n : pool_(&pool) {}\n Buffer(const Buffer &) = delete;\n Buffer(Buffer &&other) = default;\n Buffer &operator=(Buffer &&other) = default;\n ~Buffer();\n\n Result tryAllocate(uint32_t size);\n\n CoTryTask allocate(uint32_t size);\n\n auto index() const { return indices_.back().registerIndex; }\n\n private:\n BufferPool *pool_{};\n std::vector indices_;\n net::RDMABuf current_;\n };\n auto get() { return Buffer{*this}; }\n\n void clear(CPUExecutorGroup &executor);\n\n protected:\n static Result> initBuffers(CPUExecutorGroup &executor,\n Size rdmabufSize,\n uint32_t rdmabufCount,\n uint32_t limit,\n std::vector &outBuffers);\n\n BufferIndex allocate();\n\n BufferIndex allocateBig();\n\n void deallocate(const BufferIndex &index);\n\n private:\n ConstructLog<\"storage::BufferPool\"> constructLog_;\n const Config &config_;\n Size rdmabufSize_;\n std::vector buffers_;\n std::vector iovecs_;\n folly::fibers::Semaphore semaphore_;\n folly::Synchronized, std::mutex> freeIndex_;\n\n Size bigRdmabufSize_;\n uint32_t bigBufferRegisterIndexStart_ = 0;\n folly::fibers::Semaphore bigSemaphore_;\n folly::Synchronized, std::mutex> bigFreeIndex_;\n};\n\n} // namespace hf3fs::storage\n"], ["/3FS/src/storage/store/ChunkStore.h", "#pragma once\n\n#include \n#include \n#include \n\n#include \"common/monitor/Recorder.h\"\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/FdWrapper.h\"\n#include \"common/utils/Path.h\"\n#include \"common/utils/Result.h\"\n#include \"common/utils/RobinHood.h\"\n#include \"storage/store/ChunkFileStore.h\"\n#include \"storage/store/ChunkMetaStore.h\"\n#include \"storage/store/ChunkMetadata.h\"\n\nnamespace hf3fs::storage {\n\nenum class PointQueryStrategy {\n NONE,\n CLASSIC,\n MODERN,\n};\n\nclass ChunkStore {\n public:\n class Config : public ConfigBase {\n CONFIG_OBJ(kv_store, kv::KVStore::Config);\n CONFIG_OBJ(file_store, ChunkFileStore::Config);\n CONFIG_OBJ(meta_store, ChunkMetaStore::Config);\n CONFIG_ITEM(mutex_num, 257u, ConfigCheckers::isPositivePrime);\n CONFIG_ITEM(kv_path, Path{});\n CONFIG_HOT_UPDATED_ITEM(migrate_kv_store, false);\n CONFIG_HOT_UPDATED_ITEM(force_persist, true);\n CONFIG_HOT_UPDATED_ITEM(point_query_strategy, PointQueryStrategy::NONE);\n };\n\n using Map = folly::ConcurrentHashMap;\n\n ChunkStore(const Config &config, GlobalFileStore &globalFileStore)\n : config_(config),\n fileStore_(config_.file_store(), globalFileStore),\n metaStore_(config_.meta_store(), fileStore_) {}\n\n ChunkMetaStore &chunkMetaStore() { return metaStore_; }\n\n // create chunk store.\n Result create(const PhysicalConfig &config);\n\n // load chunk store.\n Result load(const PhysicalConfig &config);\n\n // add new chunk size.\n Result addChunkSize(const std::vector &sizeList);\n\n // migrate meta store.\n Result migrate(const PhysicalConfig &config) { return metaStore_.migrate(config_.kv_store(), config); }\n\n // get meta of a chunk file.\n Result get(const ChunkId &chunkId);\n\n // create a new chunk file.\n Result createChunk(const ChunkId &chunkId,\n uint32_t chunkSize,\n ChunkInfo &chunkInfo,\n folly::CPUThreadPoolExecutor &executor,\n bool allowToAllocate);\n\n // set meta of a chunk file.\n Result set(const ChunkId &chunkId, const ChunkInfo &chunkInfo, bool persist = true);\n\n // remove a chunk file.\n Result remove(ChunkId chunkId, ChunkInfo &chunkInfo);\n\n // recycle a batch of chunks.\n Result punchHole() { return metaStore_.punchHole(); }\n\n // sync meta kv.\n Result sync() { return metaStore_.sync(); }\n\n // query chunks: the chunk ids in result are in reverse lexicographical order\n Result>> queryChunks(const ChunkIdRange &chunkIdRange);\n\n // list all chunk ids.\n Result getAllMetadata(ChunkMetaVector &metas);\n\n // get meta iterator.\n auto metaIterator() { return metaStore_.iterator(); }\n\n // get used size.\n uint64_t usedSize() const { return metaStore_.usedSize(); }\n\n // get reserved and unrecycled size.\n Result unusedSize(int64_t &reservedSize, int64_t &unrecycledSize) {\n return metaStore_.unusedSize(reservedSize, unrecycledSize);\n }\n\n // get all uncommitted chunk ids.\n const auto &uncommitted() { return metaStore_.uncommitted(); }\n\n // reset uncommitted chunk to committed state.\n Result resetUncommitted(ChainVer chainVer);\n\n // enable or disable emergency recycling.\n void setEmergencyRecycling(bool enable) { return metaStore_.setEmergencyRecycling(enable); }\n\n private:\n const Config &config_;\n ChunkFileStore fileStore_;\n ChunkMetaStore metaStore_;\n TargetId targetId_;\n monitor::TagSet tag_;\n static constexpr auto kShardsNum = 32u;\n std::array maps_;\n};\n\n} // namespace hf3fs::storage\n"], ["/3FS/src/fuse/IoRing.h", "#pragma once\n\n#include \n#include \n\n#include \"IovTable.h\"\n#include \"UserConfig.h\"\n#include \"client/storage/StorageClient.h\"\n#include \"common/utils/AtomicSharedPtrTable.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/Uuid.h\"\n#include \"fbs/meta/Schema.h\"\n#include \"lib/common/Shm.h\"\n\nnamespace hf3fs::fuse {\nstruct RcInode;\nstruct IoArgs {\n uint8_t bufId[16];\n size_t bufOff;\n\n uint64_t fileIid;\n size_t fileOff;\n\n uint64_t ioLen;\n\n const void *userdata;\n};\n\nstruct IoSqe {\n int32_t index;\n const void *userdata;\n};\n\nstruct IoCqe {\n int32_t index;\n int32_t reserved;\n int64_t result;\n const void *userdata;\n};\n\nclass IoRing;\n\nstruct IoRingJob {\n std::shared_ptr ior;\n int sqeProcTail;\n int toProc;\n};\n\n// we allow multiple io workers to process the same ioring, but different ranges\n// so 1 ioring can be used to submit ios processed in parallel\n// however, we don't allow multiple threads to prepare ios in the same ioring\n// or batches may be mixed and things may get ugly\nclass IoRing : public std::enable_shared_from_this {\n public:\n static int ringMarkerSize() {\n auto n = std::atomic_ref::required_alignment;\n return (4 + n - 1) / n * n;\n }\n // allocate 1 more slot for queue emptiness/fullness checking\n static int ioRingEntries(size_t bufSize) {\n auto n = ringMarkerSize();\n // n * 4 for sqe/cqe head/tail markers\n return (int)std::min((size_t)std::numeric_limits::max(),\n (bufSize - 4096 - n * 4 - sizeof(sem_t)) / (sizeof(IoArgs) + sizeof(IoCqe) + sizeof(IoSqe))) -\n 1;\n }\n static size_t bytesRequired(int entries) {\n auto n = ringMarkerSize();\n // n * 4 for sqe/cqe head/tail markers\n return n * 4 + sizeof(sem_t) + (sizeof(IoArgs) + sizeof(IoCqe) + sizeof(IoSqe)) * (entries + 1) + 4096;\n }\n\n public:\n using std::enable_shared_from_this::shared_from_this;\n\n // the shm arg is used to keep it from being destroyed when the iov link is removed\n IoRing(std::shared_ptr shm,\n std::string_view nm,\n const meta::UserInfo &ui,\n bool read,\n uint8_t *buf,\n size_t size,\n int iod,\n int prio,\n Duration to,\n uint64_t flags,\n bool owner = true)\n : name(nm),\n entries(ioRingEntries(size) + 1),\n ioDepth(iod),\n priority(prio),\n timeout(to),\n sqeHead_((int32_t *)buf),\n sqeTail_((int32_t *)(buf + ringMarkerSize())),\n cqeHead_((int32_t *)(buf + ringMarkerSize() * 2)),\n cqeTail_((int32_t *)(buf + ringMarkerSize() * 3)),\n sqeHead(*sqeHead_),\n sqeTail(*sqeTail_),\n cqeHead(*cqeHead_),\n cqeTail(*cqeTail_),\n ringSection((IoArgs *)(buf + ringMarkerSize() * 4)),\n cqeSection((IoCqe *)(ringSection + entries)),\n sqeSection((IoSqe *)(cqeSection + entries)),\n slots(entries - 1),\n shm_(std::move(shm)),\n userInfo_(ui),\n forRead_(read),\n flags_(flags) {\n XLOGF_IF(FATAL,\n (uintptr_t)(sqeSection + entries + sizeof(sem_t)) > (uintptr_t)(buf + size),\n \"sem has a bad address {}, after whole shm starts at {} with {} bytes\",\n (void *)(sqeSection + entries + sizeof(sem_t)),\n (void *)buf,\n size);\n auto sem = (sem_t *)(sqeSection + entries);\n if (owner) {\n sem_init(sem, 1, 0);\n }\n cqeSem.reset(sem);\n }\n std::vector jobsToProc(int maxJobs);\n int cqeCount() const { return (cqeHead.load() + entries - cqeTail.load()) % entries; }\n CoTask process(\n int spt,\n int toProc,\n storage::client::StorageClient &storageClient,\n const storage::client::IoOptions &storageIo,\n UserConfig &userConfig,\n std::function> &, const IoArgs *, const IoSqe *, int)> &&lookupFiles,\n std::function> &, const IoArgs *, const IoSqe *, int)> &&lookupBufs);\n\n public:\n bool addSqe(int idx, const void *userdata) {\n auto h = sqeHead.load();\n if ((h + 1) % entries == sqeTail.load()) {\n return false;\n }\n\n auto &sqe = sqeSection[h];\n sqe.index = idx;\n sqe.userdata = userdata;\n\n sqeHead.store((h + 1) % entries);\n\n return true;\n }\n bool sqeTailAfter(int a, int b) {\n auto h = sqeHead.load();\n if (a == h) { // caught up with head, must be the last\n return true;\n }\n auto ah = a > h, bh = b > h;\n if (ah == bh) { // both after or before head, bigger is after\n return a > b;\n } else { // the one before head is after\n return bh;\n }\n }\n\n public:\n std::string name;\n std::string mountName;\n int entries;\n int ioDepth;\n int priority;\n Duration timeout;\n\n private:\n int32_t *sqeHead_;\n int32_t *sqeTail_;\n int32_t *cqeHead_;\n int32_t *cqeTail_;\n std::optional lastCheck_;\n\n public:\n std::atomic_ref sqeHead;\n std::atomic_ref sqeTail;\n std::atomic_ref cqeHead;\n std::atomic_ref cqeTail;\n IoArgs *ringSection;\n IoCqe *cqeSection;\n IoSqe *sqeSection;\n std::unique_ptr> cqeSem{nullptr, [](sem_t *p) { sem_destroy(p); }};\n\n public:\n AvailSlots slots;\n\n private:\n int sqeCount() const { return (sqeHead.load() + entries - sqeProcTail_) % entries; }\n [[nodiscard]] bool addCqe(int idx, ssize_t res, const void *userdata) {\n auto h = cqeHead.load();\n if ((h + 1) % entries == cqeTail.load()) {\n return false;\n }\n\n auto &cqe = cqeSection[h];\n cqe.index = idx;\n cqe.result = res;\n cqe.userdata = userdata;\n\n cqeHead.store((h + 1) % entries);\n return true;\n }\n\n private: // for fuse\n std::shared_ptr shm_;\n meta::UserInfo userInfo_;\n bool forRead_;\n uint64_t flags_;\n std::mutex cqeMtx_; // when reporting cqes\n int sqeProcTail_{0};\n int processing_{0};\n std::deque sqeProcTails_; // tails claimed and processing\n std::set sqeDoneTails_; // tails done processing\n};\n\nstruct IoRingTable {\n void init(int cap) {\n for (int prio = 0; prio <= 2; ++prio) {\n auto sp = \"/\" + semOpenPath(prio);\n sems.emplace_back(sem_open(sp.c_str(), O_CREAT, 0666, 0), [sp](sem_t *p) {\n sem_close(p);\n sem_unlink(sp.c_str());\n });\n chmod(semPath(prio).c_str(), 0666);\n }\n ioRings = std::make_unique>(cap);\n }\n Result addIoRing(const Path &mountName,\n std::shared_ptr shm,\n std::string_view name,\n const meta::UserInfo &ui,\n bool forRead,\n uint8_t *buf,\n size_t size,\n int ioDepth,\n const hf3fs::lib::IorAttrs &attrs) {\n auto idxRes = ioRings->alloc();\n if (!idxRes) {\n return makeError(ClientAgentCode::kTooManyOpenFiles, \"too many io rings\");\n }\n\n auto idx = *idxRes;\n\n auto ior = std::make_shared<\n IoRing>(std::move(shm), name, ui, forRead, buf, size, ioDepth, attrs.priority, attrs.timeout, attrs.flags);\n ior->mountName = mountName.native();\n ioRings->table[idx].store(ior);\n\n return idx;\n }\n void rmIoRing(int idx) { ioRings->remove(idx); }\n std::vector>> sems;\n std::unique_ptr> ioRings;\n\n private:\n static std::string semOpenPath(int prio) {\n static std::vector semIds{Uuid::random(), Uuid::random(), Uuid::random()};\n return fmt::format(\"hf3fs-submit-ios.{}\", semIds[prio].toHexString());\n }\n\n public:\n static std::string semName(int prio) {\n return fmt::format(\"submit-ios{}\", prio == 1 ? \"\" : prio == 0 ? \".ph\" : \".pl\");\n }\n static Path semPath(int prio) { return Path(\"/dev/shm\") / (\"sem.\" + semOpenPath(prio)); }\n static meta::Inode lookupSem(int prio) {\n static const std::vector inodes{\n {meta::InodeId{meta::InodeId::iovDir().u64() - 1},\n meta::InodeData{meta::Symlink{semPath(0)}, meta::Acl{meta::Uid{0}, meta::Gid{0}, meta::Permission{0666}}}},\n {meta::InodeId{meta::InodeId::iovDir().u64() - 2},\n meta::InodeData{meta::Symlink{semPath(1)}, meta::Acl{meta::Uid{0}, meta::Gid{0}, meta::Permission{0666}}}},\n {meta::InodeId{meta::InodeId::iovDir().u64() - 3},\n meta::InodeData{meta::Symlink{semPath(2)}, meta::Acl{meta::Uid{0}, meta::Gid{0}, meta::Permission{0666}}}}};\n\n return inodes[prio];\n }\n};\n} // namespace hf3fs::fuse\n"], ["/3FS/src/fbs/meta/Utils.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/app/NodeId.h\"\n#include \"common/monitor/Recorder.h\"\n#include \"common/monitor/Sample.h\"\n#include \"common/serde/Serde.h\"\n#include \"common/utils/Duration.h\"\n#include \"common/utils/MurmurHash3.h\"\n#include \"common/utils/Reflection.h\"\n#include \"common/utils/Result.h\"\n#include \"common/utils/SerDeser.h\"\n#include \"common/utils/Status.h\"\n#include \"common/utils/StatusCode.h\"\n#include \"common/utils/TypeTraits.h\"\n#include \"common/utils/Uuid.h\"\n#include \"fbs/core/user/User.h\"\n#include \"fbs/meta/Common.h\"\n#include \"fbs/meta/Schema.h\"\n#include \"fbs/meta/Service.h\"\n#include \"fbs/mgmtd/ChainRef.h\"\n#include \"fbs/mgmtd/RoutingInfo.h\"\n#include \"fmt/core.h\"\n\nnamespace hf3fs::meta {\n\nstruct ErrorHandling {\n static bool success(const auto &result) { return !result.hasError() || success(result.error()); }\n\n // The operation was performed successfully, or an expected error code was returned\n static bool success(const Status &status) {\n auto code = status.code();\n switch (StatusCode::typeOf(code)) {\n case StatusCodeType::Common:\n switch (code) {\n case StatusCode::kOK:\n case StatusCode::kInvalidArg:\n case StatusCode::kAuthenticationFail:\n return true;\n default:\n return false;\n }\n case StatusCodeType::Meta:\n switch (code) {\n case MetaCode::kNotFound:\n case MetaCode::kNotEmpty:\n case MetaCode::kNotDirectory:\n case MetaCode::kTooManySymlinks:\n case MetaCode::kIsDirectory:\n case MetaCode::kExists:\n case MetaCode::kNoPermission:\n case MetaCode::kNotFile:\n case MetaCode::kInvalidFileLayout:\n case MetaCode::kMoreChunksToRemove:\n case MetaCode::kNameTooLong:\n return true;\n default:\n return (code >= MetaCode::kExpected && code < MetaCode::kRetryable);\n }\n default:\n return false;\n }\n }\n\n static bool retryable(const Status &status) {\n auto code = status.code();\n switch (StatusCode::typeOf(code)) {\n case StatusCodeType::Common:\n return false;\n case StatusCodeType::Meta:\n switch (code) {\n case MetaCode::kNotFound:\n case MetaCode::kNotEmpty:\n case MetaCode::kNotDirectory:\n case MetaCode::kTooManySymlinks:\n case MetaCode::kIsDirectory:\n case MetaCode::kExists:\n case MetaCode::kNoPermission:\n case MetaCode::kInconsistent:\n case MetaCode::kNotFile:\n case MetaCode::kBadFileSystem:\n case MetaCode::kInvalidFileLayout:\n case MetaCode::kFileHasHole:\n case MetaCode::kNameTooLong:\n case MetaCode::kRequestCanceled:\n case MetaCode::kFoundBug:\n return false;\n case MetaCode::kOTruncFailed:\n case MetaCode::kMoreChunksToRemove:\n case MetaCode::kBusy:\n case MetaCode::kInodeIdAllocFailed:\n return true;\n default:\n return code < MetaCode::kNotRetryable;\n }\n case StatusCodeType::StorageClient:\n switch (code) {\n case StorageClientCode::kChunkNotFound:\n case StorageClientCode::kChecksumMismatch:\n case StorageClientCode::kReadOnlyServer:\n case StorageClientCode::kFoundBug:\n return false;\n default:\n return true;\n }\n default:\n return code != RPCCode::kInvalidMethodID;\n }\n }\n\n static bool serverError(const Status &status) {\n switch (StatusCode::typeOf(status.code())) {\n case StatusCodeType::Transaction:\n return status.code() == TransactionCode::kNetworkError;\n case StatusCodeType::RPC:\n return true;\n default:\n return false;\n }\n }\n\n static bool needPruneSession(const Status &error) {\n auto code = error.code();\n switch (StatusCode::typeOf(code)) {\n case StatusCodeType::Transaction:\n return code == TransactionCode::kMaybeCommitted;\n case StatusCodeType::Meta:\n return code == MetaCode::kOTruncFailed;\n case StatusCodeType::RPC:\n switch (code) {\n case RPCCode::kSendFailed:\n case RPCCode::kConnectFailed:\n case RPCCode::kIBInitFailed:\n case RPCCode::kInvalidMethodID:\n return false;\n default:\n return true;\n }\n default:\n return false;\n }\n }\n};\n\nclass OperationRecorder {\n public:\n OperationRecorder(std::string_view prefix)\n : total_(fmt::format(\"{}_total\", prefix)),\n failed_(fmt::format(\"{}_failed\", prefix)),\n running_(fmt::format(\"{}_running\", prefix), false),\n code_(fmt::format(\"{}_code\", prefix)),\n latency_(fmt::format(\"{}_latency\", prefix)),\n retry_(fmt::format(\"{}_retry\", prefix)),\n idempotent_(fmt::format(\"{}_idempotent\", prefix)),\n duplicate_(fmt::format(\"{}_duplicate\", prefix)) {}\n\n static OperationRecorder &server() {\n static OperationRecorder recorder(\"meta_server.op\");\n return recorder;\n }\n\n static OperationRecorder &client() {\n static OperationRecorder recorder(\"meta_client.op\");\n return recorder;\n }\n\n class Guard {\n public:\n Guard(OperationRecorder &recorder, std::string_view op, flat::Uid user)\n : recorder_(recorder),\n op_(\"instance\", std::string(op)),\n user_(\"uid\", folly::to((int32_t)user.toUnderType())),\n begin_(RelativeTime::now()) {\n begin_ = RelativeTime::now();\n recorder_.running_.addSample(1, {{op_}});\n }\n\n ~Guard() {\n auto op = monitor::TagSet{op_};\n auto opUser = monitor::TagSet{{op_, user_}};\n auto latency = RelativeTime::now() - begin_;\n recorder_.total_.addSample(1, opUser);\n if (!succ_) {\n recorder_.failed_.addSample(1, opUser);\n recorder_.code_.addSample(1, {{\"tag\", folly::to(code_.value_or(0))}, user_});\n } else {\n if (code_) {\n recorder_.code_.addSample(1, {{\"tag\", folly::to(*code_)}, user_});\n }\n }\n recorder_.running_.addSample(-1, op);\n recorder_.latency_.addSample(latency, op);\n recorder_.retry_.addSample(retry_, op);\n if (duplicate_) {\n recorder_.duplicate_.addSample(1, op);\n }\n }\n\n void finish(const auto &result, bool duplicate = false) {\n duplicate_ = duplicate;\n succ_ = ErrorHandling::success(result);\n code_ = result.hasError() ? result.error().code() : 0;\n }\n\n void finish(const Status &status, bool duplicate = false) {\n duplicate_ = duplicate;\n succ_ = ErrorHandling::success(status) || status.code() == MetaCode::kRequestCanceled;\n code_ = status.code();\n }\n\n int &retry() { return retry_; }\n\n private:\n using Tag = std::pair;\n OperationRecorder &recorder_;\n Tag op_;\n Tag user_;\n RelativeTime begin_;\n std::optional code_;\n bool succ_ = false;\n int retry_ = 1;\n bool duplicate_ = false;\n };\n\n void addIdempotentCount() { idempotent_.addSample(1); }\n\n private:\n monitor::CountRecorder total_;\n monitor::CountRecorder failed_;\n monitor::CountRecorder running_;\n monitor::CountRecorder code_;\n monitor::LatencyRecorder latency_;\n monitor::DistributionRecorder retry_;\n monitor::CountRecorder idempotent_;\n monitor::CountRecorder duplicate_;\n};\n\nstruct Weight : std::array {\n static Weight calculate(flat::NodeId node, InodeId inodeId) {\n // Note: don't change this\n auto key = Serializer::serRawArgs((uint64_t)node.toUnderType(), inodeId.u64());\n return hash(key.data(), key.size());\n }\n\n static flat::NodeId select(const std::vector &nodes, InodeId inodeId) {\n return selectImpl(nodes, inodeId);\n }\n\n static Weight calculate(flat::NodeId node, Uuid clientId) {\n // todo: maybe should change to client host name?\n auto key = Serializer::serRawArgs((uint64_t)node.toUnderType(), clientId.data);\n return hash(key.data(), key.size());\n }\n\n static flat::NodeId select(const std::vector &nodes, Uuid clientId) {\n return selectImpl(nodes, clientId);\n }\n\n private:\n static Weight hash(void *key, size_t len) {\n // NOTE: don't change this\n Weight w;\n MurmurHash3_x64_128(key, len, 0, &w);\n return w;\n }\n\n static flat::NodeId selectImpl(const std::vector &nodes, auto &key) {\n if (nodes.empty()) {\n return flat::NodeId(0); // flat::NodeId(0) is invalid\n }\n\n auto node = nodes.at(0);\n auto weight = calculate(node, key);\n for (size_t i = 1; i < nodes.size(); i++) {\n auto n = nodes.at(i);\n auto w = calculate(n, key);\n if (w > weight) {\n node = n;\n weight = w;\n }\n }\n return node;\n }\n};\nstatic_assert(sizeof(Weight) == 16);\n\nstruct RoutingInfoChecker {\n template \n static constexpr bool hasInode() {\n return false;\n }\n\n template \n requires serde::SerdeType\n static constexpr bool hasInode() {\n if constexpr (std::is_same_v) {\n return true;\n }\n bool inode = false;\n refl::Helper::iterate([&](auto info) {\n using Item = std::remove_reference_t().*info.getter)>;\n inode |= hasInode();\n });\n return inode;\n }\n\n template \n requires is_variant_v\n static constexpr bool hasInode() { return variantHasInode(); }\n\n template \n static constexpr bool variantHasInode() {\n if constexpr (I < std::variant_size_v) {\n if constexpr (hasInode>()) {\n return true;\n }\n return variantHasInode();\n }\n return false;\n }\n\n template \n requires is_vector_v || is_set_v\n static constexpr bool hasInode() { return hasInode(); }\n\n template \n requires is_map_v\n static constexpr bool hasInode() { return hasInode() || hasInode(); }\n\n template \n requires is_optional_v\n static constexpr bool hasInode() { return hasInode(); }\n\n static bool checkRoutingInfo(const Inode &inode, const flat::RoutingInfo &routing) {\n if (inode.isFile()) {\n auto table = inode.asFile().layout.tableId;\n auto tableVer = inode.asFile().layout.tableVersion;\n switch (inode.asFile().layout.type()) {\n case Layout::Type::ChainRange:\n XLOGF_IF(DFATAL, (!table || !tableVer), \"File {}, invalid layout\", inode);\n if (!routing.getChainTable(table, tableVer)) {\n XLOGF(WARN, \"File {}, chain table {} version {}, not found in RoutingInfo\", inode.id, table, tableVer);\n return false;\n }\n break;\n case Layout::Type::ChainList:\n if (table && tableVer && !routing.getChainTable(table, tableVer)) {\n XLOGF(WARN, \"File {}, chain table {} version {}, not found in RoutingInfo\", inode.id, table, tableVer);\n return false;\n }\n break;\n case Layout::Type::Empty:\n break;\n }\n }\n return true;\n }\n\n template \n static bool checkRoutingInfo(const T &, const flat::RoutingInfo &) {\n return true;\n }\n\n template \n requires serde::SerdeType\n static bool checkRoutingInfo(const T &t, const flat::RoutingInfo &routing) {\n if constexpr (!hasInode()) {\n return true;\n }\n\n bool succ = true;\n refl::Helper::iterate([&](auto info) { succ &= checkRoutingInfo(t.*info.getter, routing); });\n return succ;\n }\n\n template \n requires is_variant_v\n static bool checkRoutingInfo(const T &t, const flat::RoutingInfo &routing) {\n if constexpr (!hasInode()) {\n return true;\n }\n return std::visit([&](const auto &v) { return checkRoutingInfo(v, routing); }, t);\n }\n\n template \n requires is_vector_v || is_set_v\n static bool checkRoutingInfo(const T &t, const flat::RoutingInfo &routing) {\n if constexpr (!hasInode()) {\n return true;\n }\n for (auto &i : t) {\n if (!checkRoutingInfo(i, routing)) {\n return false;\n }\n }\n return true;\n }\n\n template \n requires is_map_v\n static bool checkRoutingInfo(const T &t, const flat::RoutingInfo &routing) {\n if constexpr (!hasInode()) {\n return true;\n }\n for (auto &[k, v] : t) {\n if (!checkRoutingInfo(k, routing) || !checkRoutingInfo(v, routing)) {\n return false;\n }\n }\n return true;\n }\n\n template \n requires is_optional_v\n static bool checkRoutingInfo(const T &t, const flat::RoutingInfo &routing) {\n if constexpr (!hasInode()) {\n return true;\n }\n return t ? checkRoutingInfo(*t, routing) : true;\n }\n};\n\nstatic_assert(RoutingInfoChecker::hasInode());\nstatic_assert(RoutingInfoChecker::hasInode>());\nstatic_assert(RoutingInfoChecker::hasInode>());\nstatic_assert(RoutingInfoChecker::hasInode>());\nstatic_assert(RoutingInfoChecker::hasInode>());\nstatic_assert(RoutingInfoChecker::hasInode>());\nstatic_assert(RoutingInfoChecker::hasInode());\nstatic_assert(RoutingInfoChecker::hasInode());\nstatic_assert(RoutingInfoChecker::hasInode());\nstatic_assert(RoutingInfoChecker::hasInode());\nstatic_assert(RoutingInfoChecker::hasInode());\n} // namespace hf3fs::meta\n"], ["/3FS/src/mgmtd/MgmtdServer.h", "#pragma once\n\n#include \"MgmtdConfigFetcher.h\"\n#include \"MgmtdLauncherConfig.h\"\n#include \"common/net/Server.h\"\n#include \"core/app/ServerAppConfig.h\"\n#include \"core/app/ServerLauncher.h\"\n#include \"fdb/HybridKvEngineConfig.h\"\n#include \"mgmtd/service/MgmtdOperator.h\"\n#include \"service/MgmtdConfig.h\"\n\nnamespace hf3fs::mgmtd {\n\nclass MgmtdServer : public net::Server {\n public:\n static constexpr auto kName = \"Mgmtd\";\n static constexpr auto kNodeType = flat::NodeType::MGMTD;\n\n using AppConfig = core::ServerAppConfig;\n using LauncherConfig = MgmtdLauncherConfig;\n using RemoteConfigFetcher = MgmtdConfigFetcher;\n using Launcher = core::ServerLauncher;\n\n using CommonConfig = ApplicationBase::Config;\n class Config : public ConfigBase {\n CONFIG_OBJ(base, net::Server::Config, [](net::Server::Config &c) {\n c.set_groups_length(2);\n c.groups(0).listener().set_listen_port(8000);\n c.groups(0).set_services({\"Mgmtd\"});\n\n c.groups(1).set_network_type(net::Address::TCP);\n c.groups(1).listener().set_listen_port(9000);\n c.groups(1).set_use_independent_thread_pool(true);\n c.groups(1).set_services({\"Core\"});\n });\n CONFIG_OBJ(service, MgmtdConfig);\n };\n\n explicit MgmtdServer(const Config &config);\n ~MgmtdServer() override;\n\n using net::Server::start;\n Result start(const flat::AppInfo &info, std::shared_ptr kvEngine);\n\n Result beforeStart() final;\n\n Result afterStop() final;\n\n private:\n const Config &config_;\n\n std::shared_ptr kvEngine_;\n std::unique_ptr mgmtdOperator_;\n\n friend class testing::MgmtdTestHelper;\n};\n\n} // namespace hf3fs::mgmtd\n"], ["/3FS/src/stubs/MetaService/MockMetaServiceStub.h", "#pragma once\n\n#include \n#include \n\n#include \"common/serde/ClientContext.h\"\n#include \"common/serde/MessagePacket.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/Result.h\"\n#include \"fbs/meta/Service.h\"\n#include \"fbs/mgmtd/ChainRef.h\"\n#include \"stubs/MetaService/IMetaServiceStub.h\"\n#include \"stubs/MetaService/MetaServiceStub.h\"\n#include \"stubs/common/Stub.h\"\n\nnamespace hf3fs::meta {\n\nusing flat::ChainTableId;\nusing flat::Uid;\nusing flat::UserInfo;\n\nclass DummyMetaServiceStub : public IMetaServiceStub {\n public:\n ~DummyMetaServiceStub() override = default;\n\n#define NOT_IMPLEMENTED_FUNC(NAME, REQ, RESP) \\\n CoTryTask NAME(const REQ &req, const net::UserRequestOptions &, serde::Timestamp *) override { \\\n co_return co_await NAME(req); \\\n } \\\n virtual CoTryTask NAME(const REQ &) { co_return makeError(StatusCode::kNotImplemented); }\n\n NOT_IMPLEMENTED_FUNC(statFs, StatFsReq, StatFsRsp);\n NOT_IMPLEMENTED_FUNC(stat, StatReq, StatRsp);\n NOT_IMPLEMENTED_FUNC(create, CreateReq, CreateRsp);\n NOT_IMPLEMENTED_FUNC(mkdirs, MkdirsReq, MkdirsRsp);\n NOT_IMPLEMENTED_FUNC(symlink, SymlinkReq, SymlinkRsp);\n NOT_IMPLEMENTED_FUNC(hardLink, HardLinkReq, HardLinkRsp);\n NOT_IMPLEMENTED_FUNC(remove, RemoveReq, RemoveRsp);\n NOT_IMPLEMENTED_FUNC(open, OpenReq, OpenRsp);\n NOT_IMPLEMENTED_FUNC(sync, SyncReq, SyncRsp);\n NOT_IMPLEMENTED_FUNC(close, CloseReq, CloseRsp);\n NOT_IMPLEMENTED_FUNC(rename, RenameReq, RenameRsp);\n NOT_IMPLEMENTED_FUNC(list, ListReq, ListRsp);\n NOT_IMPLEMENTED_FUNC(truncate, TruncateReq, TruncateRsp);\n NOT_IMPLEMENTED_FUNC(getRealPath, GetRealPathReq, GetRealPathRsp);\n NOT_IMPLEMENTED_FUNC(setAttr, SetAttrReq, SetAttrRsp);\n NOT_IMPLEMENTED_FUNC(pruneSession, PruneSessionReq, PruneSessionRsp);\n NOT_IMPLEMENTED_FUNC(dropUserCache, DropUserCacheReq, DropUserCacheRsp);\n NOT_IMPLEMENTED_FUNC(lockDirectory, LockDirectoryReq, LockDirectoryRsp);\n NOT_IMPLEMENTED_FUNC(testRpc, TestRpcReq, TestRpcRsp);\n NOT_IMPLEMENTED_FUNC(batchStat, BatchStatReq, BatchStatRsp);\n NOT_IMPLEMENTED_FUNC(batchStatByPath, BatchStatByPathReq, BatchStatByPathRsp);\n\n virtual CoTryTask authenticate(const AuthReq &req) { co_return AuthRsp{req.user}; }\n CoTryTask authenticate(const AuthReq &req, const net::UserRequestOptions &, serde::Timestamp *) override {\n co_return co_await authenticate(req);\n }\n\n#undef NOT_IMPLEMENTED_FUNC\n};\n\nstruct MockMetaStubHolder {\n void setStub(std::unique_ptr st) { stub = std::move(st); }\n\n folly::atomic_shared_ptr stub;\n};\n\nclass DummyMetaServiceStubWithInode : public DummyMetaServiceStub {\n public:\n DummyMetaServiceStubWithInode(std::variant data)\n : inode_({InodeId(0x10de1d), {data, Acl{Uid(0), Gid(0), Permission(0777)}}}) {}\n\n CoTryTask create(const CreateReq &) override { co_return CreateRsp(inode_, false); }\n CoTryTask open(const OpenReq &) override { co_return OpenRsp(inode_, false); }\n CoTryTask stat(const StatReq &) override { co_return StatRsp(inode_); }\n\n protected:\n Inode inode_;\n};\nclass DummyMetaServiceStubWithDir : public DummyMetaServiceStubWithInode {\n public:\n DummyMetaServiceStubWithDir()\n : DummyMetaServiceStubWithInode(Directory{InodeId(0x10de1dff), Layout::newEmpty(ChainTableId(1), 512 << 10, 8)}) {\n }\n};\nclass DummyMetaServiceStubWithFile : public DummyMetaServiceStubWithInode {\n public:\n DummyMetaServiceStubWithFile()\n : DummyMetaServiceStubWithInode(File(Layout::newEmpty(ChainTableId(1), 512 << 10, 8))) {}\n};\nclass DummyMetaServiceStubWithSymlink : public DummyMetaServiceStubWithInode {\n public:\n DummyMetaServiceStubWithSymlink()\n : DummyMetaServiceStubWithInode(Symlink{\"/b\"}) {}\n};\n} // namespace hf3fs::meta\n\ntemplate <>\nstruct ::hf3fs::stubs::StubMockContext {\n std::shared_ptr stub;\n};\n\nnamespace hf3fs::meta {\n\ntemplate <>\nclass MetaServiceStub> : public IMetaServiceStub {\n public:\n using ContextType = hf3fs::stubs::StubMockContext;\n\n MetaServiceStub(ContextType ctx)\n : stub_(std::move(ctx.stub)) {}\n ~MetaServiceStub() override = default;\n\n#define FORWARD_RPC_FUNC(NAME, REQ, RESP) \\\n CoTryTask NAME(const REQ &req, const net::UserRequestOptions &opts, serde::Timestamp *timestamp) override { \\\n co_return co_await stub_->stub.load()->NAME(req, opts, timestamp); \\\n }\n\n FORWARD_RPC_FUNC(statFs, StatFsReq, StatFsRsp);\n FORWARD_RPC_FUNC(stat, StatReq, StatRsp);\n FORWARD_RPC_FUNC(create, CreateReq, CreateRsp);\n FORWARD_RPC_FUNC(mkdirs, MkdirsReq, MkdirsRsp);\n FORWARD_RPC_FUNC(symlink, SymlinkReq, SymlinkRsp);\n FORWARD_RPC_FUNC(hardLink, HardLinkReq, HardLinkRsp);\n FORWARD_RPC_FUNC(remove, RemoveReq, RemoveRsp);\n FORWARD_RPC_FUNC(open, OpenReq, OpenRsp);\n FORWARD_RPC_FUNC(sync, SyncReq, SyncRsp);\n FORWARD_RPC_FUNC(close, CloseReq, CloseRsp);\n FORWARD_RPC_FUNC(rename, RenameReq, RenameRsp);\n FORWARD_RPC_FUNC(list, ListReq, ListRsp);\n FORWARD_RPC_FUNC(truncate, TruncateReq, TruncateRsp);\n FORWARD_RPC_FUNC(getRealPath, GetRealPathReq, GetRealPathRsp);\n FORWARD_RPC_FUNC(setAttr, SetAttrReq, SetAttrRsp);\n FORWARD_RPC_FUNC(pruneSession, PruneSessionReq, PruneSessionRsp);\n FORWARD_RPC_FUNC(dropUserCache, DropUserCacheReq, DropUserCacheRsp);\n FORWARD_RPC_FUNC(authenticate, AuthReq, AuthRsp);\n FORWARD_RPC_FUNC(lockDirectory, LockDirectoryReq, LockDirectoryRsp);\n FORWARD_RPC_FUNC(testRpc, TestRpcReq, TestRpcRsp);\n FORWARD_RPC_FUNC(batchStat, BatchStatReq, BatchStatRsp);\n FORWARD_RPC_FUNC(batchStatByPath, BatchStatByPathReq, BatchStatByPathRsp);\n\n#undef FORWARD_RPC_FUNC\n\n private:\n std::shared_ptr stub_;\n};\n\n} // namespace hf3fs::meta\n"], ["/3FS/src/meta/store/PathResolve.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/kv/ITransaction.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/Duration.h\"\n#include \"common/utils/Path.h\"\n#include \"fbs/meta/Common.h\"\n#include \"meta/components/AclCache.h\"\n#include \"meta/store/DirEntry.h\"\n#include \"meta/store/Inode.h\"\n#include \"meta/store/Utils.h\"\n\nnamespace hf3fs::meta::server {\n\n/**\n * Path Resolution.\n *\n * Note: PathResolveOp always use snapshotLoad, so it won't add any key into read conflict set.\n * User should add keys into read conflict set manually if needed.\n */\nclass PathResolveOp : folly::NonCopyableNonMovable {\n public:\n struct ResolveResult {\n // for parent, we may already got it's Inode, or just dirEntry points to it, or just cached acl\n std::variant, Inode, DirEntry> parent;\n std::optional dirEntry;\n\n ResolveResult(std::variant, Inode, DirEntry> parent, std::optional dirEntry)\n : parent(std::move(parent)),\n dirEntry(std::move(dirEntry)) {}\n\n InodeId getParentId() const { return getInodeId(parent); }\n Acl getParentAcl() const { return getDirectoryAcl(parent); }\n CoTryTask getParentInode(kv::IReadOnlyTransaction &txn) const {\n if (std::holds_alternative(parent)) {\n co_return std::get(parent);\n } else if (std::holds_alternative(parent)) {\n co_return co_await std::get(parent).snapshotLoadInode(txn);\n } else {\n auto parentId = std::get>(parent).first;\n co_return (co_await Inode::snapshotLoad(txn, parentId)).then(checkMetaFound);\n }\n }\n };\n\n struct ResolveRangeResult : ResolveResult {\n Path missing;\n ResolveRangeResult(ResolveResult result, Path missing)\n : ResolveResult(std::move(result)),\n missing(missing) {}\n };\n\n PathResolveOp(IReadOnlyTransaction &txn, AclCache &aclCache, const UserInfo &userInfo, Path *trace = nullptr)\n : PathResolveOp(txn, aclCache, userInfo, trace, 4, 8, 5_s) {}\n PathResolveOp(IReadOnlyTransaction &txn,\n AclCache &aclCache,\n const UserInfo &userInfo,\n Path *trace,\n size_t maxSymlinkCount,\n size_t maxSymlinkDepth,\n Duration aclCacheTime)\n : txn_(txn),\n user_(userInfo),\n aclCache_(aclCache),\n trace_(trace),\n depth_(0),\n symlinkCnt_(0),\n maxSymlinkCount_(maxSymlinkCount),\n maxSymlinkDepth_(maxSymlinkDepth),\n aclCacheTime_(aclCacheTime),\n pathComponents_(0) {}\n ~PathResolveOp();\n\n CoTryTask inode(const PathAt &path, AtFlags flags, bool checkRefCnt);\n CoTryTask dirEntry(const PathAt &path, AtFlags flags);\n\n CoTryTask path(const PathAt &path, AtFlags flags);\n CoTryTask byDirectoryInodeId(InodeId inodeId);\n CoTryTask pathRange(const PathAt &path);\n\n CoTryTask symlink(DirEntry entry);\n\n private:\n template \n FRIEND_TEST(TestResolve, ResolveComponent);\n\n CoTryTask dirEntry(InodeId parent, const Path &path, bool followLastSymlink);\n\n CoTryTask path(InodeId parent, const Path &path);\n CoTryTask path(InodeId parent, const Path &path, bool followLastSymlink);\n CoTryTask pathComponent(const std::variant &parent, const Path &name);\n CoTryTask pathRange(InodeId parent, Path::const_iterator &begin, const Path::const_iterator &end);\n\n IReadOnlyTransaction &txn_;\n const UserInfo &user_;\n AclCache &aclCache_;\n Path *trace_;\n\n size_t depth_;\n size_t symlinkCnt_;\n\n size_t maxSymlinkCount_;\n size_t maxSymlinkDepth_;\n Duration aclCacheTime_;\n\n size_t pathComponents_;\n};\n\n} // namespace hf3fs::meta::server"], ["/3FS/src/fbs/meta/Service.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/app/ClientId.h\"\n#include \"common/app/NodeId.h\"\n#include \"common/serde/Serde.h\"\n#include \"common/serde/Service.h\"\n#include \"common/utils/Result.h\"\n#include \"common/utils/Status.h\"\n#include \"common/utils/StrongType.h\"\n#include \"common/utils/Uuid.h\"\n#include \"fbs/core/user/User.h\"\n#include \"fbs/meta/Common.h\"\n#include \"fbs/meta/Schema.h\"\n#include \"fbs/mgmtd/MgmtdTypes.h\"\n\n#define META_SERVICE_VERSION 1\n\n#define CHECK_SESSION(session) \\\n do { \\\n if (!session.has_value()) { \\\n return INVALID(#session \" not set\"); \\\n } \\\n if (!session->valid()) { \\\n return INVALID(#session \" invalid\"); \\\n } \\\n } while (0)\n\nnamespace hf3fs::meta {\n\nstruct ReqBase {\n SERDE_STRUCT_FIELD(user, UserInfo{});\n SERDE_STRUCT_FIELD(client, ClientId{Uuid::zero()});\n SERDE_STRUCT_FIELD(forward, flat::NodeId(0));\n SERDE_STRUCT_FIELD(uuid, Uuid::zero());\n\n public:\n // set client id in unittest\n static std::optional ¤tClientId() {\n static std::optional clientId;\n return clientId;\n }\n\n ReqBase(UserInfo user = {}, Uuid uuid = Uuid::zero())\n : user(std::move(user)),\n uuid(uuid) {\n if (currentClientId()) {\n client = *currentClientId();\n }\n }\n\n Result checkUuid() const {\n if (client.uuid == Uuid::zero()) return INVALID(\"Invalid client uuid\");\n if (uuid == Uuid::zero()) return INVALID(\"Invalid request uuid\");\n return VALID;\n }\n};\nstruct RspBase {\n SERDE_STRUCT_FIELD(dummy, Void{});\n};\n\n// authentication\nstruct AuthReq : ReqBase {\n SERDE_STRUCT_FIELD(dummy, Void{});\n\n public:\n AuthReq() = default;\n AuthReq(UserInfo user)\n : ReqBase(std::move(user)) {}\n Result valid() const { return VALID; }\n};\n\nstruct AuthRsp : RspBase {\n SERDE_STRUCT_FIELD(user, UserInfo{});\n\n public:\n AuthRsp() = default;\n AuthRsp(UserInfo user)\n : user(std::move(user)) {}\n};\n\n// statFs\nstruct StatFsReq : ReqBase {\n public:\n StatFsReq() = default;\n StatFsReq(UserInfo user)\n : ReqBase(std::move(user)) {}\n Result valid() const { return VALID; }\n};\nstruct StatFsRsp : RspBase {\n SERDE_STRUCT_FIELD(capacity, uint64_t(0));\n SERDE_STRUCT_FIELD(used, uint64_t(0));\n SERDE_STRUCT_FIELD(free, uint64_t(0));\n\n public:\n StatFsRsp() = default;\n StatFsRsp(uint64_t capacity, uint64_t used, uint64_t free)\n : capacity(capacity),\n used(used),\n free(free) {}\n};\n\n// stat\nstruct StatReq : ReqBase {\n SERDE_STRUCT_FIELD(path, PathAt());\n SERDE_STRUCT_FIELD(flags, AtFlags());\n\n public:\n StatReq() = default;\n StatReq(UserInfo user, PathAt path, AtFlags flags)\n : ReqBase(std::move(user)),\n path(std::move(path)),\n flags(flags) {}\n Result valid() const { return flags.valid(); }\n};\nstruct StatRsp : RspBase {\n SERDE_STRUCT_FIELD(stat, Inode());\n\n public:\n StatRsp() = default;\n StatRsp(Inode stat)\n : stat(std::move(stat)) {}\n};\n\n// batchStat & batchStatByPath\nstruct BatchStatReq : ReqBase {\n SERDE_STRUCT_FIELD(inodeIds, std::vector());\n\n public:\n BatchStatReq() = default;\n BatchStatReq(UserInfo user, std::vector inodeIds)\n : ReqBase(std::move(user)),\n inodeIds(std::move(inodeIds)) {}\n\n Result valid() const { return VALID; }\n};\n\nstruct BatchStatRsp : RspBase {\n SERDE_STRUCT_FIELD(inodes, std::vector>());\n\n public:\n BatchStatRsp() = default;\n BatchStatRsp(std::vector> inodes)\n : inodes(std::move(inodes)) {}\n};\n\nstruct BatchStatByPathReq : ReqBase {\n SERDE_STRUCT_FIELD(paths, std::vector());\n SERDE_STRUCT_FIELD(flags, AtFlags());\n\n public:\n BatchStatByPathReq() = default;\n BatchStatByPathReq(UserInfo user, std::vector paths, AtFlags flags)\n : ReqBase(std::move(user)),\n paths(std::move(paths)),\n flags(flags) {}\n\n Result valid() const { return flags.valid(); }\n};\n\nstruct BatchStatByPathRsp : RspBase {\n SERDE_STRUCT_FIELD(inodes, std::vector>());\n\n public:\n BatchStatByPathRsp() = default;\n BatchStatByPathRsp(std::vector> inodes)\n : inodes(std::move(inodes)) {}\n};\n\n// create\nstruct CreateReq : ReqBase {\n SERDE_STRUCT_FIELD(path, PathAt());\n SERDE_STRUCT_FIELD(session, std::optional());\n SERDE_STRUCT_FIELD(flags, OpenFlags());\n SERDE_STRUCT_FIELD(perm, Permission());\n SERDE_STRUCT_FIELD(layout, std::optional());\n SERDE_STRUCT_FIELD(removeChunksBatchSize, uint32_t(0));\n SERDE_STRUCT_FIELD(dynStripe, false);\n\n public:\n CreateReq() = default;\n CreateReq(UserInfo user,\n PathAt path,\n std::optional session,\n OpenFlags flags,\n Permission perm,\n std::optional layout = std::nullopt,\n bool dynStripe = false)\n : ReqBase(std::move(user), Uuid::random()),\n path(std::move(path)),\n session(session),\n flags(flags),\n perm(perm),\n layout(std::move(layout)),\n removeChunksBatchSize(32),\n dynStripe(dynStripe) {}\n\n Result valid() const {\n RETURN_ON_ERROR(path.validForCreate());\n RETURN_ON_ERROR(flags.valid());\n if (flags.accessType() != AccessType::READ) CHECK_SESSION(session);\n if (layout.has_value()) RETURN_ON_ERROR(layout->valid(true));\n if (flags.contains(O_TRUNC) && removeChunksBatchSize == 0) return INVALID(\"removeChunksBatchSize == 0\");\n return VALID;\n }\n};\nstruct CreateRsp : RspBase {\n SERDE_STRUCT_FIELD(stat, Inode());\n SERDE_STRUCT_FIELD(needTruncate, false);\n\n public:\n CreateRsp() = default;\n CreateRsp(Inode stat, bool needTruncate)\n : stat(std::move(stat)),\n needTruncate(needTruncate) {}\n};\n\n// mkdirs\nstruct MkdirsReq : ReqBase {\n SERDE_STRUCT_FIELD(path, PathAt());\n SERDE_STRUCT_FIELD(perm, Permission());\n SERDE_STRUCT_FIELD(recursive, false);\n SERDE_STRUCT_FIELD(layout, std::optional());\n\n public:\n MkdirsReq() = default;\n MkdirsReq(UserInfo user, PathAt path, Permission perm, bool recursive, std::optional layout = std::nullopt)\n : ReqBase(std::move(user), Uuid::random()),\n path(std::move(path)),\n perm(perm),\n recursive(recursive),\n layout(std::move(layout)) {}\n Result valid() const {\n if (!path.path.has_value() || path.path->empty()) return INVALID(\"path not set\");\n if (layout.has_value()) RETURN_ON_ERROR(layout->valid(true));\n return Void{};\n }\n};\n\nstruct MkdirsRsp : RspBase {\n SERDE_STRUCT_FIELD(stat, Inode());\n\n public:\n MkdirsRsp() = default;\n MkdirsRsp(Inode stat)\n : stat(std::move(stat)) {}\n};\n\n// symlink\nstruct SymlinkReq : ReqBase {\n SERDE_STRUCT_FIELD(path, PathAt());\n SERDE_STRUCT_FIELD(target, Path());\n\n public:\n SymlinkReq() = default;\n SymlinkReq(UserInfo user, PathAt path, Path target)\n : ReqBase(std::move(user), Uuid::random()),\n path(std::move(path)),\n target(std::move(target)) {}\n Result valid() const { return path.validForCreate(); }\n};\nstruct SymlinkRsp : RspBase {\n SERDE_STRUCT_FIELD(stat, Inode());\n\n public:\n SymlinkRsp() = default;\n SymlinkRsp(Inode stat)\n : stat(std::move(stat)) {}\n};\n\n// hardlink\nstruct HardLinkReq : ReqBase {\n SERDE_STRUCT_FIELD(oldPath, PathAt());\n SERDE_STRUCT_FIELD(newPath, PathAt());\n SERDE_STRUCT_FIELD(flags, AtFlags());\n\n public:\n HardLinkReq() = default;\n HardLinkReq(UserInfo user, PathAt oldPath, PathAt newPath, AtFlags flags)\n : ReqBase(std::move(user), Uuid::random()),\n oldPath(std::move(oldPath)),\n newPath(std::move(newPath)),\n flags(flags) {}\n Result valid() const {\n RETURN_ON_ERROR(newPath.validForCreate());\n RETURN_ON_ERROR(flags.valid());\n return VALID;\n }\n};\nstruct HardLinkRsp : RspBase {\n SERDE_STRUCT_FIELD(stat, Inode());\n\n public:\n HardLinkRsp() = default;\n HardLinkRsp(Inode stat)\n : stat(std::move(stat)) {}\n};\n\n// remove\nstruct RemoveReq : ReqBase {\n SERDE_STRUCT_FIELD(path, PathAt());\n SERDE_STRUCT_FIELD(atFlags, AtFlags());\n SERDE_STRUCT_FIELD(recursive, false);\n SERDE_STRUCT_FIELD(checkType, false);\n SERDE_STRUCT_FIELD(inodeId, std::optional());\n\n public:\n RemoveReq() = default;\n RemoveReq(UserInfo user,\n PathAt path,\n AtFlags flags,\n bool recursive,\n bool checkType = false,\n std::optional inodeId = std::nullopt)\n : ReqBase(std::move(user), Uuid::random()),\n path(std::move(path)),\n atFlags(flags),\n recursive(recursive),\n checkType(checkType),\n inodeId(inodeId) {}\n Result valid() const {\n if (path.path.has_value()) RETURN_ON_ERROR(path.validForCreate());\n if (recursive) RETURN_ON_ERROR(checkUuid());\n return VALID;\n }\n};\n\nstruct RemoveRsp : RspBase {\n SERDE_STRUCT_FIELD(dummy, Void{});\n};\n\n// open\nstruct OpenReq : ReqBase {\n SERDE_STRUCT_FIELD(path, PathAt());\n SERDE_STRUCT_FIELD(session, std::optional());\n SERDE_STRUCT_FIELD(flags, OpenFlags());\n SERDE_STRUCT_FIELD(removeChunksBatchSize, uint32_t(0));\n SERDE_STRUCT_FIELD(dynStripe, false);\n\n public:\n OpenReq() = default;\n OpenReq(UserInfo user, PathAt path, std::optional session, OpenFlags flags, bool dynStripe = false)\n : ReqBase(std::move(user)),\n path(std::move(path)),\n session(session),\n flags(flags),\n removeChunksBatchSize(32),\n dynStripe(dynStripe) {}\n Result valid() const {\n RETURN_ON_ERROR(flags.valid());\n if (flags.accessType() != AccessType::READ) CHECK_SESSION(session);\n if (flags.accessType() == AccessType::READ && (flags.contains(O_TRUNC) || flags.contains(O_APPEND)))\n return INVALID(\"O_RDONLY with O_TRUNC or O_APPEND\");\n if (flags.contains(O_TRUNC) && removeChunksBatchSize == 0) return INVALID(\"removeChunksBatchSize == 0\");\n return VALID;\n }\n};\nstruct OpenRsp : RspBase {\n SERDE_STRUCT_FIELD(_unused, (uint32_t)0);\n SERDE_STRUCT_FIELD(stat, Inode());\n SERDE_STRUCT_FIELD(needTruncate, false);\n\n public:\n OpenRsp() = default;\n OpenRsp(Inode stat, bool needTruncate)\n : stat(std::move(stat)),\n needTruncate(needTruncate) {}\n};\n\n// sync\nstruct SyncReq : ReqBase {\n SERDE_STRUCT_FIELD(inode, InodeId());\n SERDE_STRUCT_FIELD(updateLength, false);\n SERDE_STRUCT_FIELD(atime, std::optional());\n SERDE_STRUCT_FIELD(mtime, std::optional());\n SERDE_STRUCT_FIELD(truncated, false);\n SERDE_STRUCT_FIELD(lengthHint, std::optional());\n\n public:\n SyncReq() = default;\n SyncReq(UserInfo user,\n InodeId inode,\n bool updateLength,\n std::optional atime,\n std::optional mtime,\n bool truncated = false,\n std::optional hint = std::nullopt)\n : ReqBase(std::move(user)),\n inode(inode),\n updateLength(updateLength),\n atime(atime),\n mtime(mtime),\n truncated(truncated),\n lengthHint(hint) {}\n Result valid() const {\n if (truncated && !updateLength) return INVALID(\"truncate but not updateLength\");\n return VALID;\n }\n};\nstruct SyncRsp : RspBase {\n SERDE_STRUCT_FIELD(_unused, (uint32_t)0);\n SERDE_STRUCT_FIELD(stat, Inode());\n\n public:\n SyncRsp() = default;\n SyncRsp(Inode stat)\n : stat(std::move(stat)) {}\n};\n\n// close\nstruct CloseReq : ReqBase {\n SERDE_STRUCT_FIELD(inode, InodeId());\n SERDE_STRUCT_FIELD(session, std::optional());\n SERDE_STRUCT_FIELD(updateLength, false);\n SERDE_STRUCT_FIELD(atime, std::optional());\n SERDE_STRUCT_FIELD(mtime, std::optional());\n SERDE_STRUCT_FIELD(lengthHint, std::optional());\n\n public:\n bool pruneSession = false;\n\n CloseReq() = default;\n CloseReq(UserInfo user,\n InodeId inode,\n std::optional session,\n bool updateLength,\n std::optional atime,\n std::optional mtime)\n : ReqBase(std::move(user)),\n inode(inode),\n session(session),\n updateLength(updateLength),\n atime(atime),\n mtime(mtime) {}\n Result valid() const {\n if (updateLength || mtime.has_value()) CHECK_SESSION(session);\n return VALID;\n }\n};\nstruct CloseRsp : RspBase {\n SERDE_STRUCT_FIELD(_unused, (uint32_t)0);\n SERDE_STRUCT_FIELD(stat, Inode());\n\n public:\n CloseRsp() = default;\n CloseRsp(Inode stat)\n : stat(std::move(stat)) {}\n};\n\n// rename\nstruct RenameReq : ReqBase {\n SERDE_STRUCT_FIELD(src, PathAt());\n SERDE_STRUCT_FIELD(dest, PathAt());\n SERDE_STRUCT_FIELD(moveToTrash, false);\n SERDE_STRUCT_FIELD(inodeId, std::optional());\n\n public:\n RenameReq() = default;\n RenameReq(UserInfo user,\n PathAt src,\n PathAt dest,\n bool moveToTrash = false,\n std::optional inodeId = std::nullopt)\n : ReqBase(std::move(user), Uuid::random()),\n src(std::move(src)),\n dest(std::move(dest)),\n moveToTrash(moveToTrash),\n inodeId(inodeId) {}\n Result valid() const {\n RETURN_ON_ERROR(src.validForCreate());\n RETURN_ON_ERROR(dest.validForCreate());\n if (moveToTrash) RETURN_ON_ERROR(checkUuid());\n return VALID;\n }\n};\nstruct RenameRsp : RspBase {\n SERDE_STRUCT_FIELD(dummy, Void{});\n SERDE_STRUCT_FIELD(stat, std::optional());\n\n public:\n RenameRsp() = default;\n RenameRsp(Inode stat)\n : stat(std::move(stat)) {}\n};\n\n// list\nstruct ListReq : ReqBase {\n SERDE_STRUCT_FIELD(path, PathAt());\n SERDE_STRUCT_FIELD(prev, std::string());\n SERDE_STRUCT_FIELD(limit, (int32_t)-1);\n SERDE_STRUCT_FIELD(status, false);\n\n public:\n ListReq() = default;\n ListReq(UserInfo user, PathAt path, std::string prev = {}, int32_t limit = -1, bool status = false)\n : ReqBase(std::move(user)),\n path(std::move(path)),\n prev(std::move(prev)),\n limit(limit),\n status(status) {}\n Result valid() const { return VALID; }\n};\nstruct ListRsp : RspBase {\n SERDE_STRUCT_FIELD(entries, std::vector());\n SERDE_STRUCT_FIELD(inodes, std::vector());\n SERDE_STRUCT_FIELD(more, false);\n\n public:\n ListRsp() = default;\n ListRsp(std::vector entries, std::vector inodes, bool more)\n : entries(std::move(entries)),\n inodes(std::move(inodes)),\n more(more) {}\n};\n\n// truncate\nstruct TruncateReq : ReqBase {\n SERDE_STRUCT_FIELD(inode, InodeId(0));\n SERDE_STRUCT_FIELD(length, uint64_t(0));\n SERDE_STRUCT_FIELD(removeChunksBatchSize, uint32_t(0));\n\n public:\n TruncateReq() = default;\n TruncateReq(UserInfo user, InodeId inode, uint64_t length, uint32_t removeChunksBatchSize)\n : ReqBase(std::move(user)),\n inode(inode),\n length(length),\n removeChunksBatchSize(removeChunksBatchSize) {}\n Result valid() const {\n if (removeChunksBatchSize == 0) return INVALID(\"removeChunksBatchSize == 0\");\n return VALID;\n }\n};\nstruct TruncateRsp : RspBase {\n SERDE_STRUCT_FIELD(chunksRemoved, uint32_t(0));\n SERDE_STRUCT_FIELD(stat, Inode());\n SERDE_STRUCT_FIELD(finished, true);\n\n public:\n TruncateRsp() = default;\n TruncateRsp(Inode stat)\n : TruncateRsp(std::move(stat), 0, true) {}\n TruncateRsp(Inode stat, uint32_t chunksRemoved, bool finished)\n : chunksRemoved(chunksRemoved),\n stat(std::move(stat)),\n finished(finished) {}\n};\n\n// getRealPath\nstruct GetRealPathReq : ReqBase {\n SERDE_STRUCT_FIELD(path, PathAt());\n SERDE_STRUCT_FIELD(absolute, false);\n\n public:\n GetRealPathReq() = default;\n GetRealPathReq(UserInfo user, PathAt path, bool absolute)\n : ReqBase(std::move(user)),\n path(std::move(path)),\n absolute(absolute) {}\n Result valid() const { return VALID; }\n};\nstruct GetRealPathRsp : RspBase {\n SERDE_STRUCT_FIELD(path, Path());\n\n public:\n GetRealPathRsp() = default;\n GetRealPathRsp(Path path)\n : path(std::move(path)) {}\n};\n\n// setAttr\nstruct SetAttrReq : ReqBase {\n SERDE_STRUCT_FIELD(path, PathAt());\n SERDE_STRUCT_FIELD(flags, AtFlags());\n SERDE_STRUCT_FIELD(uid, std::optional());\n SERDE_STRUCT_FIELD(gid, std::optional());\n SERDE_STRUCT_FIELD(perm, std::optional());\n SERDE_STRUCT_FIELD(atime, std::optional());\n SERDE_STRUCT_FIELD(mtime, std::optional());\n SERDE_STRUCT_FIELD(layout, std::optional());\n SERDE_STRUCT_FIELD(iflags, std::optional());\n SERDE_STRUCT_FIELD(dynStripe, uint32_t(0));\n\n public:\n static SetAttrReq setLayout(UserInfo user, PathAt path, AtFlags flags, Layout layout) {\n return {std::move(user), std::move(path), flags, {}, {}, {}, {}, {}, std::move(layout)};\n }\n static SetAttrReq setPermission(UserInfo user,\n PathAt path,\n AtFlags flags,\n std::optional uid,\n std::optional gid,\n std::optional perm,\n std::optional iflags = std::nullopt) {\n return {std::move(user), std::move(path), flags, uid, gid, perm, {}, {}, {}, iflags};\n }\n static SetAttrReq setIFlags(UserInfo user, PathAt path, IFlags iflags) {\n return {std::move(user), std::move(path), AtFlags(), {}, {}, {}, {}, {}, {}, iflags};\n }\n static SetAttrReq utimes(UserInfo user,\n PathAt path,\n AtFlags flags,\n std::optional atime,\n std::optional mtime) {\n return {std::move(user), std::move(path), flags, {}, {}, {}, atime, mtime, {}};\n }\n static SetAttrReq extendStripe(UserInfo user, InodeId inode, uint32_t stripe) {\n return {std::move(user), PathAt(inode), AtFlags{}, {}, {}, {}, {}, {}, {}, {}, stripe};\n }\n Result valid() const {\n if (layout.has_value()) RETURN_ON_ERROR(layout->valid(true));\n if (iflags && (*iflags & ~FS_FL_SUPPORTED)) {\n return MAKE_ERROR_F(StatusCode::kInvalidArg, \"only support {:x}\", (uint32_t)FS_FL_SUPPORTED);\n }\n return VALID;\n }\n};\n\nstruct SetAttrRsp : RspBase {\n SERDE_STRUCT_FIELD(stat, Inode());\n\n public:\n SetAttrRsp() = default;\n SetAttrRsp(Inode stat)\n : stat(std::move(stat)) {}\n};\n\n// pruneSession\nstruct PruneSessionReq : ReqBase {\n SERDE_STRUCT_FIELD(client, ClientId::zero());\n SERDE_STRUCT_FIELD(sessions, std::vector());\n SERDE_STRUCT_FIELD(needSync, std::vector()); // deperated\n\n public:\n PruneSessionReq() = default;\n PruneSessionReq(ClientId client, std::vector sessions)\n : ReqBase(),\n client(client),\n sessions(std::move(sessions)) {}\n Result valid() const { return VALID; }\n};\nstruct PruneSessionRsp : RspBase {\n SERDE_STRUCT_FIELD(dummy, Void{});\n};\n\n// dropUserCache\nstruct DropUserCacheReq : ReqBase {\n SERDE_STRUCT_FIELD(uid, std::optional());\n SERDE_STRUCT_FIELD(dropAll, false);\n\n public:\n DropUserCacheReq() = default;\n DropUserCacheReq(std::optional u, bool d)\n : uid(std::move(u)),\n dropAll(d) {}\n Result valid() const { return VALID; }\n};\nstruct DropUserCacheRsp : RspBase {\n SERDE_STRUCT_FIELD(dummy, Void{});\n};\n\n// lockDirectory\nstruct LockDirectoryReq : ReqBase {\n enum class LockAction : uint8_t {\n TryLock,\n PreemptLock,\n UnLock,\n Clear,\n };\n SERDE_STRUCT_FIELD(inode, InodeId());\n SERDE_STRUCT_FIELD(action, LockAction::TryLock);\n\n public:\n LockDirectoryReq() = default;\n LockDirectoryReq(UserInfo user, InodeId inode, LockAction action)\n : ReqBase(user),\n inode(inode),\n action(action) {}\n Result valid() const { return VALID; }\n};\n\nstruct LockDirectoryRsp : RspBase {\n SERDE_STRUCT_FIELD(dummy, Void{});\n\n public:\n LockDirectoryRsp() = default;\n};\n\n// testRpc\nstruct TestRpcReq : ReqBase {\n SERDE_STRUCT_FIELD(path, PathAt());\n SERDE_STRUCT_FIELD(flags, uint32_t(0));\n\n public:\n Result valid() const { return VALID; }\n};\nstruct TestRpcRsp : RspBase {\n SERDE_STRUCT_FIELD(stat, Inode());\n};\n\n/* MetaSerde service */\nSERDE_SERVICE(MetaSerde, 4) {\n#define META_SERVICE_METHOD(NAME, CODE, REQ, RSP) \\\n SERDE_SERVICE_METHOD(NAME, CODE, REQ, RSP); \\\n \\\n public: \\\n static constexpr std::string_view getRpcName(const REQ &) { return #NAME; } \\\n static_assert(serde::SerializableToBytes && serde::SerializableToJson); \\\n static_assert(serde::SerializableToBytes && serde::SerializableToJson)\n\n META_SERVICE_METHOD(statFs, 1, StatFsReq, StatFsRsp);\n META_SERVICE_METHOD(stat, 2, StatReq, StatRsp);\n META_SERVICE_METHOD(create, 3, CreateReq, CreateRsp);\n META_SERVICE_METHOD(mkdirs, 4, MkdirsReq, MkdirsRsp);\n META_SERVICE_METHOD(symlink, 5, SymlinkReq, SymlinkRsp);\n META_SERVICE_METHOD(hardLink, 6, HardLinkReq, HardLinkRsp);\n META_SERVICE_METHOD(remove, 7, RemoveReq, RemoveRsp);\n META_SERVICE_METHOD(open, 8, OpenReq, OpenRsp);\n META_SERVICE_METHOD(sync, 9, SyncReq, SyncRsp);\n META_SERVICE_METHOD(close, 10, CloseReq, CloseRsp);\n META_SERVICE_METHOD(rename, 11, RenameReq, RenameRsp);\n META_SERVICE_METHOD(list, 12, ListReq, ListRsp);\n // deperated:\n META_SERVICE_METHOD(truncate, 13, TruncateReq, TruncateRsp);\n META_SERVICE_METHOD(getRealPath, 14, GetRealPathReq, GetRealPathRsp);\n META_SERVICE_METHOD(setAttr, 15, SetAttrReq, SetAttrRsp);\n META_SERVICE_METHOD(pruneSession, 16, PruneSessionReq, PruneSessionRsp);\n META_SERVICE_METHOD(dropUserCache, 17, DropUserCacheReq, DropUserCacheRsp);\n META_SERVICE_METHOD(authenticate, 18, AuthReq, AuthRsp);\n META_SERVICE_METHOD(lockDirectory, 19, LockDirectoryReq, LockDirectoryRsp);\n META_SERVICE_METHOD(batchStat, 20, BatchStatReq, BatchStatRsp);\n META_SERVICE_METHOD(batchStatByPath, 21, BatchStatByPathReq, BatchStatByPathRsp);\n\n META_SERVICE_METHOD(testRpc, 50, TestRpcReq, TestRpcRsp);\n\n#undef META_SERVICE_METHOD\n};\n\n} // namespace hf3fs::meta\n"], ["/3FS/benchmarks/storage_bench/StorageBench.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/logging/LogInit.h\"\n#include \"common/net/ib/IBDevice.h\"\n#include \"common/utils/Duration.h\"\n#include \"common/utils/SysResource.h\"\n#include \"tests/lib/UnitTestFabric.h\"\n\nnamespace hf3fs::storage::benchmark {\n\nusing namespace hf3fs::storage::client;\n\nclass StorageBench : public test::UnitTestFabric {\n public:\n struct Options {\n const size_t numChunks;\n const size_t readSize;\n const size_t writeSize;\n const size_t batchSize;\n const uint64_t numReadSecs;\n const uint64_t numWriteSecs;\n const uint64_t clientTimeoutMS;\n const size_t numCoroutines;\n const size_t numTestThreads;\n const uint32_t randSeed = 0;\n const uint16_t chunkIdPrefix = 0xFFFF;\n const bool benchmarkNetwork = false;\n const bool benchmarkStorage = false;\n const bool ignoreIOError = false;\n const bool injectRandomServerError = false;\n const bool injectRandomClientError = false;\n const bool retryPermanentError = false;\n const bool verifyReadData = false;\n const bool verifyReadChecksum = false;\n const bool verifyWriteChecksum = true;\n const bool randomShuffleChunkIds = true;\n const bool generateTestData = true;\n const bool sparseChunkIds = true;\n const std::string statsFilePath = \"./perfstats.csv\";\n const std::vector ibvDevices = {};\n const std::vector ibnetZones = {};\n const std::vector mgmtdEndpoints = {};\n const std::string clusterId = kClusterId;\n const uint32_t chainTableId = 0;\n const uint32_t chainTableVersion = 0;\n const std::vector chainIds = {};\n const std::vector storageNodeIds = {};\n const size_t memoryAlignment = 1;\n const size_t readOffAlignment = 0;\n const size_t defaultPKeyIndex = 1;\n size_t readBatchSize = 0;\n size_t writeBatchSize = 0;\n size_t removeBatchSize = 0;\n };\n\n private:\n static constexpr uint32_t kTDigestMaxSize = 1000;\n\n struct ChunkInfo {\n ChainId chainId;\n ChunkId chunkId;\n size_t size;\n };\n\n Options benchOptions_;\n std::vector writeLatencyDigests_;\n std::vector readLatencyDigests_;\n folly::CPUThreadPoolExecutor testExecutor_;\n std::atomic_uint64_t numWriteBytes_;\n std::atomic_uint64_t numReadBytes_;\n folly::Random::DefaultGenerator randGen_;\n std::vector> chunkInfos_;\n std::vector numCreatedChunks_;\n size_t totalNumChunks_;\n double totalChunkGiB_;\n\n public:\n StorageBench(const test::SystemSetupConfig &setupConfig, const Options &options)\n : UnitTestFabric(setupConfig),\n benchOptions_(options),\n writeLatencyDigests_(benchOptions_.numCoroutines, folly::TDigest(kTDigestMaxSize)),\n readLatencyDigests_(benchOptions_.numCoroutines, folly::TDigest(kTDigestMaxSize)),\n testExecutor_(benchOptions_.numTestThreads),\n numWriteBytes_(0),\n numReadBytes_(0),\n randGen_(folly::Random::create()),\n chunkInfos_(benchOptions_.numCoroutines),\n numCreatedChunks_(benchOptions_.numCoroutines) {\n if (benchOptions_.readBatchSize == 0) benchOptions_.readBatchSize = benchOptions_.batchSize;\n if (benchOptions_.writeBatchSize == 0) benchOptions_.writeBatchSize = benchOptions_.batchSize;\n if (benchOptions_.removeBatchSize == 0) benchOptions_.removeBatchSize = benchOptions_.batchSize;\n }\n\n void generateChunkIds() {\n static_assert(sizeof(benchOptions_.chunkIdPrefix) == 2);\n uint64_t chunkIdPrefix64 = ((uint64_t)benchOptions_.chunkIdPrefix) << (UINT64_WIDTH - UINT16_WIDTH);\n std::sort(chainIds_.begin(), chainIds_.end());\n static thread_local std::mt19937 generator;\n randGen_.seed(benchOptions_.randSeed);\n\n XLOGF(WARN,\n \"Generating {} chunk ids with prefix {:08X} and random seed {}...\",\n totalNumChunks_,\n chunkIdPrefix64,\n benchOptions_.randSeed);\n\n for (auto &chunkInfos : chunkInfos_) {\n uint64_t instancePrefix = chunkIdPrefix64 | folly::Random::rand64(randGen_);\n XLOGF(DBG3, \"Random chunk id prefix {:08X}\", instancePrefix);\n\n chunkInfos.reserve(chainIds_.size() * benchOptions_.numChunks);\n\n for (auto chainId : chainIds_) {\n for (size_t chunkIndex = 0; chunkIndex < benchOptions_.numChunks; chunkIndex++) {\n if (benchOptions_.sparseChunkIds) {\n uint64_t chunkIdHigh = chunkIdPrefix64 | (folly::Random::rand64(randGen_) & 0x000000FFFFFFFFFF);\n uint64_t chunkIdLow = (folly::Random::rand64(randGen_) << UINT32_WIDTH) + chunkIndex;\n chunkInfos.push_back({chainId, ChunkId(chunkIdHigh, chunkIdLow), 0});\n } else {\n chunkInfos.push_back({chainId, ChunkId(instancePrefix, chunkIndex), 0});\n }\n }\n }\n\n if (benchOptions_.randomShuffleChunkIds) std::shuffle(chunkInfos.begin(), chunkInfos.end(), generator);\n }\n }\n\n bool connect() {\n XLOGF(INFO, \"Start to connect...\");\n\n if (!setupIBSock()) {\n return false;\n }\n\n mgmtdClientConfig_.set_mgmtd_server_addresses(benchOptions_.mgmtdEndpoints);\n mgmtdClientConfig_.set_enable_auto_refresh(true);\n mgmtdClientConfig_.set_enable_auto_heartbeat(false);\n mgmtdClientConfig_.set_enable_auto_extend_client_session(true);\n mgmtdClientConfig_.set_auto_refresh_interval(3_s);\n mgmtdClientConfig_.set_auto_heartbeat_interval(3_s);\n mgmtdClientConfig_.set_auto_extend_client_session_interval(3_s);\n mgmtdClientConfig_.set_accept_incomplete_routing_info_during_mgmtd_bootstrapping(false);\n\n if (!client_.start()) {\n XLOGF(ERR, \"Failed to start net client for mgmtd client\");\n return false;\n }\n\n XLOGF(INFO, \"Creating mgmtd client...\");\n\n auto stubFactory = std::make_unique>(\n stubs::ClientContextCreator{[this](net::Address addr) { return client_.serdeCtx(addr); }});\n auto mgmtdClient = std::make_unique(benchOptions_.clusterId,\n std::move(stubFactory),\n mgmtdClientConfig_);\n\n auto physicalHostnameRes = SysResource::hostname(/*physicalMachineName=*/true);\n if (!physicalHostnameRes) {\n XLOGF(ERR, \"getHostname(true) failed: {}\", physicalHostnameRes.error());\n return false;\n }\n\n auto containerHostnameRes = SysResource::hostname(/*physicalMachineName=*/false);\n if (!containerHostnameRes) {\n XLOGF(ERR, \"getHostname(false) failed: {}\", containerHostnameRes.error());\n return false;\n }\n\n mgmtdClient->setClientSessionPayload({clientId_.uuid.toHexString(),\n flat::NodeType::CLIENT,\n flat::ClientSessionData::create(\n /*universalId=*/*physicalHostnameRes,\n /*description=*/fmt::format(\"StorageBench: {}\", *containerHostnameRes),\n /*serviceGroups=*/std::vector{},\n flat::ReleaseVersion::fromVersionInfo()),\n flat::UserInfo{}});\n folly::coro::blockingWait(mgmtdClient->start(&client_.tpg().bgThreadPool().randomPick()));\n mgmtdForClient_ = std::move(mgmtdClient);\n\n // get routing info\n\n for (size_t retry = 0; retry < 15; retry++) {\n auto routingInfo = mgmtdForClient_->getRoutingInfo();\n\n if (routingInfo == nullptr || routingInfo->raw()->chains.empty()) {\n XLOGF(WARN, \"Empty routing info, #{} retry...\", retry + 1);\n std::this_thread::sleep_for(std::chrono::milliseconds(1000));\n } else {\n for (const auto &[tableId, tableVersions] : routingInfo->raw()->chainTables) {\n if (tableId == benchOptions_.chainTableId) {\n if (tableVersions.empty()) {\n XLOGF(WARN, \"No version found for chain table with id {}\", tableId);\n return false;\n }\n\n XLOGF(INFO, \"Found {} version(s) of chain table {}\", tableVersions.size(), benchOptions_.chainTableId);\n\n flat::ChainTable chainTable;\n\n if (benchOptions_.chainTableVersion > 0) {\n flat::ChainTableVersion tableVersion(benchOptions_.chainTableVersion);\n auto tableIter = tableVersions.find(tableVersion);\n\n if (tableIter == tableVersions.end()) {\n XLOGF(WARN, \"Version {} not found in chain table with id {}\", tableVersion, tableId);\n return false;\n }\n\n chainTable = tableIter->second;\n XLOGF(INFO,\n \"Found version {} of chain table {}: {}\",\n benchOptions_.chainTableVersion,\n benchOptions_.chainTableId,\n chainTable.chainTableVersion);\n } else {\n const auto iter = --tableVersions.cend();\n const auto &latestTable = iter->second;\n chainTable = latestTable;\n XLOGF(INFO,\n \"Found latest version of chain table {}: {}\",\n benchOptions_.chainTableId,\n chainTable.chainTableVersion);\n }\n\n XLOGF(WARN,\n \"Selected chain table: {}@{} [{}] {} chains\",\n chainTable.chainTableId,\n chainTable.chainTableVersion,\n chainTable.desc,\n chainTable.chains.size());\n\n if (!benchOptions_.storageNodeIds.empty()) {\n for (const auto &chainId : chainTable.chains) {\n const auto chainInfo = routingInfo->raw()->getChain(chainId);\n for (const auto &target : chainInfo->targets) {\n const auto targetInfo = routingInfo->raw()->getTarget(target.targetId);\n auto nodeIter = std::find(benchOptions_.storageNodeIds.begin(),\n benchOptions_.storageNodeIds.end(),\n *targetInfo->nodeId);\n if (nodeIter != benchOptions_.storageNodeIds.end()) {\n chainIds_.push_back(chainId);\n break;\n }\n }\n }\n } else if (!benchOptions_.chainIds.empty()) {\n for (const auto &chainId : chainTable.chains) {\n auto chainIter = std::find(benchOptions_.chainIds.begin(), benchOptions_.chainIds.end(), chainId);\n if (chainIter != benchOptions_.chainIds.end()) {\n chainIds_.push_back(chainId);\n }\n }\n } else {\n chainIds_ = chainTable.chains;\n }\n\n break;\n }\n }\n\n if (!chainIds_.empty()) break;\n }\n }\n\n if (chainIds_.empty()) {\n XLOGF(ERR, \"Failed to get chain table with id {}\", benchOptions_.chainTableId);\n return false;\n } else {\n XLOGF(WARN, \"Selected {} replication chains for benchmark\", chainIds_.size());\n }\n\n // create storage client\n\n if (setupConfig_.client_config().empty()) {\n XLOGF(ERR, \"Storage client config not specified\");\n return false;\n }\n\n auto configRes = clientConfig_.atomicallyUpdate(setupConfig_.client_config(), false /*isHotUpdate*/);\n if (!configRes) {\n XLOGF(ERR, \"Cannot load client config from {}, error: {}\", setupConfig_.client_config(), configRes.error());\n return false;\n }\n\n totalNumChunks_ = chainIds_.size() * benchOptions_.numCoroutines * benchOptions_.numChunks;\n totalChunkGiB_ = (double)totalNumChunks_ * setupConfig_.chunk_size() / 1_GB;\n clientConfig_.retry().set_max_retry_time(Duration(std::chrono::milliseconds(benchOptions_.clientTimeoutMS)));\n clientConfig_.net_client().io_worker().ibsocket().set_sl(setupConfig_.service_level());\n\n XLOGF(INFO, \"Creating storage client...\");\n storageClient_ = client::StorageClient::create(clientId_, clientConfig_, *mgmtdForClient_);\n\n return true;\n }\n\n bool setupIBSock() {\n XLOGF(WARN, \"Setting up IB socket...\");\n\n std::vector subnets;\n\n for (const auto &ibnetZoneStr : benchOptions_.ibnetZones) {\n std::vector ibnetZoneSubnet;\n boost::split(ibnetZoneSubnet, ibnetZoneStr, boost::is_any_of(\":\"));\n\n if (ibnetZoneSubnet.size() != 2) {\n XLOGF(CRITICAL, \"Invalid IB zone subnet: {}\", ibnetZoneStr);\n return false;\n }\n\n auto zone = boost::trim_copy(ibnetZoneSubnet[0]);\n auto subnet = boost::trim_copy(ibnetZoneSubnet[1]);\n\n if (zone.empty() || subnet.empty()) {\n XLOGF(CRITICAL, \"Invalid IB zone subnet: {}\", ibnetZoneStr);\n return false;\n }\n\n subnets.emplace_back();\n subnets.back().set_network_zones({zone});\n subnets.back().set_subnet(*net::IBConfig::Network::from(subnet));\n XLOGF(WARN, \"Add IB network zone: {} -- {}\", zone, subnet);\n }\n\n net::IBConfig ibConfig;\n ibConfig.set_subnets(subnets);\n ibConfig.set_allow_unknown_zone(false);\n ibConfig.set_default_network_zone(\"$HF3FS_NETWORK_ZONE\");\n ibConfig.set_device_filter(benchOptions_.ibvDevices);\n ibConfig.set_default_pkey_index(benchOptions_.defaultPKeyIndex);\n\n auto ibResult = net::IBManager::start(ibConfig);\n if (ibResult.hasError()) {\n XLOGF(CRITICAL, \"Cannot initialize IB device: {}\", ibResult.error());\n return false;\n }\n\n return true;\n }\n\n bool setup() {\n XLOGF(WARN, \"Setting up benchmark...\");\n\n if (!setupIBSock()) {\n return false;\n }\n\n bool ok = setUpStorageSystem();\n\n totalNumChunks_ = chainIds_.size() * benchOptions_.numCoroutines * benchOptions_.numChunks;\n totalChunkGiB_ = (double)totalNumChunks_ * setupConfig_.chunk_size() / 1_GB;\n clientConfig_.retry().set_max_retry_time(Duration(std::chrono::milliseconds(benchOptions_.clientTimeoutMS)));\n\n return ok;\n }\n\n void teardown() {\n tearDownStorageSystem();\n net::IBManager::stop();\n }\n\n void printThroughput(hf3fs::SteadyClock::duration elapsedMicro, double totalGiB) {\n auto elapsedMilli = std::chrono::duration_cast(elapsedMicro);\n double throughput = totalGiB / (elapsedMilli.count() / 1000.0);\n XLOGF(WARN, \"Average throughput: {:.3f}GiB/s, total {:.3f} GiB\", throughput, totalGiB);\n }\n\n void printLatencyDigest(const folly::TDigest &digest) {\n XLOGF(WARN, \"latency summary ({} samples)\", digest.count());\n XLOGF(WARN, \"min: {:10.1f}us\", digest.min());\n XLOGF(WARN, \"max: {:10.1f}us\", digest.max());\n XLOGF(WARN, \"avg: {:10.1f}us\", digest.mean());\n for (double p : {0.1, 0.2, 0.5, 0.9, 0.95, 0.99}) {\n XLOGF(WARN, \"{}%: {:10.1f}us\", p * 100.0, digest.estimateQuantile(p));\n }\n }\n\n void dumpPerfStats(const std::string &testName,\n const folly::TDigest &digest,\n hf3fs::SteadyClock::duration elapsedTime,\n double totalGiB,\n bool readIO) {\n if (benchOptions_.statsFilePath.empty()) return;\n\n boost::filesystem::path outFilePath(benchOptions_.statsFilePath);\n\n if (!boost::filesystem::exists(outFilePath) || boost::filesystem::is_empty(outFilePath)) {\n XLOGF(INFO, \"Create a file for perfermance stats at {}\", outFilePath);\n std::ofstream outFile(outFilePath);\n if (!outFile) {\n throw std::runtime_error(\"Failed to open file: \" + outFilePath.string());\n }\n\n outFile << \"test name,#storages,#chains,#replicas,concurrency,batch size,\"\n \"io size (bytes),effective batch size (batch size / #replicas),elapsed time (us),\"\n \"QPS,IOPS,bandwidth (MB/s),latency samples,min latency (us),max latency (us),avg latency (us),\"\n \"latency P50 (us),latency P75 (us),latency P90 (us),latency P95 (us),latency P99 (us)\\n\";\n\n if (!outFile) {\n throw std::runtime_error(\"Failed to write to file: \" + outFilePath.string());\n }\n\n outFile.close();\n }\n\n auto elapsedMicro = std::chrono::duration_cast(elapsedTime);\n double bandwidthMBps = totalGiB * 1024.0 / (elapsedMicro.count() / 1'000'000.0);\n size_t ioSize = readIO ? benchOptions_.readSize : benchOptions_.writeSize;\n size_t batchSize = readIO ? benchOptions_.readBatchSize : benchOptions_.writeBatchSize;\n double iops = bandwidthMBps * 1024.0 * 1024.0 / ioSize;\n double qps = bandwidthMBps * 1024.0 * 1024.0 / (batchSize * ioSize);\n\n boost::filesystem::ofstream fout(outFilePath, std::ios_base::app);\n\n fout << fmt::format(\"{},{},{},{},{},{},{},{:.1f},{},{:.1f},{:.1f},{:.3f},{},{:.1f},{:.1f},{:.1f}\",\n testName,\n setupConfig_.num_storage_nodes(),\n setupConfig_.num_chains(),\n setupConfig_.num_replicas(),\n benchOptions_.numCoroutines,\n batchSize,\n ioSize,\n double(batchSize) / setupConfig_.num_storage_nodes(),\n elapsedMicro.count(),\n qps,\n iops,\n bandwidthMBps,\n digest.count(),\n digest.min(),\n digest.max(),\n digest.mean());\n\n for (double p : {0.5, 0.75, 0.9, 0.95, 0.99}) {\n fout << fmt::format(\",{:.1f}\", digest.estimateQuantile(p));\n }\n\n fout << \"\\n\";\n fout.close();\n }\n\n CoTask batchWrite(uint32_t instanceId, size_t writeBatchSize, size_t writeSize, uint32_t numWriteSecs) {\n // create an aligned memory block\n size_t memoryBlockSize = ALIGN_UPPER(setupConfig_.chunk_size(), benchOptions_.memoryAlignment);\n auto memoryBlock = (uint8_t *)folly::aligned_malloc(memoryBlockSize, sysconf(_SC_PAGESIZE));\n auto deleter = [](uint8_t *ptr) { folly::aligned_free(ptr); };\n std::unique_ptr memoryBlockPtr(memoryBlock, deleter);\n std::memset(memoryBlock, 0xFF, memoryBlockSize);\n\n if (benchOptions_.verifyReadData) {\n for (size_t byteIndex = 0; byteIndex < memoryBlockSize; byteIndex++) {\n memoryBlock[byteIndex] = byteIndex;\n }\n }\n\n // register a block of memory\n auto regRes = storageClient_->registerIOBuffer(memoryBlock, memoryBlockSize);\n\n if (regRes.hasError()) {\n co_return regRes.error().code();\n }\n\n // create write IOs\n\n auto ioBuffer = std::move(*regRes);\n\n WriteOptions options;\n options.set_enableChecksum(benchOptions_.verifyWriteChecksum);\n options.debug().set_bypass_disk_io(benchOptions_.benchmarkNetwork);\n options.debug().set_bypass_rdma_xmit(benchOptions_.benchmarkStorage);\n options.debug().set_inject_random_server_error(benchOptions_.injectRandomServerError);\n options.debug().set_inject_random_client_error(benchOptions_.injectRandomClientError);\n options.retry().set_retry_permanent_error(benchOptions_.retryPermanentError);\n\n std::vector elapsedMicroSecs;\n uint64_t numWriteBytes = 0;\n\n std::vector writeIOs;\n writeIOs.reserve(writeBatchSize);\n\n auto benchStart = hf3fs::SteadyClock::now();\n std::vector &chunkInfos = chunkInfos_[instanceId];\n size_t &numCreatedChunks = numCreatedChunks_[instanceId];\n size_t seqChunkIndex = 0;\n\n while (true) {\n if (numWriteSecs) {\n auto accumElapsedSecs =\n std::chrono::duration_cast(hf3fs::SteadyClock::now() - benchStart);\n if (accumElapsedSecs >= std::chrono::seconds(numWriteSecs)) break;\n } else {\n if (numCreatedChunks >= chunkInfos.size()) break;\n }\n\n writeIOs.clear();\n\n for (size_t writeIndex = 0; writeIndex < writeBatchSize; writeIndex++) {\n auto &[chainId, chunkId, chunkSize] = chunkInfos[seqChunkIndex++ % chunkInfos.size()];\n size_t writeOffset = 0;\n size_t writeLength = 0;\n\n if (chunkSize < setupConfig_.chunk_size()) {\n writeOffset = chunkSize;\n writeLength = std::min(writeSize, setupConfig_.chunk_size() - writeOffset);\n chunkSize += writeLength;\n numCreatedChunks += chunkSize == setupConfig_.chunk_size();\n } else {\n writeOffset = folly::Random::rand32(0, setupConfig_.chunk_size() - writeSize);\n writeLength = writeSize;\n }\n\n auto writeIO = storageClient_->createWriteIO(chainId,\n chunkId,\n writeOffset,\n writeLength,\n setupConfig_.chunk_size(),\n &memoryBlock[writeOffset],\n &ioBuffer);\n writeIOs.push_back(std::move(writeIO));\n numWriteBytes += writeLength;\n }\n\n auto rpcStart = hf3fs::SteadyClock::now();\n\n co_await storageClient_->batchWrite(writeIOs, flat::UserInfo(), options);\n\n auto elapsedMicro = std::chrono::duration_cast(hf3fs::SteadyClock::now() - rpcStart);\n elapsedMicroSecs.push_back(elapsedMicro.count());\n\n if (!benchOptions_.ignoreIOError) {\n for (const auto &writeIO : writeIOs) {\n if (writeIO.result.lengthInfo.hasError()) {\n XLOGF(ERR, \"Error in write result: {}\", writeIO.result);\n co_return writeIO.result.lengthInfo.error().code();\n }\n if (writeIO.length != *writeIO.result.lengthInfo) {\n XLOGF(ERR, \"Unexpected write length: {} != {}\", *writeIO.result.lengthInfo, writeIO.length);\n co_return StorageClientCode::kRemoteIOError;\n }\n }\n }\n }\n\n folly::TDigest digest;\n writeLatencyDigests_[instanceId] = digest.merge(elapsedMicroSecs);\n numWriteBytes_ += numWriteBytes;\n\n co_return StatusCode::kOK;\n }\n\n CoTask batchRead(uint32_t instanceId) {\n // create an aligned memory block\n size_t alignedBufSize = ALIGN_UPPER(std::max(size_t(1), benchOptions_.readSize), benchOptions_.memoryAlignment);\n size_t memoryBlockSize = alignedBufSize * benchOptions_.readBatchSize;\n auto memoryBlock = (uint8_t *)folly::aligned_malloc(memoryBlockSize, sysconf(_SC_PAGESIZE));\n auto deleter = [](uint8_t *ptr) { folly::aligned_free(ptr); };\n std::unique_ptr memoryBlockPtr(memoryBlock, deleter);\n std::memset(memoryBlock, 0, memoryBlockSize);\n\n // register a block of memory\n auto regRes = storageClient_->registerIOBuffer(memoryBlock, memoryBlockSize);\n\n if (regRes.hasError()) {\n co_return regRes.error().code();\n }\n\n std::vector expectedChunkData(setupConfig_.chunk_size());\n\n if (benchOptions_.verifyReadData) {\n for (size_t byteIndex = 0; byteIndex < expectedChunkData.size(); byteIndex++) {\n expectedChunkData[byteIndex] = byteIndex;\n }\n }\n\n // create read IOs\n\n auto ioBuffer = std::move(*regRes);\n\n ReadOptions options;\n options.set_enableChecksum(benchOptions_.verifyReadChecksum);\n options.debug().set_bypass_disk_io(benchOptions_.benchmarkNetwork);\n options.debug().set_bypass_rdma_xmit(benchOptions_.benchmarkStorage);\n options.debug().set_inject_random_server_error(benchOptions_.injectRandomServerError);\n options.debug().set_inject_random_client_error(benchOptions_.injectRandomClientError);\n options.retry().set_retry_permanent_error(benchOptions_.retryPermanentError);\n\n std::vector elapsedMicroSecs;\n uint64_t numReadBytes = 0;\n size_t offsetAlignment =\n benchOptions_.readOffAlignment ? benchOptions_.readOffAlignment : std::max(size_t(1), benchOptions_.readSize);\n\n std::vector readIOs;\n readIOs.reserve(benchOptions_.readBatchSize);\n\n auto benchStart = hf3fs::SteadyClock::now();\n std::vector &chunkInfos = chunkInfos_[instanceId];\n\n while (true) {\n auto accumElapsedSecs = std::chrono::duration_cast(hf3fs::SteadyClock::now() - benchStart);\n if (accumElapsedSecs >= std::chrono::seconds(benchOptions_.numReadSecs)) break;\n\n readIOs.clear();\n\n for (size_t readIndex = 0; readIndex < benchOptions_.readBatchSize; readIndex++) {\n uint64_t randChunkIndex = folly::Random::rand64(0, chunkInfos.size());\n const auto &[chainId, chunkId, chunkSize] = chunkInfos[randChunkIndex];\n uint32_t offset = folly::Random::rand32(0, setupConfig_.chunk_size() - benchOptions_.readSize);\n uint32_t alignedOffset = ALIGN_LOWER(offset, offsetAlignment);\n auto readIO = storageClient_->createReadIO(chainId,\n chunkId,\n alignedOffset /*offset*/,\n benchOptions_.readSize /*length*/,\n &memoryBlock[readIndex * alignedBufSize],\n &ioBuffer);\n readIOs.push_back(std::move(readIO));\n numReadBytes += benchOptions_.readSize;\n }\n\n auto rpcStart = hf3fs::SteadyClock::now();\n\n co_await storageClient_->batchRead(readIOs, flat::UserInfo(), options);\n\n auto elapsedMicro = std::chrono::duration_cast(hf3fs::SteadyClock::now() - rpcStart);\n elapsedMicroSecs.push_back(elapsedMicro.count());\n\n if (!benchOptions_.ignoreIOError) {\n for (const auto &readIO : readIOs) {\n if (readIO.result.lengthInfo.hasError()) {\n XLOGF(ERR, \"Error in read result: {}\", readIO.result);\n co_return readIO.result.lengthInfo.error().code();\n }\n if (readIO.length != *readIO.result.lengthInfo) {\n XLOGF(ERR, \"Unexpected read length: {} != {}\", *readIO.result.lengthInfo, readIO.length);\n co_return StorageClientCode::kRemoteIOError;\n }\n }\n }\n\n if (benchOptions_.verifyReadData) {\n for (const auto &readIO : readIOs) {\n auto diffPos = std::mismatch(&readIO.data[0], &readIO.data[readIO.length], &expectedChunkData[readIO.offset]);\n uint32_t byteIndex = diffPos.first - &readIO.data[0];\n if (byteIndex < readIO.length) {\n XLOGF(ERR,\n \"Wrong data at bytes index {} and chunk offset {}: data {:#x} != expected {:#x}\",\n byteIndex,\n readIO.offset + byteIndex,\n *diffPos.first,\n *diffPos.second);\n co_return StorageClientCode::kFoundBug;\n }\n }\n }\n }\n\n folly::TDigest digest;\n readLatencyDigests_[instanceId] = digest.merge(elapsedMicroSecs);\n numReadBytes_ += numReadBytes;\n\n co_return StatusCode::kOK;\n }\n\n uint32_t generateChunks() {\n XLOGF(WARN, \"Generating {} test chunks ({:.3f} GiB)...\", totalNumChunks_, totalChunkGiB_);\n\n auto testStart = hf3fs::SteadyClock::now();\n std::vector> writeTasks;\n numWriteBytes_ = 0;\n\n size_t writeBatchSize =\n std::max(benchOptions_.writeBatchSize,\n clientConfig_.traffic_control().write().max_concurrent_requests() / benchOptions_.numCoroutines);\n\n for (size_t instanceId = 0; instanceId < benchOptions_.numCoroutines; instanceId++) {\n writeTasks.push_back(batchWrite(instanceId, writeBatchSize, setupConfig_.chunk_size(), 0 /*numWriteSecs*/)\n .scheduleOn(folly::Executor::getKeepAliveToken(testExecutor_))\n .start());\n }\n\n auto results = folly::coro::blockingWait(folly::coro::collectAllRange(std::move(writeTasks)));\n\n for (auto res : results) {\n if (res != StatusCode::kOK) {\n XLOGF(WARN, \"Test task failed with status code: {}\", res);\n return res;\n }\n }\n\n auto elapsedTime = hf3fs::SteadyClock::now() - testStart;\n double totalGiB = (double)numWriteBytes_ / 1_GB;\n printThroughput(elapsedTime, totalGiB);\n\n auto mergedDigest = folly::TDigest::merge(writeLatencyDigests_);\n printLatencyDigest(mergedDigest);\n\n return StatusCode::kOK;\n }\n\n uint32_t runWriteBench() {\n XLOGF(WARN,\n \"Running write benchmark ({} secs, {} chunks, {:.3f} GiB)...\",\n benchOptions_.numWriteSecs,\n totalNumChunks_,\n totalChunkGiB_);\n\n auto testStart = hf3fs::SteadyClock::now();\n std::vector> writeTasks;\n numWriteBytes_ = 0;\n\n for (size_t instanceId = 0; instanceId < benchOptions_.numCoroutines; instanceId++) {\n writeTasks.push_back(\n batchWrite(instanceId, benchOptions_.writeBatchSize, benchOptions_.writeSize, benchOptions_.numWriteSecs)\n .scheduleOn(folly::Executor::getKeepAliveToken(testExecutor_))\n .start());\n }\n\n auto results = folly::coro::blockingWait(folly::coro::collectAllRange(std::move(writeTasks)));\n\n for (auto res : results) {\n if (res != StatusCode::kOK) {\n XLOGF(WARN, \"Test task failed with status code: {}\", res);\n return res;\n }\n }\n\n auto elapsedTime = hf3fs::SteadyClock::now() - testStart;\n double totalGiB = (double)numWriteBytes_ / 1_GB;\n printThroughput(elapsedTime, totalGiB);\n\n auto mergedDigest = folly::TDigest::merge(writeLatencyDigests_);\n printLatencyDigest(mergedDigest);\n\n dumpPerfStats(\"batch write\", mergedDigest, elapsedTime, totalGiB, false /*readIO*/);\n\n return StatusCode::kOK;\n }\n\n uint32_t runReadBench() {\n XLOGF(WARN, \"Running read benchmark ({} secs)...\", benchOptions_.numReadSecs);\n\n auto testStart = hf3fs::SteadyClock::now();\n std::vector> readTasks;\n numReadBytes_ = 0;\n\n for (size_t instanceId = 0; instanceId < benchOptions_.numCoroutines; instanceId++) {\n readTasks.push_back(batchRead(instanceId).scheduleOn(folly::Executor::getKeepAliveToken(testExecutor_)).start());\n }\n\n auto results = folly::coro::blockingWait(folly::coro::collectAllRange(std::move(readTasks)));\n\n for (auto res : results) {\n if (res != StatusCode::kOK) {\n XLOGF(WARN, \"Test task failed with status code: {}\", res);\n return res;\n }\n }\n\n auto elapsedTime = hf3fs::SteadyClock::now() - testStart;\n double totalGiB = (double)numReadBytes_ / 1_GB;\n printThroughput(elapsedTime, totalGiB);\n\n auto mergedDigest = folly::TDigest::merge(readLatencyDigests_);\n printLatencyDigest(mergedDigest);\n\n dumpPerfStats(\"batch read\", mergedDigest, elapsedTime, totalGiB, false /*readIO*/);\n\n return StatusCode::kOK;\n }\n\n uint32_t cleanup() {\n XLOGF(WARN, \"Clean up chunks...\");\n\n std::vector> removeTasks;\n\n for (size_t instanceId = 0; instanceId < benchOptions_.numCoroutines; instanceId++) {\n auto batchRemove = [this](size_t instanceId) -> folly::coro::Task {\n std::vector removeOps;\n size_t totalNumChunksRemoved = 0;\n\n for (const auto &[chainId, chunkId, chunkSize] : chunkInfos_[instanceId]) {\n removeOps.push_back(storageClient_->createRemoveOp(chainId, chunkId, ChunkId(chunkId, 1)));\n\n if (removeOps.size() >= benchOptions_.removeBatchSize) {\n WriteOptions options;\n options.debug().set_inject_random_server_error(benchOptions_.injectRandomServerError);\n options.debug().set_inject_random_client_error(benchOptions_.injectRandomClientError);\n options.retry().set_retry_permanent_error(benchOptions_.retryPermanentError);\n\n co_await storageClient_->removeChunks(removeOps, flat::UserInfo(), options);\n\n for (const auto &removeOp : removeOps) {\n if (removeOp.result.statusCode.hasError()) {\n XLOGF(WARN, \"Remove operation failed with error: {}\", removeOp.result.statusCode.error());\n co_return removeOp.result.statusCode.error().code();\n }\n\n XLOGF_IF(DBG5,\n removeOp.result.numChunksRemoved != 1,\n \"{} chunks removed in range {}\",\n removeOp.result.numChunksRemoved,\n removeOp.chunkRange());\n totalNumChunksRemoved += removeOp.result.numChunksRemoved;\n }\n\n removeOps.clear();\n }\n }\n\n XLOGF(WARN, \"{} chunks removed by instance #{}\", totalNumChunksRemoved, instanceId);\n co_return StatusCode::kOK;\n };\n\n removeTasks.push_back(\n batchRemove(instanceId).scheduleOn(folly::Executor::getKeepAliveToken(testExecutor_)).start());\n }\n\n auto results = folly::coro::blockingWait(folly::coro::collectAllRange(std::move(removeTasks)));\n\n for (auto res : results) {\n if (res != StatusCode::kOK) {\n XLOGF(WARN, \"Test task failed with status code: {}\", res);\n return res;\n }\n }\n\n return StatusCode::kOK;\n };\n\n uint32_t truncate() {\n XLOGF(WARN, \"Truncate chunks...\");\n\n std::vector> truncateTasks;\n\n for (size_t instanceId = 0; instanceId < benchOptions_.numCoroutines; instanceId++) {\n auto batchTruncate = [this](size_t instanceId) -> folly::coro::Task {\n std::vector truncateOps;\n\n for (const auto &[chainId, chunkId, chunkSize] : chunkInfos_[instanceId]) {\n truncateOps.push_back(storageClient_->createTruncateOp(chainId, chunkId, 0, setupConfig_.chunk_size()));\n\n if (truncateOps.size() >= benchOptions_.writeBatchSize) {\n WriteOptions options;\n options.debug().set_inject_random_server_error(benchOptions_.injectRandomServerError);\n options.debug().set_inject_random_client_error(benchOptions_.injectRandomClientError);\n options.retry().set_retry_permanent_error(benchOptions_.retryPermanentError);\n\n co_await storageClient_->truncateChunks(truncateOps, flat::UserInfo(), options);\n\n for (const auto &truncateOp : truncateOps) {\n if (truncateOp.result.lengthInfo.hasError()) {\n XLOGF(WARN, \"Truncate operation failed with error: {}\", truncateOp.result.lengthInfo.error());\n co_return truncateOp.result.lengthInfo.error().code();\n }\n }\n\n truncateOps.clear();\n }\n }\n\n co_return StatusCode::kOK;\n };\n\n truncateTasks.push_back(\n batchTruncate(instanceId).scheduleOn(folly::Executor::getKeepAliveToken(testExecutor_)).start());\n }\n\n auto results = folly::coro::blockingWait(folly::coro::collectAllRange(std::move(truncateTasks)));\n\n for (auto res : results) {\n if (res != StatusCode::kOK) {\n XLOGF(WARN, \"Test task failed with status code: {}\", res);\n return res;\n }\n }\n\n return StatusCode::kOK;\n };\n\n bool run() {\n if (benchOptions_.numWriteSecs > 0)\n if (runWriteBench() != StatusCode::kOK) return false;\n if (benchOptions_.generateTestData)\n if (generateChunks() != StatusCode::kOK) return false;\n if (benchOptions_.numReadSecs > 0)\n if (runReadBench() != StatusCode::kOK) return false;\n return true;\n }\n\n uint64_t getWriteBytes() { return numWriteBytes_; }\n\n uint64_t getReadBytes() { return numReadBytes_; }\n};\n\n} // namespace hf3fs::storage::benchmark\n"], ["/3FS/src/fbs/meta/Common.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/app/ClientId.h\"\n#include \"common/serde/Serde.h\"\n#include \"common/serde/SerdeComparisons.h\"\n#include \"common/utils/Path.h\"\n#include \"common/utils/Result.h\"\n#include \"common/utils/StrongType.h\"\n#include \"common/utils/UtcTime.h\"\n#include \"common/utils/UtcTimeSerde.h\"\n#include \"fbs/core/user/User.h\"\n\n#define VALID Void()\n#define INVALID(str) makeError(StatusCode::kInvalidArg, str)\n\n#define FS_CHAIN_ALLOCATION_FL FS_INDEX_FL /* reuse attr 'I', this directory has it't own chain allocation counter */\n#define FS_NEW_CHUNK_ENGINE FS_SECRM_FL /* reuse attr 's', files under this directory will use new chunk engine */\n#define FS_FL_SUPPORTED (FS_IMMUTABLE_FL | FS_CHAIN_ALLOCATION_FL | FS_NEW_CHUNK_ENGINE | FS_HUGE_FILE_FL)\n#define FS_FL_INHERITABLE (FS_CHAIN_ALLOCATION_FL | FS_NEW_CHUNK_ENGINE)\n\nnamespace hf3fs::meta {\n\nusing flat::Gid;\nusing flat::Permission;\nusing flat::Uid;\nusing flat::UserAttr;\nusing flat::UserInfo;\n\n// see: ioctl_iflags\nSTRONG_TYPEDEF(uint32_t, IFlags);\n\nstruct SessionInfo {\n SERDE_STRUCT_FIELD(client, ClientId::zero());\n SERDE_STRUCT_FIELD(session, Uuid::zero());\n\n public:\n SessionInfo() = default;\n SessionInfo(ClientId client, Uuid session)\n : client(client),\n session(session) {}\n constexpr bool valid() const { return client != ClientId::zero() && session != Uuid::zero(); }\n constexpr operator bool() const { return valid(); }\n};\n\nenum AccessType {\n EXEC = 1,\n WRITE = 2,\n READ = 4,\n};\n\nBOOST_BITMASK(AccessType)\n\ntemplate \nclass BitFlags {\n public:\n using Self = C;\n constexpr BitFlags(T val = 0)\n : val_(val) {}\n using is_serde_copyable = void;\n\n T mask(T m) const { return val_ & m; }\n bool contains(T bits) const { return mask(bits) == bits; }\n void set(T bits) { val_ |= bits; }\n void clear(T bits) { val_ &= (~bits); }\n\n T toUnderType() const { return val_; }\n operator const T &() const { return val_; }\n operator T &() { return val_; }\n Self operator|(const T other) const { return Self(val_ | other); }\n\n std::string serdeToReadable() const { return fmt::format(\"{:x}\", val_); }\n\n static Result serdeFromReadable(std::string_view str) {\n auto [r, v] = scn::scan_tuple(str, \"{:x}\");\n if (!r)\n return makeError(StatusCode::kDataCorruption,\n fmt::format(\"SCN({}): {}\", magic_enum::enum_name(r.error().code()), r.error().msg()));\n return Self(v);\n }\n\n private:\n T val_;\n};\n\nclass OpenFlags : public BitFlags {\n public:\n using Base = BitFlags;\n using Base::Base;\n\n AccessType accessType() const {\n switch (mask(O_ACCMODE)) {\n case O_RDONLY:\n return AccessType::READ;\n case O_WRONLY:\n return AccessType::WRITE;\n case O_RDWR:\n default:\n return AccessType::READ | AccessType::WRITE;\n }\n }\n operator AccessType() const { return accessType(); }\n\n Result valid() const {\n if (contains(O_DIRECTORY)) {\n if (accessType() != AccessType::READ) return makeError(StatusCode::kInvalidArg, \"O_DIRECTORY & WRITE\");\n if (contains(O_TRUNC)) return makeError(StatusCode::kInvalidArg, \"O_DIRECTORY & O_TRUNC\");\n }\n return Void{};\n }\n};\n\nclass AtFlags : public BitFlags {\n public:\n explicit AtFlags(int32_t val = 0)\n : BitFlags(val) {}\n\n Result valid() const { return Void{}; }\n bool followLastSymlink() const { return contains(AT_SYMLINK_FOLLOW) && !contains(AT_SYMLINK_NOFOLLOW); }\n};\n\nclass InodeId {\n public:\n // Use little endian form as key in FoundationDB, it helps to avoid hot spot\n using Key = std::array;\n using is_serde_copyable = void;\n\n static constexpr size_t trees() { return 2; }\n static constexpr InodeId root() { return InodeId(0); }\n static constexpr InodeId gcRoot() { return InodeId(1); }\n\n // InodeId: 0 ~ 0x01ffffffffffffff\n // If InodeId starts with 0x01: use new 3FS Chunk Engine\n static constexpr uint64_t kNewChunkEngineMask = (1ull << 56);\n static_assert(kNewChunkEngineMask == 0x0100000000000000ull);\n static constexpr InodeId withNewChunkEngine(InodeId orig) { return InodeId(orig.u64() | kNewChunkEngineMask); }\n static constexpr InodeId normalMax() { return InodeId::withNewChunkEngine(InodeId((1ull << 56) - 1)); }\n\n // special InodeId used by Client\n // 3fs-virt InodeId: 0xfffffffffffffffe\n static constexpr InodeId virt() { return InodeId(uint64_t(-2)); }\n // iov InodeId range [0xffffffff7ffe0002, 0xffffffff7fff0001]\n static constexpr int iovIidStart = 65535;\n static constexpr InodeId iovDir() { return InodeId((uint64_t) - (1ull << 31)); }\n static constexpr InodeId iov(int iovd) { return InodeId(iovDir().u64() - iovIidStart - iovd); }\n\n // 3fs-virt/rm-rf: 0xfffffffffffffffd\n static constexpr InodeId rmRf() { return InodeId(-3); }\n // temporary InodeId used by rm-rf or mv symlink: [0xfdffffe700000001, 0xffffffe700000000]\n static constexpr InodeId virtTemporary(InodeId toRemove) { return InodeId(-(100ull << 30) - toRemove.u64()); }\n\n // 0xffffffff00000000\n static constexpr InodeId getConf() { return InodeId(-((uint64_t)2 << 31)); }\n // 0xfffffffe80000000\n static constexpr InodeId setConf() { return InodeId(-((uint64_t)3 << 31)); }\n\n explicit constexpr InodeId(uint64_t val = 0)\n : val_(val) {}\n\n // InodeId &operator=(uint64_t val) {\n // val_ = val;\n // return *this;\n // }\n\n Key packKey() const {\n auto le = folly::Endian::little(val_);\n return folly::bit_cast(le);\n }\n static InodeId unpackKey(const Key &key) {\n auto le = folly::bit_cast(key);\n return InodeId(folly::Endian::little(le));\n }\n\n std::string toHexString() const { return fmt::format(\"0x{:016x}\", val_); }\n std::string serdeToReadable() const { return toHexString(); }\n operator folly::dynamic() const { return toHexString(); }\n constexpr uint64_t u64() const { return val_; }\n // constexpr operator uint64_t() const { return u64(); }\n constexpr auto operator<=>(const InodeId &o) const { return this->val_ <=> o.val_; }\n constexpr auto operator==(const InodeId &o) const { return this->val_ == o.val_; }\n\n bool isTreeRoot() const { return *this == root() || *this == gcRoot(); }\n\n bool useNewChunkEngine() const { return u64() & kNewChunkEngineMask; }\n\n private:\n uint64_t val_;\n};\n\n// check 3fs-virt InodeIds\nstatic_assert(InodeId::normalMax().u64() == 0x01ffffffffffffffull);\nstatic_assert(InodeId::virt().u64() == 0xfffffffffffffffeull);\nstatic_assert(InodeId::iovDir().u64() == 0xffffffff80000000ull);\nstatic_assert(InodeId::iov(0).u64() == 0xffffffff7fff0001ull);\nstatic_assert(InodeId::iov(65535).u64() == 0xffffffff7ffe0002ull);\nstatic_assert(InodeId::rmRf().u64() == 0xfffffffffffffffdull);\nstatic_assert(InodeId::virtTemporary(InodeId(0)).u64() == 0xffffffe700000000ull);\nstatic_assert(InodeId::virtTemporary(InodeId(0x1ffffffffffffff)).u64() == 0xfdffffe700000001ull);\nstatic_assert(InodeId::getConf().u64() == 0xffffffff00000000ull);\nstatic_assert(InodeId::setConf().u64() == 0xfffffffe80000000ull);\n\n// check 3fs-virt InodeIds won't conflict with each other and normal InodeIds\nstatic constexpr auto spacialInodeRanges =\n std::to_array({InodeId::normalMax(),\n InodeId(0xfd00000000000000ull), // all virt must start with 0xf\n InodeId::virtTemporary(InodeId::normalMax()),\n InodeId::virtTemporary(InodeId(0)),\n InodeId::setConf(),\n InodeId::getConf(),\n InodeId::iov(65535),\n InodeId::iov(0),\n InodeId::iovDir(),\n InodeId::rmRf(),\n InodeId::virt()});\nconstexpr inline bool checkSpecialInode() {\n for (uint64_t i = 1; i < spacialInodeRanges.size(); i++) {\n if (spacialInodeRanges[i] <= spacialInodeRanges[i - 1]) {\n return false;\n }\n }\n return true;\n}\nstatic_assert(checkSpecialInode());\n\nstruct PathAt {\n SERDE_STRUCT_FIELD(parent, InodeId(0));\n SERDE_STRUCT_FIELD(path, std::optional());\n\n public:\n PathAt(InodeId parent = InodeId::root())\n : PathAt(parent, std::nullopt) {}\n PathAt(Path path)\n : PathAt(InodeId::root(), std::move(path)) {}\n PathAt(std::string path)\n : PathAt(Path(path)) {}\n PathAt(const char *p)\n : PathAt(Path(p)) {}\n PathAt(InodeId parent, std::optional path)\n : parent(parent),\n path(std::move(path)) {}\n Result validForCreate() const {\n if (!path.has_value() || path->empty()) return INVALID(\"path not set\");\n if (!path->has_filename()) return INVALID(\"doesn't have filename\");\n if (path->filename_is_dot()) return INVALID(\"filename is .\");\n if (path->filename_is_dot_dot()) return INVALID(\"filename is ..\");\n if (path->filename() == \"/\") return INVALID(\"filename is /\");\n return VALID;\n }\n bool operator==(const PathAt &o) const { return serde::equals(*this, o); }\n};\n\n} // namespace hf3fs::meta\n\ntemplate <>\nstruct std::hash {\n size_t operator()(const hf3fs::meta::InodeId &id) const { return robin_hood::hash_int(id.u64()); }\n};\n\ntemplate <>\nstruct hf3fs::serde::SerdeMethod {\n static constexpr auto serdeTo(const hf3fs::meta::InodeId &id) { return id.u64(); }\n static Result serdeFrom(uint64_t id) { return hf3fs::meta::InodeId(id); }\n};\n\nFMT_BEGIN_NAMESPACE\n\ntemplate <>\nstruct formatter : formatter {\n template \n auto format(const hf3fs::meta::InodeId &id, FormatContext &ctx) const {\n return fmt::format_to(ctx.out(), \"0x{:016x}\", id.u64());\n }\n};\n\nFMT_END_NAMESPACE\n"], ["/3FS/src/client/mgmtd/CommonMgmtdClient.h", "#pragma once\n\n#include \"ICommonMgmtdClient.h\"\n#include \"MgmtdClient.h\"\n\nnamespace hf3fs::client {\ntemplate \nclass CommonMgmtdClient : public Base {\n public:\n explicit CommonMgmtdClient(std::shared_ptr client)\n : client_(std::move(client)) {}\n\n CoTask start(folly::Executor *backgroundExecutor = nullptr, bool startBackground = true) final {\n return client_->start(backgroundExecutor, startBackground);\n }\n\n CoTask startBackgroundTasks() final { return client_->startBackgroundTasks(); }\n\n CoTask stop() final { return client_->stop(); }\n\n std::shared_ptr getRoutingInfo() final { return client_->getRoutingInfo(); }\n\n CoTryTask refreshRoutingInfo(bool force) final { return client_->refreshRoutingInfo(force); }\n\n bool addRoutingInfoListener(String name, ICommonMgmtdClient::RoutingInfoListener listener) final {\n return client_->addRoutingInfoListener(std::move(name), std::move(listener));\n }\n\n bool removeRoutingInfoListener(std::string_view name) final { return client_->removeRoutingInfoListener(name); }\n\n CoTryTask listClientSessions() final { return client_->listClientSessions(); }\n\n CoTryTask> getConfig(flat::NodeType nodeType, flat::ConfigVersion version) final {\n return client_->getConfig(nodeType, version);\n }\n\n CoTryTask> getUniversalTags(const String &universalId) final {\n return client_->getUniversalTags(universalId);\n }\n\n CoTryTask> getConfigVersions() final { return client_->getConfigVersions(); }\n\n CoTryTask getClientSession(const String &clientId) final {\n return client_->getClientSession(clientId);\n }\n\n protected:\n std::shared_ptr client_;\n};\n} // namespace hf3fs::client\n"], ["/3FS/src/meta/store/BatchContext.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/Result.h\"\n#include \"fbs/meta/Common.h\"\n#include \"fbs/meta/Schema.h\"\n#include \"meta/store/DirEntry.h\"\n#include \"meta/store/Inode.h\"\nnamespace hf3fs::meta::server {\n\nclass BatchContext : public folly::RequestData {\n public:\n template \n struct SharedFuture : folly::NonCopyableNonMovable {\n Result value = makeError(StatusCode::kUnknown);\n folly::coro::Baton baton;\n };\n\n template \n struct LoadGuard {\n bool needLoad;\n std::shared_ptr> future;\n\n LoadGuard(bool needLoad, std::shared_ptr> future)\n : needLoad(needLoad),\n future(future) {}\n\n ~LoadGuard() {\n if (needLoad && !future->baton.ready()) {\n future->value = makeError(StatusCode::kUnknown, \"load failed in BatchContext\");\n future->baton.post();\n }\n }\n\n void set(const Result &r) {\n assert(!future->baton.ready());\n future->value = r;\n future->baton.post();\n }\n\n CoTryTask coAwait() {\n co_await future->baton;\n co_return future->value;\n }\n };\n\n static folly::ShallowCopyRequestContextScopeGuard create() {\n return folly::ShallowCopyRequestContextScopeGuard{token(), std::make_unique()};\n }\n\n static inline BatchContext *get() {\n auto requestContext = folly::RequestContext::try_get();\n if (LIKELY(requestContext == nullptr)) {\n return nullptr;\n }\n return dynamic_cast(requestContext->getContextData(token()));\n }\n\n LoadGuard> loadInode(InodeId inodeId) {\n return loadImpl>(inodes_, inodeId);\n }\n\n LoadGuard> loadDirEntry(InodeId parent, std::string name) {\n return loadImpl, std::optional>(entries_, {parent, std::move(name)});\n }\n\n bool hasCallback() override { return false; }\n\n private:\n static constexpr const char *kTokenName = \"hf3fs::meta::server::BatchContext\";\n\n static folly::RequestToken const &token() {\n static folly::RequestToken const token(kTokenName);\n return token;\n }\n\n template \n using SynchronizedFutureMap = folly::Synchronized>>, std::mutex>;\n\n template \n LoadGuard loadImpl(SynchronizedFutureMap &map, K key) {\n auto guard = map.lock();\n auto iter = guard->find(key);\n if (iter != guard->end()) {\n return LoadGuard(false, iter->second);\n }\n auto future = std::make_shared>();\n guard->emplace(std::move(key), future);\n return LoadGuard(true, future);\n }\n\n SynchronizedFutureMap> inodes_;\n SynchronizedFutureMap, std::optional> entries_;\n};\n\n} // namespace hf3fs::meta::server"], ["/3FS/src/common/net/Listener.h", "#pragma once\n\n#include \n#include \n#include \n\n#include \"common/net/IOWorker.h\"\n#include \"common/net/Network.h\"\n#include \"common/net/Transport.h\"\n#include \"common/net/ib/IBConnectService.h\"\n#include \"common/net/ib/IBSocket.h\"\n#include \"common/utils/ConfigBase.h\"\n\nnamespace hf3fs::net {\n\nclass ServiceGroup;\n\nclass Listener {\n public:\n class Config : public ConfigBase {\n CONFIG_ITEM(listen_port, uint16_t{0});\n CONFIG_ITEM(reuse_port, false);\n CONFIG_ITEM(listen_queue_depth, 4096u);\n CONFIG_ITEM(filter_list, std::set{}); // use all available network cards if filter is empty.\n CONFIG_ITEM(rdma_listen_ethernet, true); // support setup RDMA connection with Ethernet by default.\n CONFIG_ITEM(domain_socket_index, 1u);\n CONFIG_HOT_UPDATED_ITEM(rdma_accept_timeout, 15_s);\n };\n\n Listener(const Config &config,\n const IBSocket::Config &ibconfig,\n IOWorker &ioWorker,\n folly::IOThreadPoolExecutor &connThreadPool,\n Address::Type networkType);\n ~Listener() { stopAndJoin(); }\n\n // setup listener.\n Result setup();\n\n // start listening.\n Result start(ServiceGroup &group);\n\n // stop listening.\n void stopAndJoin();\n\n // get listening address list.\n const std::vector
&addressList() const { return addressList_; }\n\n protected:\n // do listen with calcellation support.\n CoTask listen(folly::coro::ServerSocket socket);\n\n // accept a TCP connection.\n CoTask acceptTCP(std::unique_ptr tr);\n\n // accept a RDMA connection.\n void acceptRDMA(std::unique_ptr socket);\n CoTask checkRDMA(std::weak_ptr weak);\n\n // release a TCP connection.\n CoTask release(folly::coro::ServerSocket /* socket */);\n\n private:\n const Config &config_;\n const IBSocket::Config &ibconfig_;\n IOWorker &ioWorker_;\n folly::IOThreadPoolExecutor &connThreadPool_;\n Address::Type networkType_;\n\n CancellationSource cancel_;\n std::vector
addressList_;\n std::vector serverSockets_;\n std::atomic running_{0};\n};\n\n} // namespace hf3fs::net\n"], ["/3FS/src/migration/service/Server.h", "#pragma once\n\n#include \n\n#include \"client/mgmtd/MgmtdClientForClient.h\"\n#include \"client/storage/StorageClient.h\"\n#include \"common/logging/LogConfig.h\"\n#include \"common/net/Client.h\"\n#include \"common/net/Server.h\"\n#include \"common/utils/BackgroundRunner.h\"\n#include \"common/utils/ConfigBase.h\"\n#include \"core/app/ServerAppConfig.h\"\n#include \"core/app/ServerLauncher.h\"\n#include \"core/app/ServerLauncherConfig.h\"\n#include \"core/app/ServerMgmtdClientFetcher.h\"\n\nnamespace hf3fs::migration::server {\n\nclass MigrationServer : public net::Server {\n public:\n static constexpr auto kName = \"Migration\";\n static constexpr auto kNodeType = flat::NodeType::CLIENT;\n\n struct CommonConfig : public ApplicationBase::Config {\n CommonConfig() {\n using logging::LogConfig;\n log().set_categories({LogConfig::makeRootCategoryConfig(), LogConfig::makeEventCategoryConfig()});\n log().set_handlers({LogConfig::makeNormalHandlerConfig(),\n LogConfig::makeErrHandlerConfig(),\n LogConfig::makeFatalHandlerConfig(),\n LogConfig::makeEventHandlerConfig()});\n }\n };\n\n struct Config : public ConfigBase {\n CONFIG_OBJ(base, net::Server::Config, [](net::Server::Config &c) {\n c.set_groups_length(2);\n c.groups(0).listener().set_listen_port(8000);\n c.groups(0).set_services({\"MigrationSerde\"});\n\n c.groups(1).set_network_type(net::Address::TCP);\n c.groups(1).listener().set_listen_port(9000);\n c.groups(1).set_use_independent_thread_pool(true);\n c.groups(1).set_services({\"Core\"});\n });\n CONFIG_OBJ(background_client, net::Client::Config);\n CONFIG_OBJ(mgmtd_client, ::hf3fs::client::MgmtdClientForClient::Config);\n CONFIG_OBJ(storage_client, storage::client::StorageClient::Config);\n };\n\n MigrationServer(const Config &config);\n ~MigrationServer() override;\n\n Result beforeStart() final;\n\n Result beforeStop() final;\n\n private:\n const Config &config_;\n const ClientId clientId_;\n\n std::unique_ptr backgroundClient_;\n std::shared_ptr<::hf3fs::client::IMgmtdClientForClient> mgmtdClient_;\n};\n\n} // namespace hf3fs::migration::server\n"], ["/3FS/src/storage/service/ReliableUpdate.h", "#pragma once\n\n#include \"common/net/Transport.h\"\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/Duration.h\"\n#include \"common/utils/LockManager.h\"\n#include \"common/utils/RobinHood.h\"\n#include \"common/utils/Shards.h\"\n#include \"common/utils/Size.h\"\n#include \"fbs/storage/Common.h\"\n#include \"storage/service/TargetMap.h\"\n\nnamespace hf3fs::storage {\n\nstruct Components;\nclass StorageOperator;\n\nclass ReliableUpdate {\n public:\n struct Config : ConfigBase {\n CONFIG_HOT_UPDATED_ITEM(clean_up_expired_clients, false);\n CONFIG_HOT_UPDATED_ITEM(expired_clients_timeout, 1_h);\n };\n ReliableUpdate(const Config &config, Components &components)\n : config_(config),\n components_(components) {}\n\n CoTask update(ServiceRequestContext &requestCtx,\n UpdateReq &req,\n net::IBSocket *ibSocket,\n TargetPtr &target);\n\n Result cleanUpExpiredClients(const robin_hood::unordered_set &activeClients);\n\n void beforeStop() { stopped_ = true; }\n\n private:\n ConstructLog<\"storage::ReliableUpdate\"> constructLog_;\n const Config &config_;\n Components &components_;\n std::atomic stopped_ = false;\n folly::coro::Mutex mutex_;\n\n struct ReqResult {\n SERDE_STRUCT_FIELD(channelSeqnum, ChannelSeqNum{0});\n SERDE_STRUCT_FIELD(requestId, RequestId{0});\n SERDE_STRUCT_FIELD(updateResult, IOResult{});\n SERDE_STRUCT_FIELD(succUpdateVer, ChunkVer{});\n SERDE_STRUCT_FIELD(generationId, uint32_t{});\n };\n\n struct ClientStatus {\n std::unordered_map, ReqResult> channelMap;\n UtcTime lastUsedTime;\n };\n using ClientMap = std::unordered_map>;\n Shards shards_;\n};\n\n} // namespace hf3fs::storage\n"], ["/3FS/src/meta/store/Inode.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/kv/ITransaction.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/Path.h\"\n#include \"common/utils/Result.h\"\n#include \"common/utils/UtcTime.h\"\n#include \"common/utils/Uuid.h\"\n#include \"fbs/meta/Common.h\"\n#include \"fbs/meta/Schema.h\"\n\nnamespace hf3fs::meta::server {\nusing hf3fs::kv::IReadOnlyTransaction;\nusing hf3fs::kv::IReadWriteTransaction;\n\nclass Inode : public meta::Inode {\n public:\n using Base = meta::Inode;\n using Base::Base;\n\n Inode(Base base)\n : Base(std::move(base)) {}\n Inode(InodeId id, Acl acl, UtcTime time, std::variant type)\n : Base{id, InodeData{type, acl, 1, time, time, time}} {}\n\n static Inode newFile(InodeId id, Acl acl, Layout layout, UtcTime time) { return Inode(id, acl, time, File(layout)); }\n\n static Inode newDirectory(InodeId id, InodeId parent, std::string name, Acl acl, Layout layout, UtcTime time) {\n return Inode(id, acl, time, Directory{parent, std::move(layout), std::move(name)});\n }\n\n static Inode newSymlink(InodeId id, Path target, Uid uid, Gid gid, UtcTime time) {\n static constexpr Permission perm{0777}; // permission of symlink is never used, and won't changed\n return Inode(id, Acl(uid, gid, perm), time, Symlink{std::move(target)});\n }\n\n /** key format: kInodePrefx + InodeId.key */\n static std::string packKey(InodeId id);\n std::string packKey() const;\n Result unpackKey(std::string_view key);\n\n static Result newUnpacked(std::string_view key, std::string_view value);\n\n // The difference of `snapshotLoad` and `load` is the former won't add key of inode into read conflict set.\n static CoTryTask> snapshotLoad(IReadOnlyTransaction &txn, InodeId id);\n static CoTryTask> load(IReadOnlyTransaction &txn, InodeId id);\n\n CoTryTask addIntoReadConflict(IReadWriteTransaction &txn) {\n#ifndef NDEBUG\n snapshotLoaded_ = false;\n#endif\n co_return co_await txn.addReadConflict(packKey());\n }\n\n CoTryTask store(IReadWriteTransaction &txn) const;\n /** Remove this inode */\n CoTryTask remove(IReadWriteTransaction &txn) const;\n\n CoTryTask snapshotLoadDirEntry(IReadOnlyTransaction &txn) const;\n\n static CoTryTask loadAncestors(IReadWriteTransaction &txn, std::vector &ancestors, InodeId parent);\n\n private:\n template \n static CoTryTask> loadImpl(IReadOnlyTransaction &txn, InodeId id);\n\n#ifndef NDEBUG\n mutable bool snapshotLoaded_ = false;\n#endif\n};\n\nstatic_assert(serde::SerializableToJson);\n} // namespace hf3fs::meta::server\n"], ["/3FS/src/meta/store/Idempotent.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"common/kv/ITransaction.h\"\n#include \"common/kv/KeyPrefix.h\"\n#include \"common/serde/MessagePacket.h\"\n#include \"common/serde/Serde.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/Duration.h\"\n#include \"common/utils/Nameof.hpp\"\n#include \"common/utils/Result.h\"\n#include \"common/utils/SerDeser.h\"\n#include \"common/utils/UtcTime.h\"\n#include \"common/utils/Uuid.h\"\n#include \"fbs/meta/Service.h\"\n\nnamespace hf3fs::meta::server {\n/** Store transaction result to ensure idempotency during retries. Currently used for remove operations.\n */\nstruct Idempotent {\n static constexpr auto keyPrefix = kv::KeyPrefix::MetaIdempotent;\n\n template \n struct Record {\n Record() requires(std::is_same_v) = default;\n explicit Record(const T &result)\n : result(result) {}\n\n SERDE_STRUCT_FIELD(clientId, Uuid::zero());\n SERDE_STRUCT_FIELD(requestId, Uuid::zero());\n SERDE_STRUCT_FIELD(timestamp, UtcTime());\n SERDE_STRUCT_FIELD(result, serde::Payload());\n\n public:\n std::string packKey() const {\n // requestId + clientId to avoid hotspot\n XLOGF_IF(FATAL, clientId == Uuid::zero() || requestId == Uuid::zero(), \"invalid uuid\");\n return Serializer::serRawArgs(keyPrefix, requestId, clientId);\n }\n };\n\n template \n static CoTryTask>> load(kv::IReadWriteTransaction &txn,\n const Uuid clientId,\n const Uuid requestId,\n const ReqInfo &req) {\n if (clientId == Uuid::zero() || requestId == Uuid::zero()) {\n XLOGF(CRITICAL, \"Request invalid uuid {} {}\", clientId, requestId);\n co_return makeError(StatusCode::kInvalidArg, \"Invalid uuid\");\n }\n\n Record record;\n record.clientId = clientId;\n record.requestId = requestId;\n auto res = co_await txn.get(record.packKey());\n CO_RETURN_ON_ERROR(res);\n if (!res->has_value()) {\n co_return std::nullopt;\n }\n auto desRes = serde::deserialize(record, res->value());\n if (!desRes) {\n XLOGF(DFATAL, \"IdempotentRecord deserialize failed, request {}, error {}\", req, desRes.error());\n co_return makeError(StatusCode::kDataCorruption, \"IdempotentRecord des failed\");\n }\n if (record.clientId != clientId || record.requestId != requestId) {\n XLOGF(DFATAL, \"IdempotentRecord mismatch, request {}, record {}\", req, record);\n co_return makeError(MetaCode::kInconsistent, \"IdempotentRecord uuid mismatch\");\n }\n\n Result result = makeError(StatusCode::kUnknown);\n auto desResult = serde::deserialize(result, record.result);\n if (!desResult) {\n XLOGF(DFATAL, \"IdempotentRecord deserialize result failed, request {}, error {}\", req, desResult.error());\n co_return makeError(StatusCode::kDataCorruption, \"IdempotentRecord deserialize result failed\");\n }\n XLOGF(CRITICAL, \"Duplicated request {}, result {}, prev {}, now {}\", req, result, record.timestamp, UtcTime::now());\n co_return std::optional(result);\n }\n\n template \n static CoTryTask store(kv::IReadWriteTransaction &txn,\n const Uuid clientId,\n const Uuid requestId,\n const Result &result) {\n Record> record(result);\n record.clientId = clientId;\n record.requestId = requestId;\n record.timestamp = UtcClock::now();\n\n auto key = record.packKey();\n auto value = serde::serialize(record);\n co_return co_await txn.set(key, value);\n }\n\n static CoTryTask> clean(kv::IReadWriteTransaction &txn,\n std::optional prev,\n Duration expire,\n size_t limit,\n size_t &total,\n size_t &cleaned) {\n auto now = UtcClock::now();\n auto prefix = Serializer::serRawArgs(keyPrefix);\n auto begin = prev.value_or(prefix);\n XLOGF_IF(FATAL, begin < prefix, \"{} < {}\", begin, prefix);\n auto end = kv::TransactionHelper::prefixListEndKey(prefix);\n kv::IReadOnlyTransaction::KeySelector selBegin{begin, false};\n kv::IReadOnlyTransaction::KeySelector selEnd{end, false};\n auto res = co_await txn.getRange(selBegin, selEnd, limit);\n CO_RETURN_ON_ERROR(res);\n\n total = res->kvs.size();\n cleaned = 0;\n for (const auto &kv : res->kvs) {\n Record record;\n auto des = serde::deserialize(record, kv.value);\n if (!des) {\n XLOGF(CRITICAL, \"IdempotentRecord deserialize failed {}\", des.error());\n continue;\n }\n if (record.timestamp + expire < now) {\n cleaned++;\n CO_RETURN_ON_ERROR(co_await txn.clear(kv.key));\n }\n }\n\n auto nextPrev = res->kvs.empty() ? begin : res->kvs.back().key;\n co_return std::pair{nextPrev, res->hasMore};\n }\n};\n\n} // namespace hf3fs::meta::server"], ["/3FS/src/simple_example/service/Server.h", "#pragma once\n\n#include \n\n#include \"client/mgmtd/MgmtdClientForServer.h\"\n#include \"client/storage/StorageClient.h\"\n#include \"common/logging/LogConfig.h\"\n#include \"common/net/Client.h\"\n#include \"common/net/Server.h\"\n#include \"common/utils/BackgroundRunner.h\"\n#include \"common/utils/ConfigBase.h\"\n#include \"core/app/ServerAppConfig.h\"\n#include \"core/app/ServerLauncher.h\"\n#include \"core/app/ServerLauncherConfig.h\"\n#include \"core/app/ServerMgmtdClientFetcher.h\"\n\nnamespace hf3fs::simple_example::server {\n\nclass SimpleExampleServer : public net::Server {\n public:\n static constexpr auto kName = \"SimpleExample\";\n static constexpr auto kNodeType = flat::NodeType::CLIENT;\n\n struct CommonConfig : public ApplicationBase::Config {\n CommonConfig() {\n using logging::LogConfig;\n log().set_categories({LogConfig::makeRootCategoryConfig(), LogConfig::makeEventCategoryConfig()});\n log().set_handlers({LogConfig::makeNormalHandlerConfig(),\n LogConfig::makeErrHandlerConfig(),\n LogConfig::makeFatalHandlerConfig(),\n LogConfig::makeEventHandlerConfig()});\n }\n };\n\n using AppConfig = core::ServerAppConfig;\n struct LauncherConfig : public core::ServerLauncherConfig {\n LauncherConfig() { mgmtd_client() = hf3fs::client::MgmtdClientForServer::Config{}; }\n };\n using RemoteConfigFetcher = core::launcher::ServerMgmtdClientFetcher;\n using Launcher = core::ServerLauncher;\n\n struct Config : public ConfigBase {\n CONFIG_OBJ(base, net::Server::Config, [](net::Server::Config &c) {\n c.set_groups_length(2);\n c.groups(0).listener().set_listen_port(8000);\n c.groups(0).set_services({\"SimpleExampleSerde\"});\n\n c.groups(1).set_network_type(net::Address::TCP);\n c.groups(1).listener().set_listen_port(9000);\n c.groups(1).set_use_independent_thread_pool(true);\n c.groups(1).set_services({\"Core\"});\n });\n CONFIG_OBJ(background_client, net::Client::Config);\n CONFIG_OBJ(mgmtd_client, ::hf3fs::client::MgmtdClientForServer::Config);\n CONFIG_OBJ(storage_client, storage::client::StorageClient::Config);\n };\n\n SimpleExampleServer(const Config &config);\n ~SimpleExampleServer() override;\n\n Result beforeStart() final;\n\n Result beforeStop() final;\n\n private:\n const Config &config_;\n\n std::unique_ptr backgroundClient_;\n std::shared_ptr<::hf3fs::client::MgmtdClientForServer> mgmtdClient_;\n};\n\n} // namespace hf3fs::simple_example::server\n"], ["/3FS/src/storage/update/UpdateWorker.h", "#pragma once\n\n#include \n\n#include \"common/utils/BoundedQueue.h\"\n#include \"storage/store/StorageTargets.h\"\n#include \"storage/update/UpdateJob.h\"\n\nnamespace hf3fs::storage {\n\nclass UpdateWorker {\n public:\n class Config : public ConfigBase {\n CONFIG_ITEM(queue_size, 4096u);\n CONFIG_ITEM(num_threads, 32ul);\n CONFIG_ITEM(bg_num_threads, 8ul);\n };\n\n UpdateWorker(const Config &config)\n : config_(config),\n executors_(std::make_pair(config_.num_threads(), config_.num_threads()),\n std::make_shared(\"Update\")),\n bgExecutors_(std::make_pair(config_.bg_num_threads(), config_.bg_num_threads()),\n std::make_shared(\"Recycle\")) {}\n ~UpdateWorker() { stopAndJoin(); }\n\n Result start(uint32_t numberOfDisks);\n void stopAndJoin();\n\n CoTask enqueue(UpdateJob *job) {\n assert(job->target()->diskIndex() < queueVec_.size());\n co_await queueVec_[job->target()->diskIndex()]->co_enqueue(job);\n }\n\n protected:\n using Queue = BoundedQueue;\n void run(Queue &queue);\n\n private:\n ConstructLog<\"storage::UpdateWorker\"> constructLog_;\n const Config &config_;\n std::vector> queueVec_;\n folly::CPUThreadPoolExecutor executors_;\n folly::CPUThreadPoolExecutor bgExecutors_;\n std::atomic_flag stopped_;\n};\n\n} // namespace hf3fs::storage\n"], ["/3FS/src/common/net/Client.h", "#pragma once\n\n#include \n#include \n\n#include \"common/net/IOWorker.h\"\n#include \"common/net/Processor.h\"\n#include \"common/net/RDMAControl.h\"\n#include \"common/net/ThreadPoolGroup.h\"\n#include \"common/serde/ClientContext.h\"\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/Result.h\"\n\nnamespace hf3fs::net {\n\nclass Client {\n public:\n struct Config : public ConfigBase {\n CONFIG_OBJ(thread_pool, ThreadPoolGroup::Config);\n CONFIG_OBJ(processor, Processor::Config);\n CONFIG_OBJ(io_worker, IOWorker::Config);\n CONFIG_OBJ(rdma_control, RDMAControlImpl::Config);\n CONFIG_HOT_UPDATED_ITEM(default_timeout, kClientRequestDefaultTimeout);\n CONFIG_HOT_UPDATED_ITEM(default_log_long_running_threshold, kClientRequestLogLongRunningThreshold);\n CONFIG_HOT_UPDATED_ITEM(default_send_retry_times, kDefaultMaxRetryTimes, ConfigCheckers::checkPositive);\n CONFIG_HOT_UPDATED_ITEM(default_compression_level, 0u);\n CONFIG_HOT_UPDATED_ITEM(default_compression_threshold, 128_KB);\n CONFIG_HOT_UPDATED_ITEM(enable_rdma_control, false);\n CONFIG_HOT_UPDATED_ITEM(force_use_tcp, false);\n CONFIG_HOT_UPDATED_ITEM(default_report_metrics, false);\n };\n\n explicit Client(const Config &config, const std::string &name = \"Cli\")\n : config_(config),\n tpg_(name, config_.thread_pool()),\n processor_(serdeServices_, tpg_.procThreadPool(), config_.processor()),\n ioWorker_(processor_, tpg_.ioThreadPool(), tpg_.connThreadPool(), config_.io_worker()),\n clientConfigGuard_(config_.addCallbackGuard([&] { updateDefaultOptions(); })) {\n updateDefaultOptions();\n }\n ~Client() { stopAndJoin(); }\n\n Result start(const std::string &name = \"Cli\") {\n RETURN_AND_LOG_ON_ERROR(processor_.start(name));\n RETURN_AND_LOG_ON_ERROR(serdeServices_.addService(std::make_unique(config_.rdma_control()), true));\n return ioWorker_.start(name);\n }\n\n void stopAndJoin() {\n processor_.stopAndJoin();\n ioWorker_.stopAndJoin();\n tpg_.stopAndJoin();\n }\n\n serde::ClientContext serdeCtx(Address serverAddr) {\n return serde::ClientContext(ioWorker_, config_.force_use_tcp() ? serverAddr.tcp() : serverAddr, options_);\n }\n\n auto &tpg() { return tpg_; }\n\n auto options() const { return options_.load(); }\n\n void dropConnections(Address addr) { ioWorker_.dropConnections(addr); }\n\n void checkConnections(Address addr, Duration expiredTime) { ioWorker_.checkConnections(addr, expiredTime); }\n\n protected:\n void updateDefaultOptions() {\n auto options = std::make_shared();\n options->timeout = config_.default_timeout();\n options->logLongRunningThreshold = config_.default_log_long_running_threshold();\n options->sendRetryTimes = config_.default_send_retry_times();\n options->compression = {config_.default_compression_level(), config_.default_compression_threshold()};\n options->enableRDMAControl = config_.enable_rdma_control();\n options->reportMetrics = config_.default_report_metrics();\n options_ = std::move(options);\n }\n\n private:\n serde::Services serdeServices_;\n const Config &config_;\n\n ThreadPoolGroup tpg_;\n Processor processor_;\n IOWorker ioWorker_;\n std::unique_ptr clientConfigGuard_;\n folly::atomic_shared_ptr options_{std::make_shared()};\n};\n\n} // namespace hf3fs::net\n"], ["/3FS/src/kv/KVStore.h", "#pragma once\n\n#include \n#include \n#include \n#include \n\n#include \"common/serde/Serde.h\"\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/Duration.h\"\n#include \"common/utils/Path.h\"\n#include \"common/utils/Result.h\"\n#include \"common/utils/Size.h\"\n\nnamespace hf3fs::kv {\n\nclass KVStore {\n public:\n enum class Type { LevelDB, RocksDB, MemDB };\n class Config : public ConfigBase {\n CONFIG_ITEM(type, Type::LevelDB);\n CONFIG_ITEM(create_if_missing, false);\n CONFIG_HOT_UPDATED_ITEM(sync_when_write, true);\n\n // for leveldb.\n CONFIG_ITEM(leveldb_sst_file_size, 16_MB, ConfigCheckers::checkGE);\n CONFIG_ITEM(leveldb_write_buffer_size, 16_MB, ConfigCheckers::checkGE);\n CONFIG_ITEM(leveldb_block_cache_size, 8_GB, ConfigCheckers::checkGE);\n CONFIG_ITEM(leveldb_shared_block_cache, true);\n CONFIG_HOT_UPDATED_ITEM(leveldb_iterator_fill_cache, true);\n CONFIG_ITEM(integrate_leveldb_log, false);\n\n // for rocksdb\n CONFIG_ITEM(rocksdb_max_manifest_file_size, 64_MB, ConfigCheckers::checkGE);\n CONFIG_ITEM(rocksdb_stats_dump_period, 2_min);\n CONFIG_ITEM(rocksdb_enable_pipelined_write, false);\n CONFIG_ITEM(rocksdb_unordered_write, false);\n CONFIG_ITEM(rocksdb_avoid_flush_during_recovery, false);\n CONFIG_ITEM(rocksdb_avoid_flush_during_shutdown, false);\n CONFIG_ITEM(rocksdb_avoid_unnecessary_blocking_io, false);\n CONFIG_ITEM(rocksdb_lowest_used_cache_tier, rocksdb_internal::CacheTier::kNonVolatileBlockTier);\n CONFIG_ITEM(rocksdb_write_buffer_size, 16_MB, ConfigCheckers::checkGE);\n CONFIG_ITEM(rocksdb_compression, rocksdb_internal::CompressionType::kNoCompression);\n CONFIG_ITEM(rocksdb_level0_file_num_compaction_trigger, 4, ConfigCheckers::checkGE);\n CONFIG_ITEM(rocksdb_enable_prefix_transform, true);\n CONFIG_ITEM(rocksdb_enable_bloom_filter, true);\n CONFIG_ITEM(rocksdb_bloom_filter_bits_per_key, 10);\n CONFIG_ITEM(rocksdb_num_levels, 7, ConfigCheckers::checkGE);\n CONFIG_ITEM(rocksdb_target_file_size_base, 64_MB, ConfigCheckers::checkGE);\n CONFIG_ITEM(rocksdb_target_file_size_multiplier, 1, ConfigCheckers::checkPositive);\n CONFIG_ITEM(rocksdb_block_cache_size, 8_GB, ConfigCheckers::checkGE);\n CONFIG_ITEM(rocksdb_shared_block_cache, true);\n CONFIG_ITEM(rocksdb_block_size, 4_KB, ConfigCheckers::checkGE);\n CONFIG_ITEM(rocksdb_prepopulate_block_cache,\n rocksdb_internal::BlockBasedTableOptions::PrepopulateBlockCache::kDisable);\n CONFIG_ITEM(rocksdb_threads_num, 8u, ConfigCheckers::checkPositive);\n CONFIG_ITEM(rocksdb_wal_recovery_mode, rocksdb_internal::WALRecoveryMode::kTolerateCorruptedTailRecords);\n CONFIG_ITEM(rocksdb_keep_log_file_num, 10u);\n CONFIG_HOT_UPDATED_ITEM(rocksdb_readahead_size, 2_MB);\n };\n\n struct Options {\n SERDE_STRUCT_FIELD(type, Type::RocksDB);\n SERDE_STRUCT_FIELD(path, Path{});\n SERDE_STRUCT_FIELD(createIfMissing, false);\n };\n\n virtual ~KVStore() = default;\n\n // get value corresponding to key.\n virtual Result get(std::string_view key) = 0;\n\n // get the first key which is greater than input key.\n using IterateFunc = std::function(std::string_view, std::string_view)>;\n virtual Result iterateKeysWithPrefix(std::string_view prefix,\n uint32_t limit,\n IterateFunc func,\n std::optional *nextValidKey = nullptr) = 0;\n\n // put a key-value pair.\n virtual Result put(std::string_view key, std::string_view value, bool sync = false) = 0;\n\n // remove a key-value pair.\n virtual Result remove(std::string_view key) = 0;\n\n // batch operations.\n class BatchOperations {\n public:\n virtual ~BatchOperations() = default;\n // put a key-value pair.\n virtual void put(std::string_view key, std::string_view value) = 0;\n // remove a key.\n virtual void remove(std::string_view key) = 0;\n // clear a batch operations.\n virtual void clear() = 0;\n // commit a batch of operations.\n virtual Result commit() = 0;\n // destroy self.\n virtual void destroy() = 0;\n // deleter for std::unique_ptr.\n struct Deleter {\n void operator()(BatchOperations *b) { b->destroy(); }\n };\n };\n using BatchOptionsPtr = std::unique_ptr;\n virtual BatchOptionsPtr createBatchOps() = 0;\n\n // iterator.\n class Iterator {\n public:\n virtual ~Iterator() = default;\n virtual void seek(std::string_view key) = 0;\n virtual void seekToFirst() = 0;\n virtual void seekToLast() = 0;\n virtual void next() = 0;\n virtual Result status() const = 0;\n virtual bool valid() const = 0;\n virtual std::string_view key() const = 0;\n virtual std::string_view value() const = 0;\n virtual void destroy() = 0;\n struct Deleter {\n void operator()(Iterator *it) { it->destroy(); }\n };\n };\n using IteratorPtr = std::unique_ptr;\n virtual IteratorPtr createIterator() = 0;\n\n // create a KVStore instance.\n static std::unique_ptr create(const Config &config, const Options &options);\n};\n\n} // namespace hf3fs::kv\n"], ["/3FS/src/fuse/FuseConfig.h", "#pragma once\n\n#include \"client/meta/MetaClient.h\"\n#include \"client/mgmtd/MgmtdClientForClient.h\"\n#include \"client/storage/StorageClient.h\"\n#include \"common/app/ApplicationBase.h\"\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/CoroutinesPool.h\"\n\nnamespace hf3fs::fuse {\nstruct FuseConfig : public ConfigBase {\n#ifdef ENABLE_FUSE_APPLICATION\n CONFIG_OBJ(common, ApplicationBase::Config);\n#else\n CONFIG_ITEM(cluster_id, \"\");\n CONFIG_ITEM(token_file, \"\");\n CONFIG_ITEM(mountpoint, \"\");\n CONFIG_ITEM(allow_other, true);\n CONFIG_OBJ(ib_devices, net::IBDevice::Config);\n CONFIG_OBJ(log, logging::LogConfig);\n CONFIG_OBJ(monitor, monitor::Monitor::Config);\n#endif\n CONFIG_HOT_UPDATED_ITEM(enable_priority, false);\n CONFIG_HOT_UPDATED_ITEM(enable_interrupt, false);\n CONFIG_HOT_UPDATED_ITEM(attr_timeout, (double)30);\n CONFIG_HOT_UPDATED_ITEM(entry_timeout, (double)30);\n CONFIG_HOT_UPDATED_ITEM(negative_timeout, (double)5);\n CONFIG_HOT_UPDATED_ITEM(symlink_timeout, (double)5);\n CONFIG_HOT_UPDATED_ITEM(readonly, false);\n CONFIG_HOT_UPDATED_ITEM(memset_before_read, false);\n CONFIG_HOT_UPDATED_ITEM(enable_read_cache, true);\n CONFIG_HOT_UPDATED_ITEM(fsync_length_hint, false); // for test\n CONFIG_HOT_UPDATED_ITEM(fdatasync_update_length, false);\n CONFIG_ITEM(max_idle_threads, 10);\n CONFIG_ITEM(max_threads, 256);\n CONFIG_ITEM(max_readahead, 16_MB);\n CONFIG_ITEM(max_background, 32);\n CONFIG_ITEM(enable_writeback_cache, false);\n CONFIG_OBJ(client, net::Client::Config);\n CONFIG_OBJ(mgmtd, client::MgmtdClientForClient::Config);\n CONFIG_OBJ(storage, storage::client::StorageClient::Config);\n CONFIG_OBJ(meta, meta::client::MetaClient::Config, [&](auto &cfg) { cfg.set_dynamic_stripe(true); });\n CONFIG_ITEM(remount_prefix, (std::optional)std::nullopt);\n CONFIG_ITEM(iov_limit, 1_MB);\n CONFIG_ITEM(io_jobq_size, 1024);\n CONFIG_ITEM(batch_io_coros, 128);\n CONFIG_ITEM(rdma_buf_pool_size, 1024);\n CONFIG_ITEM(time_granularity, 1_s);\n CONFIG_HOT_UPDATED_ITEM(check_rmrf, true);\n CONFIG_ITEM(notify_inval_threads, 32);\n\n CONFIG_ITEM(max_uid, 1_M);\n\n CONFIG_HOT_UPDATED_ITEM(chunk_size_limit, 0_KB);\n\n CONFIG_SECT(io_jobq_sizes, {\n CONFIG_ITEM(hi, 32);\n CONFIG_ITEM(lo, 4096);\n });\n\n CONFIG_SECT(io_worker_coros, {\n CONFIG_HOT_UPDATED_ITEM(hi, 8);\n CONFIG_HOT_UPDATED_ITEM(lo, 8);\n });\n\n CONFIG_HOT_UPDATED_ITEM(io_job_deq_timeout, 1_ms);\n\n CONFIG_OBJ(storage_io, storage::client::IoOptions);\n\n CONFIG_HOT_UPDATED_ITEM(submit_wait_jitter, 1_ms);\n CONFIG_HOT_UPDATED_ITEM(max_jobs_per_ioring, 32);\n\n CONFIG_SECT(io_bufs, {\n CONFIG_ITEM(max_buf_size, 1_MB);\n CONFIG_ITEM(max_readahead, 256_KB);\n CONFIG_ITEM(write_buf_size, 1_MB);\n });\n\n CONFIG_HOT_UPDATED_ITEM(flush_on_stat, true);\n CONFIG_HOT_UPDATED_ITEM(sync_on_stat, true);\n CONFIG_HOT_UPDATED_ITEM(dryrun_bench_mode, false);\n\n struct PeriodSync : public ConfigBase {\n CONFIG_HOT_UPDATED_ITEM(enable, true);\n CONFIG_HOT_UPDATED_ITEM(interval, 30_s);\n CONFIG_HOT_UPDATED_ITEM(limit, 1000u);\n CONFIG_HOT_UPDATED_ITEM(flush_write_buf, true);\n CONFIG_OBJ(worker, CoroutinesPoolBase::Config, [](auto &cfg) { cfg.set_coroutines_num(4); });\n };\n CONFIG_OBJ(periodic_sync, PeriodSync);\n};\n} // namespace hf3fs::fuse\n"], ["/3FS/src/client/storage/StorageClientInMem.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"StorageClient.h\"\n#include \"StorageMessenger.h\"\n#include \"common/net/Client.h\"\n#include \"common/utils/Address.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/Result.h\"\n#include \"fbs/storage/Common.h\"\n\nnamespace hf3fs::storage::client {\n\nclass StorageClientInMem : public StorageClient {\n public:\n StorageClientInMem(ClientId clientId, const Config &config, hf3fs::client::ICommonMgmtdClient &mgmtdClient);\n\n ~StorageClientInMem() override = default;\n\n hf3fs::client::ICommonMgmtdClient &getMgmtdClient() override { return mgmtdClient_; }\n\n CoTryTask batchRead(std::span readIOs,\n const flat::UserInfo &userInfo,\n const ReadOptions &options = ReadOptions(),\n std::vector *failedIOs = nullptr) override;\n\n CoTryTask batchWrite(std::span writeIOs,\n const flat::UserInfo &userInfo,\n const WriteOptions &options = WriteOptions(),\n std::vector *failedIOs = nullptr) override;\n\n CoTryTask read(ReadIO &readIO,\n const flat::UserInfo &userInfo,\n const ReadOptions &options = ReadOptions()) override;\n\n CoTryTask write(WriteIO &writeIO,\n const flat::UserInfo &userInfo,\n const WriteOptions &options = WriteOptions()) override;\n\n CoTryTask queryLastChunk(std::span ops,\n const flat::UserInfo &userInfo,\n const ReadOptions &options = ReadOptions(),\n std::vector *failedOps = nullptr) override;\n\n CoTryTask removeChunks(std::span ops,\n const flat::UserInfo &userInfo,\n const WriteOptions &options = WriteOptions(),\n std::vector *failedOps = nullptr) override;\n\n CoTryTask truncateChunks(std::span ops,\n const flat::UserInfo &userInfo,\n const WriteOptions &options = WriteOptions(),\n std::vector *failedOps = nullptr) override;\n\n CoTryTask querySpaceInfo(NodeId) override;\n\n CoTryTask createTarget(NodeId nodeId, const CreateTargetReq &req) override;\n\n CoTryTask offlineTarget(NodeId nodeId, const OfflineTargetReq &req) override;\n\n CoTryTask removeTarget(NodeId nodeId, const RemoveTargetReq &req) override;\n\n CoTryTask>> queryChunk(const QueryChunkReq &req) override;\n\n CoTryTask getAllChunkMetadata(const ChainId &chainId, const TargetId &targetId) override;\n\n // for meta test\n CoTask injectErrorOnChain(ChainId chainId, Result error);\n\n private:\n struct ChunkData {\n std::vector content;\n uint32_t capacity;\n uint32_t version;\n };\n\n struct Chain {\n folly::coro::Mutex mutex;\n std::map chunks;\n Result error = Void{};\n };\n\n CoTask>> getChain(ChainId chainId) {\n auto &chain = (*chains_.lock())[chainId];\n auto guard = co_await chain.mutex.co_scoped_lock();\n co_return std::make_pair(&chain, std::move(guard));\n }\n\n using ChunkDataProcessor = std::function(const ChunkId &, const ChunkData &)>;\n\n CoTryTask>> doQuery(const ChainId &chainId, const ChunkIdRange &range);\n\n CoTryTask processQueryResults(const ChainId chainId,\n const ChunkIdRange &range,\n ChunkDataProcessor processor,\n bool &moreChunksInRange);\n\n hf3fs::client::ICommonMgmtdClient &mgmtdClient_;\n folly::Synchronized, std::mutex> chains_;\n};\n\n} // namespace hf3fs::storage::client\n"], ["/3FS/src/fbs/meta/FileOperation.h", "#pragma once\n\n#include \n#include \n#include \n\n#include \"client/storage/StorageClient.h\"\n#include \"client/storage/TargetSelection.h\"\n#include \"common/monitor/Recorder.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"fbs/meta/Schema.h\"\n#include \"fbs/mgmtd/MgmtdTypes.h\"\n\nnamespace hf3fs::meta {\n\nclass FileOperation {\n public:\n struct Recorder {\n Recorder(std::string_view prefix)\n : removeChunksCount(fmt::format(\"{}.remove_chunks\", prefix)),\n removeChunksSize(fmt::format(\"{}.remove_chunks_size\", prefix)),\n queryChunksFailed(fmt::format(\"{}.query_chunks_failed\", prefix)),\n removeChunksFailed(fmt::format(\"{}.remove_chunks_failed\", prefix)),\n truncateChunkFailed(fmt::format(\"{}.truncate_chunk_failed\", prefix)),\n queryLastChunkLatency(fmt::format(\"{}.query_last_chunk\", prefix)),\n queryTotalChunkLatency(fmt::format(\"{}.query_total_chunks\", prefix)),\n removeChunksLatency(fmt::format(\"{}.remove_chunks_latency\", prefix)),\n truncateChunkLatency(fmt::format(\"{}.truncate_latency\", prefix)) {}\n\n monitor::CountRecorder removeChunksCount;\n monitor::CountRecorder removeChunksSize;\n monitor::CountRecorder queryChunksFailed;\n monitor::CountRecorder removeChunksFailed;\n monitor::CountRecorder truncateChunkFailed;\n monitor::LatencyRecorder queryLastChunkLatency;\n monitor::LatencyRecorder queryTotalChunkLatency;\n monitor::LatencyRecorder removeChunksLatency;\n monitor::LatencyRecorder truncateChunkLatency;\n };\n\n FileOperation(storage::client::StorageClient &storage,\n const flat::RoutingInfo &routing,\n const flat::UserInfo &userInfo,\n const meta::Inode &inode,\n std::optional> recorder = {})\n : storage_(storage),\n routing_(routing),\n userInfo_(userInfo),\n inode_(inode),\n recorder_(recorder) {}\n\n struct QueryResult {\n uint64_t length = 0;\n uint64_t lastChunk = 0;\n uint64_t lastChunkLen = 0;\n uint64_t totalChunkLen = 0;\n uint64_t totalNumChunks = 0;\n };\n\n CoTryTask queryChunks(bool queryTotalChunk, bool dynStripe);\n\n CoTryTask> queryChunksByChain(bool queryTotalChunk, bool dynStripe);\n\n CoTryTask> removeChunks(size_t targetLength,\n size_t removeChunksBatchSize,\n bool dynStripe,\n storage::client::RetryOptions retry);\n\n CoTryTask truncateChunk(size_t targetLength);\n\n CoTryTask> queryAllChunks(uint64_t begin, uint64_t end);\n\n private:\n storage::client::StorageClient &storage_;\n const flat::RoutingInfo &routing_;\n const flat::UserInfo &userInfo_;\n const meta::Inode &inode_;\n std::optional> recorder_;\n};\n\n} // namespace hf3fs::meta"], ["/3FS/src/lib/common/Shm.h", "#pragma once\n\n#include \n#include \n\n#include \"PerProcTable.h\"\n#include \"client/storage/StorageClient.h\"\n#include \"common/utils/Path.h\"\n#include \"fbs/meta/Schema.h\"\n\nnamespace hf3fs::lib {\n\nstruct IorAttrs {\n int priority = 1;\n Duration timeout{Duration::zero()};\n uint64_t flags = 0;\n};\n\nstruct ShmBuf {\n ShmBuf(const Path &p, size_t sz, size_t bsz, int numa, meta::Uid u, int pid, int ppid);\n ShmBuf(const Path &p, off_t o, size_t sz, size_t bsz, Uuid u);\n ~ShmBuf();\n\n CoTask registerForIO(folly::Executor::KeepAlive<> exec,\n storage::client::StorageClient &sc,\n std::function &&recordMetrics);\n CoTask> memh(size_t off);\n\n bool checkId(const Uuid &uid) const { return id == uid; }\n\n CoTask deregisterForIO();\n void unmapBuf();\n bool maybeUnlinkShm() {\n if (owner_) {\n shm_unlink(path.c_str());\n }\n\n return owner_;\n }\n\n Path path;\n uint8_t *bufStart{nullptr};\n size_t size{0};\n size_t blockSize{0};\n\n // for client lib\n off_t off;\n\n // for global shm to do acl\n meta::Uid user{0};\n // for global shm to be freed after owning process is gone\n int pid{0};\n int ppid{0};\n Uuid id;\n\n // for fuse\n std::string key;\n int iorIndex = -1;\n bool isIoRing = false;\n bool forRead = true;\n int ioDepth = 0;\n std::optional iora;\n\n private:\n void mapBuf();\n\n private:\n bool owner_;\n int numaNode_;\n // int fd_;\n\n // for client agent\n std::vector> memhs_;\n folly::coro::Baton memhBaton_;\n std::atomic regging_;\n};\n\nclass ShmBufForIO {\n public:\n ShmBufForIO(std::shared_ptr buf, off_t off)\n : buf_(std::move(buf)),\n off_(off) {}\n uint8_t *ptr() const {\n XLOGF(DBG, \"buf start {} off {} ptr {}\", (void *)buf_->bufStart, off_, (void *)(buf_->bufStart + off_));\n return buf_->bufStart + off_;\n }\n CoTryTask memh(size_t len) const {\n XLOGF(DBG, \"shm buf for io off {} buf ptr {}\", off_, (void *)buf_.get());\n XLOGF(DBG, \"shm block size {}\", buf_->blockSize);\n if (len && off_ / buf_->blockSize != (off_ + len - 1) / buf_->blockSize) {\n co_return makeError(StatusCode::kInvalidArg);\n }\n co_return (co_await buf_->memh(off_)).get();\n }\n\n private:\n std::shared_ptr buf_;\n off_t off_;\n};\n\nusing ProcShmBuf = AllProcMap;\n} // namespace hf3fs::lib\n"], ["/3FS/src/meta/store/Utils.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"client/mgmtd/ICommonMgmtdClient.h\"\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/Result.h\"\n#include \"common/utils/StatusCode.h\"\n#include \"fbs/meta/Common.h\"\n#include \"fbs/meta/Schema.h\"\n#include \"meta/store/DirEntry.h\"\n#include \"meta/store/Inode.h\"\n\nnamespace hf3fs::meta::server {\n\ntemplate \ninline InodeId getInodeId(T &&val) {\n return folly::variant_match(\n std::forward(val),\n [](const Inode &inode) { return inode.id; },\n [](const DirEntry &entry) { return entry.id; },\n [](const InodeId &id) { return id; },\n [](const std::pair &cachedAcl) { return cachedAcl.first; });\n}\n\ntemplate \ninline Acl getDirectoryAcl(T &&val) {\n return folly::variant_match(\n std::forward(val),\n [](const Inode &inode) {\n assert(inode.isDirectory());\n return inode.acl;\n },\n [](const DirEntry &entry) {\n assert(entry.isDirectory() && entry.dirAcl.has_value());\n return *entry.dirAcl;\n },\n [](const std::pair &cachedAcl) { return cachedAcl.second; });\n}\n\ntemplate \ninline InodeType getInodeType(T &&val) {\n return folly::variant_match(\n std::forward(val),\n [](const Inode &inode) { return inode.getType(); },\n [](const DirEntry &entry) { return entry.type; },\n [](const std::pair &) { return InodeType::Directory; });\n}\n\ntemplate \ninline Result checkMetaFound(std::optional val) {\n if (!val.has_value()) {\n return makeError(MetaCode::kNotFound);\n }\n return std::move(val.value());\n}\n\ninline bool isFirstMeta(client::ICommonMgmtdClient &mgmtd, flat::NodeId nodeId) {\n auto routing = mgmtd.getRoutingInfo();\n if (!routing) {\n return false;\n }\n auto nodes = routing->getNodeBy(flat::selectNodeByType(flat::NodeType::META) && flat::selectActiveNode());\n auto first =\n std::min_element(nodes.begin(), nodes.end(), [](auto &a, auto &b) { return a.app.nodeId < b.app.nodeId; });\n return first != nodes.end() && first->app.nodeId == nodeId;\n}\n\n} // namespace hf3fs::meta::server\n"], ["/3FS/src/common/utils/ConfigBase.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/utils/AtomicValue.h\"\n#include \"common/utils/MagicEnum.hpp\"\n#include \"common/utils/Path.h\"\n#include \"common/utils/Result.h\"\n#include \"common/utils/RobinHood.h\"\n#include \"common/utils/Toml.hpp\"\n#include \"common/utils/TypeTraits.h\"\n\nDECLARE_string(cfg);\n\nnamespace hf3fs {\n\n/*\n * ConfigBase class with macro.\n * The supported value types:\n * - std::string\n * - int64_t\n * - double\n * - bool\n * - enum\n * - std::vector of above types\n */\n\n#define CONFIG_OBJ(name, cls, ...) /* optional parameter: initializer */ \\\n public: \\\n cls &name() { return name##_; } \\\n const cls &name() const { return name##_; } \\\n \\\n private: \\\n cls name##_; \\\n [[maybe_unused]] bool name##Insert_ = [this]() { \\\n using Self = std::decay_t; \\\n ConfigBase::sections_[#name] = reinterpret_cast<::hf3fs::config::IConfig Self::*>(&Self::name##_); \\\n __VA_OPT__(__VA_ARGS__(name##_);) \\\n return true; \\\n }()\n\n#define CONFIG_OBJ_ARRAY(name, cls, cap, ...) /* optional parameter: initializer */ \\\n public: \\\n cls &name(size_t idx) { return name##_[idx]; } \\\n const cls &name(size_t idx) const { return name##_[idx]; } \\\n size_t name##_length() const { \\\n auto lock = std::unique_lock(mutex_); \\\n return name##Length_; \\\n } \\\n void set_##name##_length(size_t len) { \\\n auto lock = std::unique_lock(mutex_); \\\n if (len < k_capacity_##name) { \\\n name##Length_ = len; \\\n } \\\n } \\\n \\\n private: \\\n static constexpr size_t k_capacity_##name{cap}; \\\n static_assert(k_capacity_##name <= 4096u, \"array cap should less than 4096\"); \\\n std::array name##_; \\\n size_t name##Length_ = [this]() { \\\n using Self = std::decay_t; \\\n ConfigBase::lengths_[#name] = reinterpret_cast(&Self::name##Length_); \\\n auto base = reinterpret_cast<::hf3fs::config::IConfig Self::*>(&Self::name##_); \\\n static_assert(sizeof(base) == sizeof(uintptr_t), \"sizeof(base) != sizeof(uintptr_t)\"); \\\n for (auto i = 0ul; i < k_capacity_##name; ++i) { \\\n ConfigBase::sections_[fmt::format(#name \"#{}\", i)] = base; \\\n *reinterpret_cast(&base) += sizeof(cls); \\\n } \\\n auto length = 1ul; \\\n __VA_OPT__(length = __VA_ARGS__(name##_);) \\\n return length; \\\n }()\n\n#define CONFIG_SECT(name, section) \\\n protected: \\\n struct T##name : public ConfigBase section; \\\n CONFIG_OBJ(name, T##name)\n\n#define CONFIG_ADD_ITEM(name, defaultValue, supportHotUpdated, ...) /* optional parameter: checker */ \\\n private: \\\n using T##name = ::hf3fs::config::ValueType>; \\\n using R##name = ::hf3fs::config::ReturnType; \\\n \\\n public: \\\n auto name##_getter() const { \\\n return [this] { return name(); }; \\\n } \\\n R##name name() const { return name##_.value(); } \\\n bool set_##name(R##name value) { return name##_.checkAndSet(value); } \\\n \\\n private: \\\n ::hf3fs::config::Item name##_ = ::hf3fs::config::Item(#name, defaultValue, [this] { \\\n using Self = std::decay_t; \\\n ConfigBase::items_[#name] = reinterpret_cast<::hf3fs::config::IItem Self::*>(&Self::name##_); \\\n return supportHotUpdated; \\\n }() __VA_OPT__(, ) __VA_ARGS__)\n\n#define CONFIG_ITEM(name, defaultValue, ...) CONFIG_ADD_ITEM(name, defaultValue, false, __VA_ARGS__)\n#define CONFIG_HOT_UPDATED_ITEM(name, defaultValue, ...) CONFIG_ADD_ITEM(name, defaultValue, true, __VA_ARGS__)\n\n#define CONFIG_VARIANT_TYPE(defaultType) \\\n CONFIG_ITEM(type, std::string{defaultType}, [this](const std::string &name) { \\\n using Self = std::decay_t; \\\n return ConfigBase::sections_.count(name); \\\n }); \\\n \\\n public: \\\n constexpr static inline bool is_variant_type() { return true; }\n\nnamespace config {\n\nstruct IItem {\n virtual ~IItem() = default;\n virtual Result validate(const std::string &path) const = 0;\n virtual Result update(const toml::node &node, bool isHotUpdate, const std::string &path) = 0;\n virtual void toToml(toml::table &table) const = 0;\n virtual bool isParsedFromString() const = 0;\n virtual bool operator==(const IItem &other) const = 0;\n virtual String toString() const = 0;\n};\n\nclass ConfigCallbackGuard;\n\nusing KeyValue = std::pair;\n\ninline std::string tomlToString(const toml::node &node) {\n std::stringstream ss;\n ss << toml::toml_formatter(node, toml::toml_formatter::default_flags & ~toml::format_flags::indentation);\n return ss.str();\n}\n\nstruct IConfig {\n virtual ~IConfig() = default;\n\n virtual std::unique_ptr clonePtr() const = 0;\n\n // return a default constructed object\n virtual std::unique_ptr defaultPtr() const = 0;\n\n // validate configuration items one by one.\n virtual Result validate(const std::string &path = {}) const = 0;\n\n // validate configuration items as a whole.\n virtual Result overallValidate() const { return Void{}; }\n\n // update configuration. [thread safe]\n virtual Result update(const toml::table &table, bool isHotUpdate = true, const std::string &path = {}) = 0;\n\n // update configuration from a string. [thread safe]\n Result update(std::string_view str, bool isHotUpdate);\n\n // update configuration from a file. [thread safe]\n Result update(const Path &path, bool isHotUpdate);\n\n // update configuration from a series of key-values. [thread safe]\n Result update(const std::vector &updates, bool isHotUpdate);\n\n // remove callback guard.\n virtual void removeCallbackGuard(ConfigCallbackGuard *guard) const = 0;\n\n // convert configuration to TOML. [thread safe]\n virtual toml::table toToml() const = 0;\n\n // convert configuration of specific section/item to TOML. [thread safe]\n virtual Result toToml(std::string_view key) const = 0;\n\n // find item by a key.\n virtual Result find(std::string_view key) = 0;\n\n virtual bool operator==(const IConfig &other) const = 0;\n\n struct ItemDiff {\n String key;\n String left;\n String right;\n };\n\n size_t diffWith(const IConfig &other, std::span diffs, size_t pos = 0) const {\n return diffWith(other, {}, diffs, pos);\n }\n\n virtual size_t diffWith(const IConfig &other, String path, std::span diffs, size_t pos) const = 0;\n\n virtual Result atomicallyUpdate(std::string_view str, bool isHotUpdate) = 0;\n Result atomicallyUpdate(std::string_view str) { return atomicallyUpdate(str, /*isHotUpdate=*/true); }\n\n virtual Result atomicallyUpdate(const Path &path, bool isHotUpdate) = 0;\n Result atomicallyUpdate(const Path &path) { return atomicallyUpdate(path, /*isHotUpdate=*/true); }\n\n virtual Result atomicallyUpdate(const std::vector &updates, bool isHotUpdate) = 0;\n Result atomicallyUpdate(const std::vector &updates) {\n return atomicallyUpdate(updates, /*isHotUpdate=*/true);\n }\n\n virtual Result validateUpdate(std::string_view str, bool isHotUpdate) = 0;\n Result validateUpdate(std::string_view str) { return validateUpdate(str, /*isHotUpdate=*/true); }\n\n // convert configuration to string. [thread safe]\n std::string toString() const { return tomlToString(toToml()); }\n\n // initialize config from command line and config files.\n Result init(int *argc, char ***argv, bool follyInit = true);\n};\n\ntemplate \nstruct ConfigValueToTomlNode {\n template \n auto operator()(V &&v) {\n if constexpr (std::is_enum_v) {\n return magic_enum::enum_name(std::forward(v));\n } else if constexpr (std::is_same_v) {\n return static_cast(v);\n } else if constexpr (std::is_same_v) {\n return v.string();\n } else if constexpr (std::derived_from) {\n return v.toToml();\n } else if constexpr (requires { std::string(v.toString()); }) {\n return v.toString();\n } else {\n return std::forward(v);\n }\n }\n};\n\nResult> parseFlags(std::string_view prefix, int &argc, char *argv[]);\n\nclass ConfigCallbackGuard {\n public:\n explicit ConfigCallbackGuard(const config::IConfig *cfg, auto &&...f)\n : cfg_(cfg),\n func_(std::forward(f)...) {}\n ~ConfigCallbackGuard() { dismiss(); }\n\n void setCallback(auto &&f) { func_ = std::forward(f); }\n void callCallback() { func_ ? func_() : void(); }\n void dismiss() { cfg_ ? std::exchange(cfg_, nullptr)->removeCallbackGuard(this) : void(); }\n\n private:\n const config::IConfig *cfg_;\n std::function func_;\n};\n\ntemplate \nclass TLSStore {\n public:\n TLSStore(T &&value)\n : ptr_(std::make_shared(std::move(value))) {}\n TLSStore(const TLSStore &o)\n : ptr_(o.ptr_.load(std::memory_order_acquire)) {}\n\n const T &value() const {\n auto &cache = *tlsCache_;\n size_t latest = version_.load(std::memory_order_acquire);\n if (UNLIKELY(cache.version != latest)) {\n cache.ptr = ptr_.load(std::memory_order_acquire);\n cache.version = latest;\n }\n return *cache.ptr;\n }\n\n template \n void setValue(V &&value) {\n ptr_.store(std::make_shared(std::forward(value)));\n ++version_;\n }\n\n TLSStore &operator=(const TLSStore &o) {\n ptr_.store(o.ptr_.load(std::memory_order_acquire));\n ++version_;\n return *this;\n }\n\n private:\n std::atomic version_ = 1;\n folly::atomic_shared_ptr ptr_{std::make_shared()};\n struct Cache {\n std::shared_ptr ptr;\n uint64_t version = 0;\n };\n folly::ThreadLocal tlsCache_;\n};\n\ntemplate \nusing RemoveOptional = typename std::conditional_t, T, std::optional>::value_type;\ntemplate \ninline constexpr bool IsPrimitive = std::is_trivially_copyable_v && sizeof(T) <= 8;\ntemplate \nusing ReturnType = std::conditional_t, T, const T &>;\ntemplate \nusing StoreType = std::conditional_t, AtomicValue, TLSStore>;\ntemplate \nusing ValueType = std::conditional_t, std::string, T>;\n\ntemplate \ninline Result tomlNodeToValue(const toml::node &node) {\n return node.visit([&](auto &&el) -> Result {\n using TE = std::decay_t;\n if constexpr (!toml::is_value) {\n return makeError(StatusCode::kConfigInvalidType, fmt::format(\"{} isn't value\", typeid(TE).name()));\n } else {\n using E = typename TE::value_type;\n\n if constexpr (std::is_same_v) {\n return *el;\n } else if constexpr (std::is_same_v) {\n // do not allow any implicit conversion to bool\n return makeError(StatusCode::kConfigInvalidType,\n fmt::format(\"implicit conversion from {} to bool is not allowed\", typeid(E).name()));\n } else if constexpr (std::is_floating_point_v) {\n if constexpr (std::is_same_v || std::is_floating_point_v) {\n return *el;\n } else {\n return makeError(StatusCode::kConfigInvalidType,\n fmt::format(\"{} is not int64_t or floating types\", typeid(E).name()));\n }\n } else if constexpr (std::is_enum_v) {\n if constexpr (std::is_same_v) {\n auto opt = magic_enum::enum_cast(*el);\n if (opt) {\n return opt.value();\n } else {\n return makeError(StatusCode::kConfigInvalidValue, fmt::format(\"Value {}\", *el));\n }\n } else {\n return makeError(StatusCode::kConfigInvalidType,\n fmt::format(\"{} is enum but {} is not string\", typeid(T).name(), typeid(E).name()));\n }\n } else if constexpr (requires { Result{T::from(*el)}; }) {\n return T::from(*el);\n } else if constexpr (std::is_constructible_v) {\n try {\n return T(*el);\n } catch (const std::exception &e) {\n return makeError(\n StatusCode::kConfigInvalidType,\n fmt::format(\"Throws when constructing T ({}), E is {}: \", typeid(T).name(), typeid(E).name(), e.what()));\n }\n } else {\n return makeError(StatusCode::kConfigInvalidType,\n fmt::format(\"T is {}, E is {}\", typeid(T).name(), typeid(E).name()));\n }\n }\n });\n}\n\ntemplate \nclass Item : public IItem {\n public:\n Item(std::string name, T defaultValue, bool supportHotUpdate, std::function)> checker = nullptr)\n : value_(std::move(defaultValue)),\n name_(std::move(name)),\n supportHotUpdate_(supportHotUpdate),\n checker_(checker ? std::move(checker) : [](ReturnType) { return true; }) {}\n\n ReturnType value() const { return value_.value(); }\n\n template \n void setValue(V &&value) {\n value_.setValue(std::forward(value));\n }\n\n bool operator==(const IItem &other) const final {\n if (typeid(*this) != typeid(other)) {\n return false;\n }\n return *this == *reinterpret_cast(&other);\n }\n\n bool operator==(const Item &other) const { return this == std::addressof(other) || value() == other.value(); }\n\n bool operator==(const T &val) const { return value() == val; }\n\n String toString() const final {\n toml::table table;\n toToml(table);\n auto *view = table.get(name_);\n if constexpr (is_optional_v) {\n return view ? tomlToString(*view) : \"nullopt\";\n } else {\n return tomlToString(*view);\n }\n }\n\n bool checkAndSet(ReturnType value) {\n if (checker_(value)) {\n setValue(value);\n return true;\n }\n return false;\n }\n\n Result update(const toml::node &node, bool isHotUpdate, const std::string &path) final {\n try {\n bool enableUpdate = supportHotUpdate_ || !isHotUpdate;\n if constexpr (is_vector_v || is_set_v) {\n return updateVectorOrSet(node, enableUpdate, path);\n } else if constexpr (is_map_v) {\n return updateMap(node, enableUpdate, path);\n } else {\n return updateNormal(node, enableUpdate, path);\n }\n } catch (const std::exception &e) {\n return makeError(StatusCode::kConfigUpdateFailed, fmt::format(\"name: {}, error: {}\", path, e.what()));\n }\n }\n\n Result validate(const std::string &path) const final {\n if (!checker_(value())) {\n return makeError(StatusCode::kConfigValidateFailed, fmt::format(\"Check failed: {}\", path));\n }\n return Void{};\n }\n\n void toToml(toml::table &table) const override {\n if constexpr (is_vector_v || is_set_v) {\n toml::array array;\n for (const auto &item : value()) {\n array.emplace_back(ConfigValueToTomlNode{}(item));\n }\n table.insert_or_assign(name_, std::move(array));\n } else if constexpr (is_map_v) {\n toml::table inlineTable;\n for (const auto &pair : value()) {\n inlineTable.emplace(pair.first, ConfigValueToTomlNode{}(pair.second));\n }\n inlineTable.is_inline(true);\n table.insert_or_assign(name_, std::move(inlineTable));\n } else if constexpr (is_optional_v) {\n if (value().has_value()) {\n table.insert_or_assign(name_, ConfigValueToTomlNode>{}(value().value()));\n }\n } else {\n table.insert_or_assign(name_, ConfigValueToTomlNode{}(value()));\n }\n }\n\n bool isParsedFromString() const override {\n return std::is_constructible_v, std::string> || std::is_enum_v>;\n }\n\n protected:\n Result updateNormal(const toml::node &node, bool enableUpdate, const std::string &path) {\n try {\n auto res = tomlNodeToValue>(node);\n if (res.hasError()) {\n return makeError(StatusCode::kConfigUpdateFailed, fmt::format(\"name: {}, error: {}\", path, res.error()));\n }\n if (!checker_(res.value())) {\n return makeError(StatusCode::kConfigValidateFailed, fmt::format(\"Check failed: {}\", path));\n }\n if (res.value() != value()) {\n if (enableUpdate) {\n setValue(std::move(res.value()));\n } else {\n return makeError(StatusCode::kConfigUpdateFailed, fmt::format(\"Not support hot update: {}\", path));\n }\n }\n return Void{};\n } catch (const std::exception &e) {\n return makeError(StatusCode::kConfigUpdateFailed, fmt::format(\"throws when update {}: {}\", path, e.what()));\n }\n }\n\n Result updateVectorOrSet(const toml::node &node, bool enableUpdate, const std::string &path) {\n using I = typename T::value_type;\n\n if (!node.is_array()) {\n return makeError(StatusCode::kConfigInvalidType, fmt::format(\"Not array: {}\", path));\n }\n auto arr = node.as_array();\n if (arr == nullptr) {\n return makeError(StatusCode::kConfigInvalidValue, fmt::format(\"Empty array: {}\", path));\n }\n\n T tmp;\n for (size_t i = 0; i < arr->size(); ++i) {\n const auto &e = (*arr)[i];\n auto res = [&]() -> Result {\n if constexpr (std::derived_from) {\n if (!e.is_table()) {\n return makeError(StatusCode::kConfigInvalidType, fmt::format(\"Not table: {}[{}]\", path, i));\n }\n I v;\n RETURN_ON_ERROR(v.update(*e.as_table(), /*isHotUpdate=*/false));\n return v;\n } else {\n return tomlNodeToValue>(e);\n }\n }();\n if (res.hasError()) {\n return makeError(StatusCode::kConfigUpdateFailed, fmt::format(\"name: {}, error: {}\", path, res.error()));\n }\n if constexpr (is_set_v) {\n auto [it, succ] = tmp.emplace(std::move(res.value()));\n if (!succ) {\n return makeError(StatusCode::kConfigUpdateFailed, fmt::format(\"name: {}, set value repeats\", path));\n }\n } else {\n tmp.push_back(std::move(res.value()));\n }\n }\n if (!checker_(tmp)) {\n return makeError(StatusCode::kConfigValidateFailed, fmt::format(\"Array check failed: {}\", path));\n }\n if (tmp != value()) {\n if (enableUpdate) {\n value_.setValue(std::move(tmp));\n } else {\n return makeError(StatusCode::kConfigUpdateFailed, fmt::format(\"Not support hot update: {}\", path));\n }\n }\n return Void{};\n }\n\n Result updateMap(const toml::node &node, bool enableUpdate, const std::string &path) {\n using I = typename T::mapped_type;\n\n if (!node.is_table()) {\n return makeError(StatusCode::kConfigInvalidType, fmt::format(\"Not map: {}\", path));\n }\n auto table = node.as_table();\n if (table == nullptr) {\n return makeError(StatusCode::kConfigInvalidValue, fmt::format(\"Empty map: {}\", path));\n }\n\n T tmp;\n for (const auto &e : *table) {\n auto res = tomlNodeToValue(e.second);\n if (res.hasError()) {\n return makeError(StatusCode::kConfigUpdateFailed, fmt::format(\"name: {}, error: {}\", path, res.error()));\n }\n auto [it, succ] = tmp.emplace(std::string{e.first.str()}, std::move(res.value()));\n if (!succ) {\n return makeError(StatusCode::kConfigRedundantKey,\n fmt::format(\"name: {}, redundant key: {}\", path, e.first.str()));\n }\n }\n if (!checker_(tmp)) {\n return makeError(StatusCode::kConfigValidateFailed, fmt::format(\"Array check failed: {}\", path));\n }\n if (tmp != value()) {\n if (enableUpdate) {\n value_.setValue(std::move(tmp));\n } else {\n return makeError(StatusCode::kConfigUpdateFailed, fmt::format(\"Not support hot update: {}\", path));\n }\n }\n return Void{};\n }\n\n private:\n StoreType value_;\n std::string name_;\n bool supportHotUpdate_ = false;\n std::function)> checker_;\n};\n\ninline std::string concat(const std::string &a, const std::string &b) { return a.empty() ? b : a + \".\" + b; }\n\n} // namespace config\n\nusing config::ConfigCallbackGuard;\n\ntemplate \nclass ConfigBase : public config::IConfig {\n protected:\n ConfigBase() = default;\n ConfigBase(const ConfigBase &o)\n : sections_(o.sections_),\n items_(o.items_),\n lengths_(o.lengths_) {}\n ConfigBase &operator=(const ConfigBase &) { return *this; }\n\n public:\n using config::IConfig::update;\n Result update(const toml::table &table, bool isHotUpdate = true, const std::string &path = {}) final {\n auto self = reinterpret_cast(this);\n auto lock = std::unique_lock(mutex_);\n\n for (auto &pair : table) {\n auto name = std::string(pair.first.str());\n auto &node = pair.second;\n\n if (lengths().count(name)) {\n if (!(node.is_array_of_tables() || (node.is_array() && node.as_array()->empty()))) {\n return makeError(StatusCode::kConfigInvalidType, fmt::format(\"Not array of table: {}\", name));\n }\n auto array = node.as_array();\n auto size = array->size();\n for (auto i = 0ul; i < size; ++i) {\n auto itemName = fmt::format(\"{}#{}\", name, i);\n auto itemTable = array->get_as(i);\n if (itemTable == nullptr) {\n return makeError(StatusCode::kConfigInvalidType, fmt::format(\"Not a table: {}\", itemName));\n }\n if (!sections().count(itemName)) {\n return makeError(StatusCode::kConfigInvalidType, fmt::format(\"Array length exceed: {}\", itemName));\n }\n RETURN_ON_ERROR(\n (self->*(sections().at(itemName))).update(*itemTable, isHotUpdate, config::concat(path, itemName)));\n }\n self->*(lengths().at(name)) = size;\n } else if (sections().count(name)) {\n if (!node.is_table()) {\n return makeError(StatusCode::kConfigInvalidType, fmt::format(\"Not table: {}\", name));\n }\n RETURN_ON_ERROR(\n (self->*(sections().at(name))).update(*node.as_table(), isHotUpdate, config::concat(path, name)));\n } else if (items().count(name)) {\n RETURN_ON_ERROR((self->*(items().at(name))).update(node, isHotUpdate, config::concat(path, name)));\n } else {\n return makeError(StatusCode::kConfigRedundantKey, fmt::format(\"Invalid key: {}\", config::concat(path, name)));\n }\n }\n\n // call callbacks after update.\n for (auto &callback : callbacks_) {\n callback->callCallback();\n }\n return overallValidate();\n }\n\n toml::table toToml() const final {\n auto lock = std::unique_lock(mutex_);\n\n auto self = reinterpret_cast(this);\n toml::table table;\n for (auto &pair : items()) {\n (self->*pair.second).toToml(table);\n }\n if constexpr (requires { Parent::is_variant_type; }) {\n auto it = sections().find(self->type());\n if (it != sections().end()) {\n table.insert_or_assign(it->first, (self->*it->second).toToml());\n }\n return table;\n }\n for (auto &pair : sections()) {\n if (pair.first.find('#') != std::string::npos) {\n continue;\n }\n table.insert_or_assign(pair.first, (self->*pair.second).toToml());\n }\n for (auto &pair : lengths()) {\n toml::array array;\n for (auto i = 0ul; i < self->*pair.second; ++i) {\n array.emplace_back((self->*sections().at(fmt::format(\"{}#{}\", pair.first, i))).toToml());\n }\n table.insert_or_assign(pair.first, std::move(array));\n }\n return table;\n }\n\n Result toToml(std::string_view key) const final {\n if (key.empty()) return toToml();\n\n auto self = reinterpret_cast(this);\n\n auto pos = key.find('.');\n if (pos == std::string_view::npos) {\n auto iit = items().find(key);\n if (iit != items().end()) {\n toml::table table;\n (self->*(iit->second)).toToml(table);\n return table;\n }\n auto sit = sections().find(key);\n if (sit != sections().end()) {\n return (self->*(sit->second)).toToml();\n }\n return makeError(StatusCode::kConfigKeyNotFound, key);\n } else {\n auto section = key.substr(0, pos);\n key.remove_prefix(pos + 1);\n auto it = sections().find(section);\n if (it != sections().end()) {\n return (self->*(it->second)).toToml(key);\n }\n return makeError(StatusCode::kConfigKeyNotFound, section);\n }\n }\n\n Result find(std::string_view key) final {\n auto self = reinterpret_cast(this);\n\n auto pos = key.find('.');\n if (pos == std::string_view::npos) {\n auto it = items().find(std::string{key});\n if (it == items().end()) {\n return makeError(StatusCode::kConfigValidateFailed);\n }\n return &(self->*(it->second));\n } else {\n auto section = key.substr(0, pos);\n key.remove_prefix(pos + 1);\n auto it = sections().find(std::string{section});\n if (it == sections().end()) {\n return makeError(StatusCode::kConfigValidateFailed);\n }\n return (self->*(it->second)).find(key);\n }\n }\n\n std::unique_ptr clonePtr() const final { return std::make_unique(clone()); }\n\n std::unique_ptr defaultPtr() const final { return std::make_unique(); }\n\n // clone current configuration. [thread safe]\n Parent clone() const {\n auto lock = std::unique_lock(mutex_);\n return reinterpret_cast(*this);\n }\n\n // copy from another configuration. [thread safe]\n void copy(const Parent &o) {\n std::scoped_lock lock(mutex_, o.mutex_);\n reinterpret_cast(*this) = o;\n }\n\n // atomically update configuration from a string.\n using IConfig::atomicallyUpdate;\n Result atomicallyUpdate(std::string_view str, bool isHotUpdate) final {\n Parent newConfig = clone();\n RETURN_ON_ERROR(newConfig.update(str, isHotUpdate));\n auto res = update(str, isHotUpdate);\n XLOGF_IF(FATAL, !res, \"Unexpected update error: {}\", res.error());\n return Void{};\n }\n\n // atomically update configuration from a file.\n Result atomicallyUpdate(const Path &path, bool isHotUpdate) final {\n Parent newConfig = clone();\n RETURN_ON_ERROR(newConfig.IConfig::update(path, isHotUpdate));\n auto res = update(path, isHotUpdate);\n XLOGF_IF(FATAL, !res, \"Unexpected update error: {}\", res.error());\n return Void{};\n }\n\n Result atomicallyUpdate(const std::vector &updates, bool isHotUpdate) final {\n Parent newConfig = clone();\n RETURN_ON_ERROR(newConfig.IConfig::update(updates, isHotUpdate));\n auto res = update(updates, isHotUpdate);\n XLOGF_IF(FATAL, !res, \"Unexpected update error: {}\", res.error());\n return Void{};\n }\n\n Result validateUpdate(std::string_view str, bool isHotUpdate) final {\n Parent newConfig = clone();\n RETURN_ON_ERROR(newConfig.IConfig::update(str, isHotUpdate));\n return Void{};\n }\n\n Result validate(const std::string &path = {}) const final {\n auto self = reinterpret_cast(this);\n for (auto &pair : sections()) {\n RETURN_ON_ERROR((self->*pair.second).validate(config::concat(path, pair.first)));\n }\n for (auto &pair : items()) {\n RETURN_ON_ERROR((self->*pair.second).validate(config::concat(path, pair.first)));\n }\n return overallValidate();\n }\n\n // add callback guard.\n std::unique_ptr addCallbackGuard(auto &&...func) const {\n auto guard = std::make_unique(this, std::forward(func)...);\n auto lock = std::unique_lock(mutex_);\n callbacks_.insert(guard.get());\n return guard;\n }\n\n bool operator==(const config::IConfig &other) const final {\n if (typeid(*this) != typeid(other)) {\n return false;\n }\n if (this == std::addressof(other)) {\n return true;\n }\n return *this == *reinterpret_cast(&other);\n }\n\n bool operator==(const Parent &other) const {\n ItemDiff diffs[1];\n return diffWith(other, std::span(diffs)) == 0;\n }\n\n using config::IConfig::diffWith;\n size_t diffWith(const config::IConfig &other, String path, std::span diffs, size_t pos) const final {\n XLOGF_IF(FATAL,\n typeid(*this) != typeid(other),\n \"Call diffWith on different config types: {} and {}\",\n typeid(*this).name(),\n typeid(other).name());\n if (this == std::addressof(other)) {\n return pos;\n }\n return diffWith(*reinterpret_cast(&other), std::move(path), diffs, pos);\n }\n\n size_t diffWith(const Parent &other, String path, std::span diffs, size_t pos) const {\n auto &self = *reinterpret_cast(this);\n auto makePath = [&path](const String &name) { return path.empty() ? name : fmt::format(\"{}.{}\", path, name); };\n\n for (const auto &[name, item] : items()) {\n auto &selfItem = self.*item;\n auto &otherItem = other.*item;\n if (!(selfItem == otherItem)) {\n diffs[pos++] = ItemDiff{makePath(name), selfItem.toString(), otherItem.toString()};\n if (pos >= diffs.size()) return pos;\n }\n }\n for (const auto &[name, sec] : sections()) {\n auto &selfSec = self.*sec;\n auto &otherSec = other.*sec;\n pos = selfSec.diffWith(otherSec, makePath(name), diffs, pos);\n if (pos >= diffs.size()) return pos;\n }\n return pos;\n }\n\n protected:\n // remove callback guard.\n void removeCallbackGuard(ConfigCallbackGuard *guard) const final {\n auto lock = std::unique_lock(mutex_);\n callbacks_.erase(guard);\n }\n\n const auto §ions() const noexcept { return sections_; }\n const auto &items() const noexcept { return items_; }\n const auto &lengths() const noexcept { return lengths_; }\n\n protected:\n mutable std::mutex mutex_;\n // offsets of sections.\n std::map> sections_;\n // offsets of items.\n std::map> items_;\n // length of section arrays.\n std::map> lengths_;\n // callbacks after update.\n mutable std::set> callbacks_;\n};\n\nnamespace ConfigCheckers {\ntemplate \nconcept Arithmetic = std::is_arithmetic_v;\n\ntemplate \nconcept Container = requires(T t) {\n t.empty();\n t.size();\n};\n\ntemplate \ninline bool checkGE(T val) {\n return val >= threshold;\n}\n\nstruct CheckPositive {\n template \n bool operator()(T val) const {\n return val > 0;\n }\n};\n\ninline constexpr CheckPositive checkPositive;\n\ntemplate \ninline bool isPositivePrime(T n) {\n if (n < 2) return false;\n for (T f = 2; f * f <= n; f++)\n if (n % f == 0) return false;\n return true;\n}\n\ntemplate \ninline bool checkNotNegative(T val) {\n return val >= 0;\n}\n\nstruct CheckNotEmpty {\n template \n bool operator()(const C &c) const {\n return !c.empty();\n }\n};\n\ninline constexpr CheckNotEmpty checkNotEmpty;\n\ntemplate \ninline bool checkEmpty(const C &c) {\n return c.empty();\n}\n} // namespace ConfigCheckers\n\n} // namespace hf3fs\n\nFMT_BEGIN_NAMESPACE\n\ntemplate <>\nstruct formatter : formatter {\n template \n auto format(const hf3fs::config::IConfig &config, FormatContext &ctx) const {\n return formatter::format(config.toString(), ctx);\n }\n};\n\nFMT_END_NAMESPACE\n"], ["/3FS/src/storage/service/ReliableForwarding.h", "#pragma once\n\n#include \"client/storage/StorageMessenger.h\"\n#include \"common/net/Client.h\"\n#include \"common/net/ib/RDMABuf.h\"\n#include \"common/utils/ConfigBase.h\"\n#include \"fbs/storage/Common.h\"\n#include \"storage/update/UpdateJob.h\"\n\nnamespace hf3fs::storage {\n\nstruct Components;\nstruct Target;\n\nclass ReliableForwarding {\n public:\n struct Config : ConfigBase {\n CONFIG_HOT_UPDATED_ITEM(retry_first_wait, 100_ms);\n CONFIG_HOT_UPDATED_ITEM(retry_max_wait, 1000_ms);\n CONFIG_HOT_UPDATED_ITEM(retry_total_time, 60_s);\n CONFIG_HOT_UPDATED_ITEM(max_inline_forward_bytes, Size{});\n };\n\n ReliableForwarding(const Config &config, Components &components)\n : config_(config),\n components_(components) {}\n\n Result init();\n\n void beforeStop() { stopped_ = true; }\n\n Result stopAndJoin();\n\n CoTask forwardWithRetry(ServiceRequestContext &requestCtx,\n const UpdateReq &req,\n const net::RDMARemoteBuf &rdmabuf,\n const ChunkEngineUpdateJob &chunkEngineJob,\n TargetPtr &target,\n CommitIO &commitIO,\n bool allowOutdatedChainVer = true);\n\n CoTask forward(const UpdateReq &req,\n uint32_t retryCount,\n const net::RDMARemoteBuf &rdmabuf,\n const ChunkEngineUpdateJob &chunkEngineJob,\n TargetPtr &target,\n CommitIO &commitIO,\n std::chrono::milliseconds timeout);\n\n CoTask doForward(const UpdateReq &req,\n const net::RDMARemoteBuf &rdmabuf,\n const ChunkEngineUpdateJob &chunkEngineJob,\n uint32_t retryCount,\n const Target &target,\n bool &isSyncing,\n std::chrono::milliseconds timeout);\n\n private:\n ConstructLog<\"storage::ReliableForwarding\"> constructLog_;\n const Config &config_;\n Components &components_;\n std::atomic stopped_ = false;\n};\n\n} // namespace hf3fs::storage\n"], ["/3FS/src/common/net/ib/RDMABuf.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/net/ib/IBDevice.h\"\n#include \"common/serde/Serde.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/Result.h\"\n\nnamespace hf3fs::net {\n\nusing RDMABufMR = ibv_mr *;\n\nclass RDMARemoteBuf {\n struct Rkey {\n uint32_t rkey = 0;\n int devId = -1;\n\n bool operator==(const Rkey &) const = default;\n };\n\n public:\n RDMARemoteBuf()\n : addr_(0),\n length_(0),\n rkeys_() {}\n\n RDMARemoteBuf(uint64_t addr, size_t length, std::array rkeys)\n : addr_(addr),\n length_(length),\n rkeys_(rkeys) {}\n\n ~RDMARemoteBuf() = default;\n\n uint64_t addr() const { return addr_; }\n size_t size() const { return length_; }\n\n std::optional getRkey(int devId) const {\n for (auto &rkey : rkeys_) {\n if (rkey.devId == devId) {\n return rkey.rkey;\n }\n }\n return std::nullopt;\n }\n\n bool advance(size_t len) {\n if (UNLIKELY(length_ < len)) {\n return false;\n }\n addr_ += len;\n length_ -= len;\n return true;\n }\n bool subtract(size_t n) {\n if (UNLIKELY(n > size())) {\n return false;\n }\n length_ -= n;\n return true;\n }\n\n RDMARemoteBuf subrange(size_t offset, size_t len) const {\n if (UNLIKELY(offset + len > length_)) {\n return RDMARemoteBuf();\n }\n RDMARemoteBuf remote = *this;\n remote.addr_ = addr_ + offset;\n remote.length_ = len;\n return remote;\n }\n\n RDMARemoteBuf first(size_t len) const { return subrange(0, len); }\n RDMARemoteBuf takeFirst(size_t len) {\n auto buf = first(len);\n advance(len);\n return buf;\n }\n\n RDMARemoteBuf last(size_t len) const {\n if (UNLIKELY(len > length_)) {\n return RDMARemoteBuf();\n }\n return subrange(length_ - len, len);\n }\n RDMARemoteBuf takeLast(size_t len) {\n auto buf = last(len);\n subtract(len);\n return buf;\n }\n\n bool valid() const { return addr_ != 0; }\n explicit operator bool() const { return valid(); }\n\n bool operator==(const RDMARemoteBuf &o) const = default;\n\n auto &rkeys() { return rkeys_; }\n const auto &rkeys() const { return rkeys_; }\n\n private:\n friend class RDMABuf;\n FRIEND_TEST(TestRDMARemoteBuf, Basic);\n FRIEND_TEST(TestIBSocket, RDMAFailure);\n\n uint64_t addr_;\n uint64_t length_;\n std::array rkeys_;\n};\n\nclass RDMABufPool;\n\nclass RDMABuf {\n public:\n RDMABuf()\n : RDMABuf(nullptr, nullptr, 0) {}\n\n RDMABuf(const RDMABuf &) = default;\n RDMABuf(RDMABuf &&) = default;\n\n RDMABuf &operator=(const RDMABuf &) = default;\n RDMABuf &operator=(RDMABuf &&) = default;\n\n static RDMABuf allocate(size_t size) { return allocate(size, {}); }\n\n bool valid() const { return buf_ != nullptr; }\n explicit operator bool() const { return valid(); }\n auto raw() const { return buf_.get(); }\n\n const uint8_t *ptr() const { return begin_; }\n uint8_t *ptr() { return begin_; }\n\n size_t capacity() const { return buf_ ? buf_->capacity() : 0; }\n size_t size() const { return length_; }\n bool empty() const { return size() == 0; }\n\n bool contains(const uint8_t *data, uint32_t len) const { return ptr() <= data && data + len <= ptr() + capacity(); }\n\n void resetRange() {\n if (LIKELY(buf_ != nullptr)) {\n begin_ = buf_->ptr();\n length_ = buf_->capacity();\n }\n }\n\n bool advance(size_t n) {\n if (UNLIKELY(n > size())) {\n return false;\n }\n begin_ += n;\n length_ -= n;\n return true;\n }\n bool subtract(size_t n) {\n if (UNLIKELY(n > size())) {\n return false;\n }\n length_ -= n;\n return true;\n }\n\n RDMABuf subrange(size_t offset, size_t length) const {\n if (UNLIKELY(offset + length > size())) {\n return RDMABuf();\n }\n return RDMABuf(buf_, begin_ + offset, length);\n }\n\n RDMABuf first(size_t length) const { return subrange(0, length); }\n RDMABuf takeFirst(size_t length) {\n auto buf = first(length);\n advance(length);\n return buf;\n }\n\n RDMABuf last(size_t length) const {\n if (UNLIKELY(length > size())) {\n return RDMABuf();\n }\n return subrange(size() - length, length);\n }\n RDMABuf takeLast(size_t length) {\n auto buf = last(length);\n subtract(length);\n return buf;\n }\n\n RDMABufMR getMR(int dev) const {\n if (UNLIKELY(buf_ == nullptr)) {\n return RDMABufMR();\n }\n return buf_->getMR(dev);\n }\n\n RDMARemoteBuf toRemoteBuf() const {\n std::array rkeys;\n if (UNLIKELY(!buf_ || !buf_->getRkeys(rkeys))) {\n return RDMARemoteBuf();\n }\n return RDMARemoteBuf((uint64_t)begin_, length_, rkeys);\n }\n\n operator RDMARemoteBuf() { return toRemoteBuf(); }\n\n operator std::span() const { return {ptr(), size()}; }\n operator std::span() { return {ptr(), size()}; }\n\n operator folly::MutableByteRange() { return {ptr(), size()}; }\n operator folly::ByteRange() const { return {ptr(), size()}; }\n\n bool operator==(const RDMABuf &o) const = default;\n\n private:\n friend class RDMABufPool;\n\n class Inner : folly::MoveOnly {\n public:\n static constexpr int kAccessFlags =\n IBV_ACCESS_LOCAL_WRITE | IBV_ACCESS_REMOTE_WRITE | IBV_ACCESS_REMOTE_READ | IBV_ACCESS_RELAXED_ORDERING;\n\n Inner(size_t capacity)\n : Inner(std::weak_ptr(), capacity) {}\n\n Inner(std::weak_ptr pool, size_t capacity)\n : pool_(std::move(pool)),\n ptr_(nullptr),\n capacity_(capacity),\n mrs_(),\n userBuffer_(false) {}\n\n Inner(uint8_t *buf, size_t len)\n : pool_(std::weak_ptr()),\n ptr_(buf),\n capacity_(len),\n mrs_(),\n userBuffer_(true) {}\n\n Inner(Inner &&o)\n : pool_(std::move(o.pool_)),\n ptr_(std::exchange(o.ptr_, nullptr)),\n capacity_(std::exchange(o.capacity_, 0)),\n mrs_(std::exchange(o.mrs_, std::array())),\n userBuffer_(std::exchange(o.userBuffer_, false)) {}\n\n ~Inner();\n\n static void deallocate(Inner *ptr);\n\n int init();\n int allocateMemory();\n int registerMemory();\n\n RDMABufMR getMR(int dev) const;\n bool getRkeys(std::array &rkeys) const;\n\n const uint8_t *ptr() const { return ptr_; }\n uint8_t *ptr() { return ptr_; }\n size_t capacity() const { return capacity_; }\n\n private:\n std::weak_ptr pool_;\n uint8_t *ptr_;\n size_t capacity_;\n std::array mrs_;\n bool userBuffer_;\n };\n\n static RDMABuf allocate(size_t size, std::weak_ptr pool);\n\n public:\n RDMABuf(Inner *buf)\n : RDMABuf(std::shared_ptr(buf, Inner::deallocate)) {}\n\n RDMABuf(std::shared_ptr buf)\n : buf_(std::move(buf)) {\n begin_ = buf_->ptr();\n length_ = buf_->capacity();\n }\n\n RDMABuf(std::shared_ptr buf, uint8_t *begin, size_t length)\n : buf_(std::move(buf)),\n begin_(begin),\n length_(length) {}\n\n static RDMABuf createFromUserBuffer(uint8_t *buf, size_t len);\n\n private:\n std::shared_ptr buf_;\n uint8_t *begin_;\n size_t length_;\n};\n\nclass RDMABufPool : public std::enable_shared_from_this, folly::MoveOnly {\n struct PrivateTag {};\n\n public:\n RDMABufPool(PrivateTag, size_t bufSize, size_t bufCnt)\n : bufSize_(bufSize),\n bufAllocated_(0),\n sem_(bufCnt),\n mutex_(),\n freeList_() {}\n\n ~RDMABufPool();\n\n static std::shared_ptr create(size_t bufSize, size_t bufCnt) {\n return std::make_shared(PrivateTag(), bufSize, bufCnt);\n }\n\n CoTask allocate(std::optional timeout = std::nullopt);\n void deallocate(RDMABuf::Inner *buf);\n\n size_t bufSize() const { return bufSize_; }\n size_t freeCnt() const { return sem_.getAvailableTokens(); }\n size_t totalCnt() const { return sem_.getCapacity(); }\n\n private:\n size_t bufSize_;\n std::atomic bufAllocated_;\n\n folly::fibers::Semaphore sem_;\n std::mutex mutex_;\n std::deque freeList_;\n};\n\n} // namespace hf3fs::net\n\ntemplate <>\nstruct ::hf3fs::serde::SerdeMethod<::hf3fs::net::RDMARemoteBuf> {\n static constexpr auto serialize(const net::RDMARemoteBuf &buf, auto &out) {\n uint8_t len = 0;\n for (auto &rkey : buf.rkeys()) {\n if (rkey.devId == -1) {\n break;\n } else {\n ++len;\n }\n }\n\n for (int8_t i = len - 1; i >= 0; --i) {\n serde::serialize(buf.rkeys()[i].devId, out);\n serde::serialize(buf.rkeys()[i].rkey, out);\n }\n serde::serialize(len, out);\n\n serde::serialize(buf.size(), out);\n serde::serialize(buf.addr(), out);\n }\n\n static Result deserialize(net::RDMARemoteBuf &buf, auto &&in) {\n uint64_t addr;\n uint64_t size;\n RETURN_AND_LOG_ON_ERROR(serde::deserialize(addr, in));\n RETURN_AND_LOG_ON_ERROR(serde::deserialize(size, in));\n\n int8_t len;\n RETURN_AND_LOG_ON_ERROR(serde::deserialize(len, in));\n\n auto rkeys = buf.rkeys();\n for (auto &rkey : rkeys) {\n if (len-- > 0) {\n RETURN_AND_LOG_ON_ERROR(serde::deserialize(rkey.rkey, in));\n RETURN_AND_LOG_ON_ERROR(serde::deserialize(rkey.devId, in));\n } else {\n rkey.devId = -1;\n }\n }\n buf = net::RDMARemoteBuf(addr, size, rkeys);\n return Void{};\n }\n\n static auto serializeReadable(const net::RDMARemoteBuf &buf, auto &out) {\n auto start = out.tableBegin(false);\n {\n out.key(\"addr\");\n serde::serialize(buf.addr(), out);\n out.key(\"size\");\n serde::serialize(buf.size(), out);\n\n out.key(\"rkeys\");\n out.arrayBegin();\n {\n for (auto &rkey : buf.rkeys()) {\n if (rkey.devId == -1) {\n break;\n }\n\n auto start = out.tableBegin(false);\n out.key(\"rkey\");\n serde::serialize(rkey.rkey, out);\n out.key(\"devId\");\n serde::serialize(rkey.devId, out);\n out.tableEnd(start);\n }\n }\n out.arrayEnd(0);\n }\n out.tableEnd(start);\n };\n\n static std::string serdeToReadable(const net::RDMARemoteBuf &rdmabuf) { return serde::toJsonString(rdmabuf); }\n\n static Result serdeFromReadable(const std::string &str) {\n net::RDMARemoteBuf rdmabuf;\n auto result = serde::fromJsonString(rdmabuf, str);\n if (result) return rdmabuf;\n return makeError(result.error());\n }\n};\n"], ["/3FS/src/fbs/storage/Common.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"client/mgmtd/RoutingInfo.h\"\n#include \"common/app/ClientId.h\"\n#include \"common/net/ib/RDMABuf.h\"\n#include \"common/utils/Reflection.h\"\n#include \"common/utils/Result.h\"\n#include \"common/utils/StrongType.h\"\n#include \"common/utils/Uuid.h\"\n#include \"fbs/core/user/User.h\"\n#include \"fbs/mgmtd/MgmtdTypes.h\"\n#include \"fbs/mgmtd/NodeInfo.h\"\n\nnamespace hf3fs::storage {\nusing ChainId = ::hf3fs::flat::ChainId;\nusing ChainVer = ::hf3fs::flat::ChainVersion;\nusing TargetId = ::hf3fs::flat::TargetId;\nusing NodeId = ::hf3fs::flat::NodeId;\n\nSTRONG_TYPEDEF(uint32_t, ChunkVer);\nSTRONG_TYPEDEF(uint64_t, RequestId);\nSTRONG_TYPEDEF(uint16_t, ChannelId);\nSTRONG_TYPEDEF(uint64_t, ChannelSeqNum);\n\n#define BITFLAGS_SET(x, bits) ((x) |= static_cast(bits))\n#define BITFLAGS_CLEAR(x, bits) ((x) &= (~static_cast(bits)))\n#define BITFLAGS_CONTAIN(x, bits) (((x) & static_cast(bits)) == static_cast(bits))\n\n#define ALIGN_LOWER(mem, align) ((mem) / (align) * (align))\n#define ALIGN_UPPER(mem, align) (((mem) + (align)-1) / (align) * (align))\n\n/* start of fault injection helpers */\n\n#ifndef NDEBUG\n#define FAULT_INJECTION_POINT(injectError, injectedRes, funcRes) \\\n (UNLIKELY(injectError) ? (XLOGF(WARN, \"Injected error: {}\", (injectedRes)), (injectedRes)) : (funcRes))\n#else\n#define FAULT_INJECTION_POINT(injectError, injectedRes, funcRes) (boost::ignore_unused(injectError), (funcRes))\n#endif\n\n/* end of fault injection helpers */\n\nenum class UpdateType : uint8_t {\n INVALID = 0,\n WRITE = 1,\n REMOVE = 2,\n TRUNCATE = 4,\n EXTEND = 8,\n COMMIT = 16,\n};\n\nenum class ChunkState : uint8_t {\n COMMIT = 0,\n DIRTY = 1,\n CLEAN = 2,\n};\n\nenum class ChecksumType : uint8_t {\n NONE = 0,\n CRC32C = 1,\n CRC32 = 2,\n};\n\nenum class FeatureFlags : uint32_t {\n DEFAULT = 0,\n BYPASS_DISKIO = 1,\n BYPASS_RDMAXMIT = 2,\n SEND_DATA_INLINE = 4,\n ALLOW_READ_UNCOMMITTED = 8,\n};\n\nconstexpr auto kAIOAlignSize = 4096ul;\n\nclass ChunkId {\n public:\n ChunkId() = default;\n explicit ChunkId(const std::string &data)\n : data_(data) {}\n explicit ChunkId(std::string_view data)\n : data_(data) {}\n explicit ChunkId(std::string &&data)\n : data_(std::move(data)) {}\n\n // special constructors to create 128-bit chunk id from 64-bit integers\n ChunkId(uint64_t high, uint64_t low);\n ChunkId(const ChunkId &baseChunkId, uint64_t chunkIndex);\n\n bool operator==(const ChunkId &other) const { return other.data_ == data_; }\n auto operator<=>(const ChunkId &other) const { return data_ <=> other.data_; }\n\n ChunkId nextChunkId() const;\n\n ChunkId rangeEndForCurrentChunk() const;\n\n auto &data() const { return data_; }\n std::string describe() const;\n std::string toString() const { return describe(); }\n static Result fromString(std::string_view str);\n\n private:\n std::string data_;\n};\nstatic_assert(serde::Serializable);\n\nstruct ChecksumInfo {\n SERDE_STRUCT_FIELD(type, ChecksumType::NONE);\n SERDE_STRUCT_FIELD(value, uint32_t{});\n\n public:\n static constexpr size_t kChunkSize = 1_MB;\n\n class DataIterator {\n public:\n virtual ~DataIterator() = default;\n virtual std::pair next() = 0;\n };\n\n class MemoryDataIterator : public DataIterator {\n public:\n MemoryDataIterator(const uint8_t *buffer, size_t length)\n : buffer_(buffer),\n length_(length) {}\n\n std::pair next() override {\n if (length_ == 0) return {nullptr, 0};\n const uint8_t *data = buffer_;\n size_t size = std::min(length_, ChecksumInfo::kChunkSize);\n buffer_ += size;\n length_ -= size;\n return {data, size};\n }\n\n private:\n const uint8_t *buffer_;\n size_t length_;\n };\n\n static ChecksumInfo create(ChecksumType type, DataIterator *iter, size_t length, uint32_t startingChecksum = ~0U) {\n ChecksumInfo checksum = {type, startingChecksum};\n size_t iterBytes = 0;\n\n if (type == ChecksumType::NONE) return ChecksumInfo{ChecksumType::NONE, 0U};\n\n for (auto data = iter->next(); data.first != nullptr && iterBytes < length; data = iter->next()) {\n iterBytes += data.second;\n switch (checksum.type) {\n case ChecksumType::NONE:\n break;\n case ChecksumType::CRC32C:\n checksum.value = folly::crc32c(data.first, data.second, checksum.value);\n break;\n case ChecksumType::CRC32:\n checksum.value = folly::crc32(data.first, data.second, checksum.value);\n break;\n }\n }\n\n if (iterBytes != length) {\n XLOGF(WARN, \"Iterated bytes {} not equal to length {}, checksum {}\", iterBytes, length, checksum);\n return ChecksumInfo{ChecksumType::NONE, 0U};\n }\n\n return checksum;\n }\n\n static ChecksumInfo create(ChecksumType type, const uint8_t *buffer, size_t length, uint32_t startingChecksum = ~0U) {\n MemoryDataIterator iter(buffer, length);\n return create(type, &iter, length, startingChecksum);\n }\n\n Result combine(const ChecksumInfo &o, size_t length) {\n if (type != ChecksumType::NONE && type != o.type) {\n return makeError(StorageCode::kChecksumMismatch,\n fmt::format(\"diffrent type {} != {}\", serde::toJsonString(*this), serde::toJsonString(o)));\n }\n if (length == 0) return Void{};\n switch (type) {\n case ChecksumType::NONE:\n *this = o;\n return Void{};\n\n case ChecksumType::CRC32C:\n value = folly::crc32c_combine(~value, o.value, length);\n return Void{};\n\n case ChecksumType::CRC32:\n value = folly::crc32_combine(~value, o.value, length);\n return Void{};\n }\n }\n\n bool operator==(const ChecksumInfo &) const = default;\n};\nstatic_assert(serde::Serializable);\n\n} // namespace hf3fs::storage\n\ntemplate <>\nstruct ::hf3fs::serde::SerdeMethod<::hf3fs::storage::ChunkId> {\n static std::string_view serdeTo(const storage::ChunkId &chunkId) { return chunkId.data(); }\n static Result serdeFrom(std::string_view str) { return storage::ChunkId(str); }\n static std::string serdeToReadable(const storage::ChunkId &chunkId) { return chunkId.describe(); };\n static Result serdeFromReadable(std::string_view s) { return storage::ChunkId::fromString(s); }\n};\n\ntemplate <>\nstruct std::hash {\n size_t operator()(const hf3fs::storage::ChunkId &chunkId) const { return std::hash{}(chunkId.data()); }\n};\n\nnamespace hf3fs::storage {\n\nstruct IOResult {\n SERDE_STRUCT_FIELD(lengthInfo, Result{makeError(StorageClientCode::kNotInitialized)});\n SERDE_STRUCT_FIELD(commitVer, ChunkVer{});\n SERDE_STRUCT_FIELD(updateVer, ChunkVer{});\n SERDE_STRUCT_FIELD(checksum, ChecksumInfo{});\n SERDE_STRUCT_FIELD(commitChainVer, ChainVer{});\n\n public:\n IOResult() = default;\n // for IOResult(makeError())\n IOResult(folly::Unexpected &&status)\n : lengthInfo(std::move(status)) {}\n IOResult(uint32_t statusCode)\n : IOResult(makeError(statusCode)) {}\n IOResult(Result lengthInfo,\n ChunkVer commitVer,\n ChunkVer updateVer,\n ChecksumInfo checksum = {},\n ChainVer commitChainVer = {})\n : lengthInfo(lengthInfo),\n commitVer(commitVer),\n updateVer(updateVer),\n checksum(checksum),\n commitChainVer(commitChainVer) {}\n\n bool operator==(const IOResult &other) const = default;\n\n friend void PrintTo(const IOResult &res, std::ostream *os) { *os << fmt::to_string(res); }\n};\nstatic_assert(serde::Serializable);\n\nstruct VersionedChainId {\n bool operator==(const VersionedChainId &) const = default;\n SERDE_STRUCT_FIELD(chainId, ChainId{});\n SERDE_STRUCT_FIELD(chainVer, ChainVer{});\n};\nstatic_assert(serde::Serializable);\n\nstruct GlobalKey {\n SERDE_STRUCT_FIELD(vChainId, VersionedChainId{});\n SERDE_STRUCT_FIELD(chunkId, ChunkId{});\n\n static GlobalKey fromFileOffset(const std::vector &chainIds,\n const ChunkId &baseChunkId,\n const size_t chunkSize,\n const size_t fileOffset);\n};\nstatic_assert(serde::Serializable);\n\nstruct UpdateChannel {\n SERDE_STRUCT_FIELD(id, ChannelId{});\n SERDE_STRUCT_FIELD(seqnum, ChannelSeqNum{});\n};\nstatic_assert(serde::Serializable);\n\nstruct MessageTag {\n SERDE_STRUCT_FIELD(clientId, ClientId{});\n SERDE_STRUCT_FIELD(requestId, RequestId{});\n SERDE_STRUCT_FIELD(channel, UpdateChannel{});\n\n public:\n MessageTag() = default;\n MessageTag(ClientId clientId, RequestId requestId, UpdateChannel channel = UpdateChannel{})\n : clientId(clientId),\n requestId(requestId),\n channel(channel) {}\n};\nstatic_assert(serde::Serializable);\n\nstruct DebugFlags {\n SERDE_STRUCT_FIELD(injectRandomServerError, false);\n SERDE_STRUCT_FIELD(injectRandomClientError, false);\n SERDE_STRUCT_FIELD(numOfInjectPtsBeforeFail, uint16_t{});\n\n private:\n bool isFailPoint() {\n bool fail = numOfInjectPtsBeforeFail == 1;\n if (numOfInjectPtsBeforeFail > 0) numOfInjectPtsBeforeFail--;\n return fail;\n }\n\n public:\n bool faultInjectionEnabled() const { return injectRandomServerError || injectRandomClientError; }\n bool injectServerError() { return injectRandomServerError && isFailPoint(); }\n bool injectClientError() { return injectRandomClientError && isFailPoint(); }\n};\nstatic_assert(serde::Serializable);\n\nstruct ReadIO {\n SERDE_STRUCT_FIELD(offset, uint32_t{});\n SERDE_STRUCT_FIELD(length, uint32_t{});\n SERDE_STRUCT_FIELD(key, GlobalKey{});\n SERDE_STRUCT_FIELD(rdmabuf, net::RDMARemoteBuf{});\n};\nstatic_assert(serde::Serializable);\n\nstruct UInt8Vector {\n SERDE_STRUCT_FIELD(data, std::vector{});\n\n public:\n std::string serdeToReadable() const { return fmt::format(\"std::vector({})\", data.size()); }\n static Result serdeFromReadable(const std::string &) { return UInt8Vector{}; }\n};\nstatic_assert(serde::Serializable);\n\nstruct UpdateIO {\n SERDE_STRUCT_FIELD(offset, uint32_t{});\n SERDE_STRUCT_FIELD(length, uint32_t{});\n SERDE_STRUCT_FIELD(chunkSize, uint32_t{});\n SERDE_STRUCT_FIELD(key, GlobalKey{});\n SERDE_STRUCT_FIELD(rdmabuf, net::RDMARemoteBuf{});\n SERDE_STRUCT_FIELD(updateVer, ChunkVer{});\n SERDE_STRUCT_FIELD(updateType, UpdateType{});\n SERDE_STRUCT_FIELD(checksum, ChecksumInfo{});\n SERDE_STRUCT_FIELD(inlinebuf, UInt8Vector{});\n\n public:\n bool isWrite() const { return updateType == UpdateType::WRITE; }\n bool isTruncate() const { return updateType == UpdateType::TRUNCATE; }\n bool isRemove() const { return updateType == UpdateType::REMOVE; }\n bool isExtend() const { return updateType == UpdateType::EXTEND; }\n bool isCommit() const { return updateType == UpdateType::COMMIT; }\n bool isWriteTruncateExtend() const { return isWrite() || isTruncate() || isExtend(); }\n};\nstatic_assert(serde::Serializable);\n\nstruct CommitIO {\n SERDE_STRUCT_FIELD(key, GlobalKey{});\n SERDE_STRUCT_FIELD(commitVer, ChunkVer{});\n SERDE_STRUCT_FIELD(isSyncing, false);\n SERDE_STRUCT_FIELD(commitChainVer, ChainVer{});\n SERDE_STRUCT_FIELD(isRemove, false);\n SERDE_STRUCT_FIELD(isForce, false);\n};\n\nstruct BatchReadReq {\n SERDE_STRUCT_FIELD(payloads, std::vector{});\n SERDE_STRUCT_FIELD(tag, MessageTag{});\n SERDE_STRUCT_FIELD(retryCount, uint32_t{});\n SERDE_STRUCT_FIELD(userInfo, flat::UserInfo{});\n SERDE_STRUCT_FIELD(featureFlags, uint32_t{});\n SERDE_STRUCT_FIELD(checksumType, ChecksumType{});\n SERDE_STRUCT_FIELD(debugFlags, DebugFlags{});\n};\nstatic_assert(serde::Serializable);\n\nstruct BatchReadRsp {\n SERDE_STRUCT_FIELD(tag, MessageTag{});\n SERDE_STRUCT_FIELD(results, std::vector{});\n SERDE_STRUCT_FIELD(inlinebuf, UInt8Vector{});\n};\nstatic_assert(serde::Serializable);\n\nstruct WriteReq {\n SERDE_STRUCT_FIELD(payload, UpdateIO{});\n SERDE_STRUCT_FIELD(tag, MessageTag{});\n SERDE_STRUCT_FIELD(retryCount, uint32_t{});\n SERDE_STRUCT_FIELD(userInfo, flat::UserInfo{});\n SERDE_STRUCT_FIELD(featureFlags, uint32_t{});\n SERDE_STRUCT_FIELD(debugFlags, DebugFlags{});\n};\nstatic_assert(serde::Serializable);\n\nstruct WriteRsp {\n SERDE_STRUCT_FIELD(tag, MessageTag{});\n SERDE_STRUCT_FIELD(result, IOResult{});\n};\nstatic_assert(serde::Serializable);\n\nstruct UpdateOptions {\n SERDE_STRUCT_FIELD(isSyncing, bool{});\n SERDE_STRUCT_FIELD(fromClient, bool{});\n SERDE_STRUCT_FIELD(commitChainVer, ChainVer{});\n};\n\nstruct UpdateReq {\n SERDE_STRUCT_FIELD(payload, UpdateIO{});\n SERDE_STRUCT_FIELD(options, UpdateOptions{});\n SERDE_STRUCT_FIELD(tag, MessageTag{});\n SERDE_STRUCT_FIELD(retryCount, uint32_t{});\n SERDE_STRUCT_FIELD(userInfo, flat::UserInfo{});\n SERDE_STRUCT_FIELD(featureFlags, uint32_t{});\n SERDE_STRUCT_FIELD(debugFlags, DebugFlags{});\n};\nstatic_assert(serde::Serializable);\n\nstruct UpdateRsp {\n SERDE_STRUCT_FIELD(tag, MessageTag{});\n SERDE_STRUCT_FIELD(result, IOResult{});\n};\nstatic_assert(serde::Serializable);\n\n/* queryLastChunk */\n\nstruct ChunkIdRange {\n SERDE_STRUCT_FIELD(begin, ChunkId{});\n SERDE_STRUCT_FIELD(end, ChunkId{});\n SERDE_STRUCT_FIELD(maxNumChunkIdsToProcess, uint32_t{});\n};\nstatic_assert(serde::Serializable);\n\nstruct QueryLastChunkOp {\n SERDE_STRUCT_FIELD(vChainId, VersionedChainId{});\n SERDE_STRUCT_FIELD(chunkIdRange, ChunkIdRange{});\n};\nstatic_assert(serde::Serializable);\n\nstruct QueryLastChunkReq {\n SERDE_STRUCT_FIELD(payloads, std::vector{});\n SERDE_STRUCT_FIELD(tag, MessageTag{});\n SERDE_STRUCT_FIELD(retryCount, uint32_t{});\n SERDE_STRUCT_FIELD(userInfo, flat::UserInfo{});\n SERDE_STRUCT_FIELD(featureFlags, uint32_t{});\n SERDE_STRUCT_FIELD(debugFlags, DebugFlags{});\n};\nstatic_assert(serde::Serializable);\n\nstruct QueryLastChunkResult {\n SERDE_STRUCT_FIELD(statusCode, Result{makeError(StorageClientCode::kNotInitialized)});\n SERDE_STRUCT_FIELD(lastChunkId, ChunkId{});\n SERDE_STRUCT_FIELD(lastChunkLen, uint32_t{});\n SERDE_STRUCT_FIELD(totalChunkLen, uint64_t{});\n SERDE_STRUCT_FIELD(totalNumChunks, uint64_t{});\n SERDE_STRUCT_FIELD(moreChunksInRange, bool{});\n\n public:\n QueryLastChunkResult() = default;\n QueryLastChunkResult(uint32_t statusCode)\n : QueryLastChunkResult(makeError(statusCode), ChunkId{}, 0, 0, 0, false) {}\n QueryLastChunkResult(const Result &statusCode,\n const ChunkId &lastChunkId,\n uint32_t lastChunkLen,\n uint64_t totalChunkLen,\n uint64_t totalNumChunks,\n bool moreChunksInRange)\n : statusCode(statusCode),\n lastChunkId(lastChunkId),\n lastChunkLen(lastChunkLen),\n totalChunkLen(totalChunkLen),\n totalNumChunks(totalNumChunks),\n moreChunksInRange(moreChunksInRange) {}\n};\nstatic_assert(serde::Serializable);\n\nstruct QueryLastChunkRsp {\n SERDE_STRUCT_FIELD(results, std::vector{});\n};\nstatic_assert(serde::Serializable);\n\n/* removeChunks */\n\nstruct RemoveChunksOp {\n SERDE_STRUCT_FIELD(vChainId, VersionedChainId{});\n SERDE_STRUCT_FIELD(chunkIdRange, ChunkIdRange{});\n SERDE_STRUCT_FIELD(tag, MessageTag{});\n SERDE_STRUCT_FIELD(retryCount, uint32_t{});\n};\nstatic_assert(serde::Serializable);\n\nstruct RemoveChunksReq {\n SERDE_STRUCT_FIELD(payloads, std::vector{});\n SERDE_STRUCT_FIELD(userInfo, flat::UserInfo{});\n SERDE_STRUCT_FIELD(featureFlags, uint32_t{});\n SERDE_STRUCT_FIELD(debugFlags, DebugFlags{});\n};\nstatic_assert(serde::Serializable);\n\nstruct RemoveChunksResult {\n SERDE_STRUCT_FIELD(statusCode, Result{makeError(StorageClientCode::kNotInitialized)});\n SERDE_STRUCT_FIELD(numChunksRemoved, uint32_t{});\n SERDE_STRUCT_FIELD(moreChunksInRange, bool{});\n\n public:\n RemoveChunksResult() = default;\n RemoveChunksResult(uint32_t statusCode)\n : RemoveChunksResult(makeError(statusCode), 0, false) {}\n RemoveChunksResult(const Result &statusCode, uint32_t numChunksRemoved, bool moreChunksInRange)\n : statusCode(statusCode),\n numChunksRemoved(numChunksRemoved),\n moreChunksInRange(moreChunksInRange) {}\n};\nstatic_assert(serde::Serializable);\n\nstruct RemoveChunksRsp {\n SERDE_STRUCT_FIELD(results, std::vector{});\n};\nstatic_assert(serde::Serializable);\n\n/* truncateChunks */\n\nstruct TruncateChunkOp {\n SERDE_STRUCT_FIELD(vChainId, VersionedChainId{});\n SERDE_STRUCT_FIELD(chunkId, ChunkId{});\n SERDE_STRUCT_FIELD(chunkLen, uint32_t{});\n SERDE_STRUCT_FIELD(chunkSize, uint32_t{});\n SERDE_STRUCT_FIELD(onlyExtendChunk, bool{});\n SERDE_STRUCT_FIELD(tag, MessageTag{});\n SERDE_STRUCT_FIELD(retryCount, uint32_t{});\n};\nstatic_assert(serde::Serializable);\n\nstruct TruncateChunksReq {\n SERDE_STRUCT_FIELD(payloads, std::vector{});\n SERDE_STRUCT_FIELD(userInfo, flat::UserInfo{});\n SERDE_STRUCT_FIELD(featureFlags, uint32_t{});\n SERDE_STRUCT_FIELD(debugFlags, DebugFlags{});\n};\nstatic_assert(serde::Serializable);\n\nstruct TruncateChunksRsp {\n SERDE_STRUCT_FIELD(results, std::vector{});\n};\nstatic_assert(serde::Serializable);\n\n/* GetAllChunkMetadata */\n\nstruct ChunkMeta {\n SERDE_STRUCT_FIELD(chunkId, ChunkId{});\n SERDE_STRUCT_FIELD(updateVer, ChunkVer{});\n SERDE_STRUCT_FIELD(commitVer, ChunkVer{});\n SERDE_STRUCT_FIELD(chainVer, ChainVer{});\n SERDE_STRUCT_FIELD(chunkState, ChunkState{});\n SERDE_STRUCT_FIELD(checksum, ChecksumInfo{});\n SERDE_STRUCT_FIELD(length, uint32_t{});\n};\nstatic_assert(serde::Serializable);\n\nusing ChunkMetaVector = std::vector;\n\nstruct GetAllChunkMetadataReq {\n SERDE_STRUCT_FIELD(targetId, TargetId{});\n};\nstatic_assert(serde::Serializable);\n\nstruct GetAllChunkMetadataRsp {\n SERDE_STRUCT_FIELD(chunkMetaVec, ChunkMetaVector{});\n};\nstatic_assert(serde::Serializable);\n\nstruct SyncStartReq {\n SERDE_STRUCT_FIELD(vChainId, VersionedChainId{});\n};\nstatic_assert(serde::Serializable);\n\nstruct TargetSyncInfo {\n SERDE_STRUCT_FIELD(metas, ChunkMetaVector{});\n};\nstatic_assert(serde::Serializable);\n\nstruct SyncDoneReq {\n SERDE_STRUCT_FIELD(vChainId, VersionedChainId{});\n};\nstatic_assert(serde::Serializable);\n\nstruct SyncDoneRsp {\n SERDE_STRUCT_FIELD(result, IOResult{});\n};\nstatic_assert(serde::Serializable);\n\nstruct SpaceInfoReq {\n SERDE_STRUCT_FIELD(tag, MessageTag{});\n SERDE_STRUCT_FIELD(force, bool{});\n};\nstatic_assert(serde::Serializable);\n\nstruct SpaceInfo {\n SERDE_STRUCT_FIELD(path, std::string{});\n SERDE_STRUCT_FIELD(capacity, uint64_t{});\n SERDE_STRUCT_FIELD(free, uint64_t{});\n SERDE_STRUCT_FIELD(available, uint64_t{});\n SERDE_STRUCT_FIELD(targetIds, std::vector{});\n SERDE_STRUCT_FIELD(manufacturer, std::string{});\n};\nstatic_assert(serde::Serializable);\n\nstruct SpaceInfoRsp {\n SERDE_STRUCT_FIELD(spaceInfos, std::vector{});\n};\nstatic_assert(serde::Serializable);\n\nstruct CreateTargetReq {\n SERDE_STRUCT_FIELD(targetId, TargetId{});\n SERDE_STRUCT_FIELD(diskIndex, uint32_t{});\n SERDE_STRUCT_FIELD(physicalFileCount, 256u);\n SERDE_STRUCT_FIELD(chunkSizeList, (std::vector{512_KB, 1_MB, 2_MB, 4_MB, 16_MB, 64_MB}));\n SERDE_STRUCT_FIELD(allowExistingTarget, true);\n SERDE_STRUCT_FIELD(chainId, ChainId{});\n SERDE_STRUCT_FIELD(addChunkSize, false);\n SERDE_STRUCT_FIELD(onlyChunkEngine, false);\n};\n\nstruct CreateTargetRsp {\n SERDE_STRUCT_FIELD(dummy, Void{});\n};\n\nstruct OfflineTargetReq {\n SERDE_STRUCT_FIELD(targetId, TargetId{});\n SERDE_STRUCT_FIELD(force, false);\n};\n\nstruct OfflineTargetRsp {\n SERDE_STRUCT_FIELD(dummy, Void{});\n};\n\nstruct RemoveTargetReq {\n SERDE_STRUCT_FIELD(targetId, TargetId{});\n SERDE_STRUCT_FIELD(force, false);\n};\n\nstruct RemoveTargetRsp {\n SERDE_STRUCT_FIELD(dummy, Void{});\n};\n\nstruct QueryChunkReq {\n SERDE_STRUCT_FIELD(chainId, ChainId{});\n SERDE_STRUCT_FIELD(chunkId, ChunkId{});\n};\n\nstruct ChunkFileId {\n bool operator==(const ChunkFileId &o) const = default;\n SERDE_STRUCT_FIELD(chunkSize, uint32_t{}, nullptr);\n SERDE_STRUCT_FIELD(chunkIdx, uint32_t{}, nullptr);\n};\n\nenum class RecycleState : uint8_t {\n NORMAL,\n REMOVAL_IN_PROGRESS,\n REMOVAL_IN_RETRYING,\n};\n\n// Metadata of chunk. The order of members has been adjusted for smaller size.\nstruct ChunkMetadata {\n bool operator==(const ChunkMetadata &o) const = default;\n\n SERDE_STRUCT_FIELD(commitVer, ChunkVer{}, nullptr);\n SERDE_STRUCT_FIELD(updateVer, ChunkVer{}, nullptr);\n SERDE_STRUCT_FIELD(chainVer, ChainVer{}, nullptr);\n\n SERDE_STRUCT_FIELD(size, uint32_t{}, nullptr);\n SERDE_STRUCT_FIELD(chunkState, ChunkState{}, nullptr);\n SERDE_STRUCT_FIELD(recycleState, RecycleState::NORMAL, nullptr);\n SERDE_STRUCT_FIELD(checksumType, ChecksumType::NONE, nullptr);\n SERDE_STRUCT_FIELD(checksumValue, uint32_t{}, 0);\n\n SERDE_STRUCT_FIELD(lastNodeId, uint16_t{}, nullptr);\n SERDE_STRUCT_FIELD(lastRequestId, RequestId{}, nullptr);\n\n SERDE_STRUCT_FIELD(innerOffset, 0_B, nullptr);\n SERDE_STRUCT_FIELD(innerFileId, ChunkFileId{}, nullptr);\n\n SERDE_STRUCT_FIELD(lastClientUuid, Uuid{});\n SERDE_STRUCT_FIELD(timestamp, UtcTime{});\n\n public:\n bool readyToRemove() const { return recycleState != RecycleState::NORMAL; }\n ChecksumInfo checksum() const { return ChecksumInfo{checksumType, checksumValue}; }\n};\n\nstruct Successor {\n SERDE_STRUCT_FIELD(nodeInfo, flat::NodeInfo{});\n SERDE_STRUCT_FIELD(targetInfo, flat::TargetInfo{});\n};\n\nclass StorageTarget;\nstruct Target {\n std::shared_ptr storageTarget;\n std::weak_ptr weakStorageTarget;\n SERDE_STRUCT_FIELD(targetId, TargetId{});\n SERDE_STRUCT_FIELD(path, Path{});\n SERDE_STRUCT_FIELD(diskError, false);\n SERDE_STRUCT_FIELD(lowSpace, false);\n SERDE_STRUCT_FIELD(rejectCreateChunk, false);\n SERDE_STRUCT_FIELD(isHead, false);\n SERDE_STRUCT_FIELD(isTail, false);\n SERDE_STRUCT_FIELD(vChainId, VersionedChainId{});\n SERDE_STRUCT_FIELD(localState, flat::LocalTargetState::INVALID);\n SERDE_STRUCT_FIELD(publicState, flat::PublicTargetState::INVALID);\n SERDE_STRUCT_FIELD(successor, std::optional{});\n SERDE_STRUCT_FIELD(diskIndex, uint32_t{});\n SERDE_STRUCT_FIELD(chainId, ChainId{});\n SERDE_STRUCT_FIELD(offlineUponUserRequest, false);\n SERDE_STRUCT_FIELD(useChunkEngine, false);\n\n public:\n Result getSuccessorAddr() const;\n\n bool upToDate() const {\n return localState == flat::LocalTargetState::UPTODATE && publicState == flat::PublicTargetState::SERVING;\n }\n\n bool unrecoverableOffline() const { return diskError || offlineUponUserRequest; }\n};\nusing TargetPtr = std::shared_ptr;\n\nstruct QueryChunkRsp {\n SERDE_STRUCT_FIELD(target, Target{});\n SERDE_STRUCT_FIELD(meta, Result{makeError(StatusCode::kInvalidArg)});\n};\n\nstruct ServiceRequestContext {\n const std::string_view requestType = \"dummyReq\";\n const MessageTag tag{};\n const uint32_t retryCount{};\n const flat::UserInfo userInfo{};\n DebugFlags debugFlags{};\n};\n\nstruct StorageEventTrace {\n SERDE_STRUCT_FIELD(clusterId, String{});\n SERDE_STRUCT_FIELD(nodeId, NodeId{});\n SERDE_STRUCT_FIELD(targetId, TargetId{});\n SERDE_STRUCT_FIELD(updateReq, UpdateReq{});\n SERDE_STRUCT_FIELD(updateRes, IOResult{});\n SERDE_STRUCT_FIELD(forwardRes, IOResult{});\n SERDE_STRUCT_FIELD(commitIO, CommitIO{});\n SERDE_STRUCT_FIELD(commitRes, IOResult{});\n};\n\n} // namespace hf3fs::storage\n\nFMT_BEGIN_NAMESPACE\n\ntemplate <>\nstruct formatter : formatter {\n template \n auto format(const hf3fs::storage::ChunkId &chunkId, FormatContext &ctx) const {\n return fmt::format_to(ctx.out(), \"ChunkId({})\", chunkId.describe());\n }\n};\n\ntemplate <>\nstruct formatter : formatter {\n template \n auto format(const hf3fs::storage::ChunkIdRange &range, FormatContext &ctx) const {\n if (range.maxNumChunkIdsToProcess == 1) {\n return fmt::format_to(ctx.out(), \"{}\", range.begin);\n } else {\n return fmt::format_to(ctx.out(),\n \"ChunkIdRange[{}, {}){{{}}}\",\n range.begin.describe(),\n range.end.describe(),\n range.maxNumChunkIdsToProcess);\n }\n }\n};\n\ntemplate <>\nstruct formatter : formatter {\n template \n auto format(const hf3fs::storage::ChecksumInfo &checksum, FormatContext &ctx) const {\n return fmt::format_to(ctx.out(), \"{}#{:08X}\", magic_enum::enum_name(checksum.type), ~checksum.value);\n }\n};\n\ntemplate <>\nstruct formatter : formatter {\n template \n auto format(const hf3fs::storage::IOResult &result, FormatContext &ctx) const {\n return fmt::format_to(ctx.out(),\n \"length{{{}}} version{{{}/{}}} checksum{{{}}} {{{}}}\",\n result.lengthInfo,\n result.updateVer,\n result.commitVer,\n result.checksum,\n result.commitChainVer);\n }\n};\n\ntemplate <>\nstruct formatter : formatter {\n template \n auto format(const hf3fs::storage::UpdateChannel &channel, FormatContext &ctx) const {\n return fmt::format_to(ctx.out(), \"@{}#{}\", channel.id, channel.seqnum);\n }\n};\n\ntemplate <>\nstruct formatter : formatter {\n template \n auto format(const hf3fs::storage::MessageTag &tag, FormatContext &ctx) const {\n return fmt::format_to(ctx.out(), \"@{}#{}:{}\", tag.clientId, tag.requestId, tag.channel);\n }\n};\n\nFMT_END_NAMESPACE\n"], ["/3FS/src/common/app/AppInfo.h", "#pragma once\n\n#include \n#include \n\n#include \"common/app/NodeId.h\"\n#include \"common/serde/SerdeComparisons.h\"\n#include \"common/serde/SerdeHelper.h\"\n#include \"common/utils/Address.h\"\n#include \"common/utils/UtcTime.h\"\n#include \"common/utils/VersionInfo.h\"\n\nnamespace hf3fs::flat {\n\nstruct ServiceGroupInfo : public serde::SerdeHelper {\n ServiceGroupInfo() = default;\n ServiceGroupInfo(std::set ss, std::vector es);\n\n bool operator==(const ServiceGroupInfo &other) const;\n\n SERDE_STRUCT_FIELD(services, std::set{});\n SERDE_STRUCT_FIELD(endpoints, std::vector{});\n};\n\nstruct TagPair : public serde::SerdeHelper {\n TagPair() = default;\n explicit TagPair(String k);\n TagPair(String k, String v);\n\n bool operator==(const TagPair &other) const;\n\n SERDE_STRUCT_FIELD(key, String{});\n SERDE_STRUCT_FIELD(value, String{});\n};\n\nstruct ReleaseVersion : public serde::SerdeHelper {\n ReleaseVersion() = default;\n\n ReleaseVersion(bool isReleaseVersion,\n uint32_t tagDate,\n uint16_t patchVersion,\n uint32_t pipelineId,\n uint32_t commitHashShort);\n\n static ReleaseVersion fromV0(uint8_t majorv,\n uint8_t minorv,\n uint8_t patchv,\n uint32_t shortH,\n uint64_t buildTimeInSec,\n uint32_t buildPipelineId);\n\n static ReleaseVersion fromVersionInfoV0();\n static ReleaseVersion fromVersionInfo();\n\n std::strong_ordering operator<=>(const ReleaseVersion &other) const;\n bool operator==(const ReleaseVersion &other) const;\n\n uint32_t getTagDate() const { return HelperV1::getTagDate(*this); }\n\n uint32_t getPatchVersion() const { return HelperV1::getPatchVersion(*this); }\n\n bool getIsReleaseVersion() const { return HelperV1::getIsReleaseVersion(*this); }\n\n uint32_t getPipelineId() const { return HelperV1::getPipelineId(*this); }\n\n uint32_t getCommitHashShort() const { return HelperV1::getCommitHashShort(*this); }\n\n String toString() const;\n\n private:\n struct HelperV1 {\n static bool getIsReleaseVersion(const ReleaseVersion &rv);\n static void setIsReleaseVersion(ReleaseVersion &rv, bool isReleaseVersion);\n static uint32_t getTagDate(const ReleaseVersion &rv);\n static void setTagDate(ReleaseVersion &rv, uint32_t tagDate);\n static uint32_t getPatchVersion(const ReleaseVersion &rv);\n static void setPatchVersion(ReleaseVersion &rv, uint32_t patchVersion);\n static uint32_t getPipelineId(const ReleaseVersion &rv);\n static void setPipelineId(ReleaseVersion &rv, uint32_t pipelineId);\n static uint32_t getCommitHashShort(const ReleaseVersion &rv);\n static void setCommitHashShort(ReleaseVersion &rv, uint32_t commitHashShort);\n\n private:\n // just for demonstration\n // structVersion_ <=> rv.majorVersion\n // isReleaseVersion_ <=> rv.minorVersion\n // <=> rv.buildTimeInSeconds\n // pipelineId_ <=> rv.pipelineId\n // commitHashShort_ <=> rv.commitHashShort\n const uint8_t structVersion_ = 1;\n bool isReleaseVersion_ = false;\n uint32_t patchVersion_ = 0;\n uint32_t tagDate_ = 0;\n uint32_t pipelineId_ = 0;\n uint32_t commitHashShort_ = 0;\n };\n\n // NOTE: other fields are just for storage when majorVersion != 0\n SERDE_STRUCT_FIELD(majorVersion, uint8_t(1));\n SERDE_STRUCT_FIELD(minorVersion, uint8_t(0));\n SERDE_STRUCT_FIELD(patchVersion, uint8_t(0));\n SERDE_STRUCT_FIELD(commitHashShort, uint32_t(0));\n SERDE_STRUCT_FIELD(buildTimeInSeconds, uint64_t(0));\n SERDE_STRUCT_FIELD(buildPipelineId, uint32_t(0));\n};\n\nstruct FbsAppInfo : public serde::SerdeHelper {\n bool operator==(const FbsAppInfo &other) const;\n\n SERDE_STRUCT_FIELD(nodeId, NodeId(0));\n SERDE_STRUCT_FIELD(hostname, String{});\n SERDE_STRUCT_FIELD(pid, uint32_t(0));\n SERDE_STRUCT_FIELD(serviceGroups, std::vector{});\n SERDE_STRUCT_FIELD(releaseVersion, ReleaseVersion{});\n SERDE_STRUCT_FIELD(podname, String{});\n};\n\nstruct AppInfo : FbsAppInfo {\n bool operator==(const AppInfo &other) const;\n\n String clusterId;\n std::vector tags;\n};\n\nstd::vector extractAddresses(const std::vector &serviceGroups,\n const String &serviceName,\n std::optional addressType = std::nullopt);\n\ninline constexpr auto kDisabledTagKey = \"Disable\";\ninline constexpr auto kTrafficZoneTagKey = \"TrafficZone\";\n\nint findTag(const std::vector &tags, std::string_view tag);\nbool removeTag(std::vector &tags, std::string_view tag);\n} // namespace hf3fs::flat\n\nFMT_BEGIN_NAMESPACE\n\ntemplate <>\nstruct formatter : formatter {\n template \n auto format(const hf3fs::flat::ReleaseVersion val, FormatContext &ctx) const -> decltype(ctx.out()) {\n return fmt::format_to(ctx.out(), \"{}\", val.toString());\n }\n};\n\ntemplate <>\nstruct formatter : formatter {\n template \n auto format(const hf3fs::flat::TagPair val, FormatContext &ctx) const -> decltype(ctx.out()) {\n if (val.value.empty()) {\n return fmt::format_to(ctx.out(), \"{}\", val.key);\n }\n return fmt::format_to(ctx.out(), \"{}={}\", val.key, val.value);\n }\n};\n\nFMT_END_NAMESPACE\n"], ["/3FS/src/client/mgmtd/ICommonMgmtdClient.h", "#pragma once\n\n#include \"RoutingInfo.h\"\n#include \"fbs/mgmtd/Rpc.h\"\n\nnamespace hf3fs::client {\n// ICommonMgmtdClient provides the common facilities:\n// 1. start and stop\n// 2. RoutingInfo\nclass ICommonMgmtdClient {\n public:\n virtual ~ICommonMgmtdClient() = default;\n\n virtual CoTask start(folly::Executor *backgroundExecutor = nullptr, bool startBackground = true) { co_return; }\n\n virtual CoTask startBackgroundTasks() { co_return; }\n\n virtual CoTask stop() { co_return; }\n\n virtual std::shared_ptr getRoutingInfo() = 0;\n\n // manual calls\n virtual CoTryTask refreshRoutingInfo(bool force) = 0;\n\n using RoutingInfoListener = std::function)>;\n virtual bool addRoutingInfoListener(String name, RoutingInfoListener listener) = 0;\n virtual bool removeRoutingInfoListener(std::string_view name) = 0;\n\n virtual CoTryTask listClientSessions() = 0;\n\n virtual CoTryTask> getConfig(flat::NodeType nodeType,\n flat::ConfigVersion version) = 0;\n\n virtual CoTryTask> getUniversalTags(const String &universalId) = 0;\n\n virtual CoTryTask> getConfigVersions() = 0;\n\n virtual CoTryTask getClientSession(const String &clientId) = 0;\n};\n} // namespace hf3fs::client\n"], ["/3FS/src/mgmtd/service/helpers.h", "#include \n#include \n\n#include \"MgmtdConfig.h\"\n#include \"MgmtdOperator.h\"\n#include \"MgmtdState.h\"\n#include \"common/kv/WithTransaction.h\"\n#include \"core/utils/ServiceOperation.h\"\n\n#define RECORD_LATENCY(latency) \\\n auto FB_ANONYMOUS_VARIABLE(guard) = folly::makeGuard([lat = &(latency), begin = std::chrono::steady_clock::now()] { \\\n lat->addSample(std::chrono::steady_clock::now() - begin); \\\n })\n\nnamespace hf3fs::mgmtd {\ntemplate \ninline T nextVersion(T version) {\n auto v = version + 1;\n return T(v);\n}\n\nCoTryTask ensureSelfIsPrimary(MgmtdState &state);\n\ntemplate \ninline std::invoke_result_t doAsPrimary(MgmtdState &state, Handler &&handler) {\n auto ret = co_await ensureSelfIsPrimary(state);\n CO_RETURN_ON_ERROR(ret);\n co_return co_await handler();\n}\n\nvoid updateMemoryRoutingInfo(RoutingInfo &alreadyLockedRoutingInfo, core::ServiceOperation &ctx);\n\ntemplate \ninline CoTask updateMemoryRoutingInfo(MgmtdState &state, core::ServiceOperation &ctx, Handler &&handler) {\n auto dataPtr = co_await state.data_.coLock();\n auto &ri = dataPtr->routingInfo;\n updateMemoryRoutingInfo(ri, ctx);\n handler(ri);\n}\n\nCoTask updateMemoryRoutingInfo(MgmtdState &state, core::ServiceOperation &ctx);\n\ntemplate >\ninline Result withReadWriteTxn(MgmtdState &state, Handler &&handler, bool expectSelfPrimary = true) {\n int maxRetryTimes = state.config_.retry_times_on_txn_errors();\n constexpr auto retryInterval = std::chrono::milliseconds(1000);\n auto strategy = state.createRetryStrategy();\n for (int i = 0;; ++i) {\n auto res = co_await kv::WithTransaction(strategy).run(\n state.env_->kvEngine()->createReadWriteTransaction(),\n [&](kv::IReadWriteTransaction &txn) -> Result {\n if (expectSelfPrimary && state.config_.validate_lease_on_write()) {\n CO_RETURN_ON_ERROR(co_await state.store_.ensureLeaseValid(txn, state.selfId(), state.utcNow()));\n }\n co_return co_await handler(txn);\n });\n if (res || i == maxRetryTimes || StatusCode::typeOf(res.error().code()) != StatusCodeType::Transaction)\n co_return res;\n XLOGF(CRITICAL, \"Transaction failed: {}\\nretryCount: {}\", res.error(), i);\n co_await folly::coro::sleep(retryInterval);\n }\n}\n\ntemplate >\ninline Result withReadOnlyTxn(MgmtdState &state, Handler &&handler) {\n auto strategy = state.createRetryStrategy();\n co_return co_await kv::WithTransaction(strategy).run(\n state.env_->kvEngine()->createReadonlyTransaction(),\n [&](kv::IReadOnlyTransaction &txn) -> Result { co_return co_await handler(txn); });\n}\n\ntemplate \ninline CoTryTask updateStoredRoutingInfo(MgmtdState &state, core::ServiceOperation &ctx, Handler &&handler) {\n auto dataPtr = co_await state.data_.coSharedLock();\n auto nextv = nextVersion(dataPtr->routingInfo.routingInfoVersion);\n co_return co_await withReadWriteTxn(state, [&](kv::IReadWriteTransaction &txn) -> CoTryTask {\n CO_RETURN_ON_ERROR(co_await state.store_.storeRoutingInfoVersion(txn, nextv));\n LOG_OP_INFO(ctx, \"RoutingInfo: bump storage version to {}\", nextv);\n co_return co_await handler(txn);\n });\n}\n\nCoTryTask updateStoredRoutingInfo(MgmtdState &state, core::ServiceOperation &ctx);\n\nflat::TargetInfo makeTargetInfo(flat::ChainId chainId, const flat::ChainTargetInfo &info);\n\nResult updateSelfConfig(MgmtdState &state, const flat::ConfigInfo &cfg);\n\nusing MgmtdStub = mgmtd::IMgmtdServiceStub;\nusing MgmtdStubFactory = stubs::IStubFactory;\n\nResult> updateTags(core::ServiceOperation &op,\n flat::SetTagMode mode,\n const std::vector &oldTags,\n const std::vector &updates);\n} // namespace hf3fs::mgmtd\n"], ["/3FS/src/common/serde/ClientMockContext.h", "#pragma once\n\n#include \n#include \n\n#include \"common/net/Client.h\"\n#include \"common/net/Network.h\"\n#include \"common/net/Server.h\"\n#include \"common/serde/CallContext.h\"\n#include \"common/serde/ClientContext.h\"\n#include \"common/utils/Address.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/Result.h\"\n\nnamespace hf3fs::serde {\n\nclass ClientMockContext {\n public:\n enum IsMock : bool { value = true };\n\n template \n static ClientMockContext create(std::unique_ptr service, net::Address::Type type = net::Address::TCP) {\n ClientMockContext ctx;\n ctx.setService(std::move(service), type);\n return ctx;\n }\n\n template \n bool setService(std::unique_ptr service, net::Address::Type type = net::Address::TCP) {\n pack_ = std::make_shared(type);\n auto setupResult = pack_->server_->setup();\n XLOGF_IF(FATAL, !setupResult, \"setup server failed: {}\", setupResult.error());\n\n auto addResult = pack_->server_->addSerdeService(std::move(service));\n XLOGF_IF(FATAL, !addResult, \"add service failed: {}\", addResult.error());\n\n auto startResult = pack_->server_->start();\n XLOGF_IF(FATAL, !startResult, \"start server failed: {}\", startResult.error());\n\n auto clientResult = pack_->client_->start();\n XLOGF_IF(FATAL, !clientResult, \"start client failed: {}\", clientResult.error());\n return true;\n }\n\n template \n CoTryTask call(const Req &req,\n const net::UserRequestOptions *options = nullptr,\n Timestamp *timestamp = nullptr) {\n auto ctx = pack_->client_->serdeCtx(pack_->server_->groups().front()->addressList().front());\n co_return co_await ctx.call(req, options, timestamp);\n }\n\n template \n Result callSync(const Req &req,\n const net::UserRequestOptions *options = nullptr,\n Timestamp *timestamp = nullptr) {\n return folly::coro::blockingWait(\n call(req, options, timestamp));\n }\n\n private:\n struct ServerPack {\n ServerPack(net::Address::Type type) {\n for (size_t i = 0; i < serverConfig_.groups_length(); i++) {\n serverConfig_.groups(i).set_network_type(type);\n }\n server_ = std::make_unique(serverConfig_);\n client_ = std::make_unique(clientConfig_);\n }\n ~ServerPack() {\n client_->stopAndJoin();\n server_->stopAndJoin();\n }\n net::Server::Config serverConfig_;\n std::unique_ptr server_;\n net::Client::Config clientConfig_;\n std::unique_ptr client_;\n };\n std::shared_ptr pack_;\n};\n\n} // namespace hf3fs::serde\n"], ["/3FS/src/common/utils/ConcurrencyLimiter.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/Shards.h\"\n\nnamespace hf3fs {\n\nclass ConcurrencyLimiterConfig : public ConfigBase {\n CONFIG_HOT_UPDATED_ITEM(max_concurrency, 1u, ConfigCheckers::checkPositive);\n};\n\ntemplate \nclass ConcurrencyLimiter {\n private:\n struct State {\n uint32_t concurrency{};\n std::queue> queue{};\n };\n using Map = std::unordered_map;\n using It = typename Map::iterator;\n const ConcurrencyLimiterConfig &config_;\n Shards shards_;\n\n public:\n ConcurrencyLimiter(const ConcurrencyLimiterConfig &config)\n : config_(config) {}\n\n struct Guard {\n Guard(ConcurrencyLimiter &limiter, std::size_t pos, It it)\n : limiter_(&limiter),\n pos_(pos),\n it_(it) {}\n Guard(const Guard &) = delete;\n Guard(Guard &&o)\n : limiter_(std::exchange(o.limiter_, nullptr)),\n pos_(o.pos_),\n it_(o.it_) {}\n ~Guard() { limiter_ == nullptr ? void() : limiter_->unlock(pos_, it_); }\n\n private:\n ConcurrencyLimiter *limiter_;\n std::size_t pos_;\n It it_;\n };\n\n CoTask lock(const Key &key) {\n folly::coro::Baton baton;\n auto pos = shards_.position(key);\n auto [it, succ] = shards_.withLockAt(\n [&](Map &map) {\n auto [it, succ] = map.emplace(key, State{});\n auto &state = it->second;\n if (state.concurrency < config_.max_concurrency()) {\n ++state.concurrency;\n return std::make_pair(it, true);\n }\n state.queue.push(std::ref(baton));\n return std::make_pair(it, false);\n },\n pos);\n if (!succ) {\n co_await baton;\n }\n co_return Guard{*this, pos, it};\n }\n\n private:\n void unlock(size_t pos, It it) {\n shards_.withLockAt(\n [&](Map &map) {\n auto &state = it->second;\n assert(state.concurrency > 0);\n if (!state.queue.empty()) {\n if (state.concurrency <= config_.max_concurrency()) {\n // wake up the next waiting baton.\n auto next = std::move(state.queue.front());\n state.queue.pop();\n next.get().post();\n } else {\n // give up.\n --state.concurrency;\n }\n } else if (--state.concurrency == 0) {\n // remove current state.\n map.erase(it);\n }\n },\n pos);\n }\n};\n\n} // namespace hf3fs\n"], ["/3FS/src/core/user/UserCache.h", "#pragma once\n\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/LockManager.h\"\n#include \"common/utils/RobinHood.h\"\n#include \"common/utils/UtcTime.h\"\n#include \"fbs/core/user/User.h\"\n\nnamespace hf3fs::core {\nusing flat::Gid;\nusing flat::Uid;\nusing flat::UserAttr;\nusing flat::UserInfo;\n\nclass UserCache {\n public:\n struct Config : ConfigBase {\n CONFIG_ITEM(buckets, 127u, ConfigCheckers::isPositivePrime);\n CONFIG_HOT_UPDATED_ITEM(exist_ttl, 5_min);\n CONFIG_HOT_UPDATED_ITEM(inexist_ttl, 10_s);\n };\n\n explicit UserCache(const Config &cfg)\n : cfg_(cfg),\n lockManager_(cfg.buckets()),\n buckets_(cfg.buckets()) {}\n\n struct GetResult {\n std::optional attr;\n bool marked = false;\n\n static GetResult unmarkedNotExist() { return {std::nullopt, false}; }\n static GetResult markedNotExist() { return {std::nullopt, true}; }\n static GetResult exist(UserAttr attr) { return {std::move(attr), false}; }\n };\n\n GetResult get(Uid id) {\n auto lock = lockManager_.lock(id);\n auto now = SteadyClock::now();\n auto &bucket = buckets_[lockManager_.idx(id)];\n\n auto it = bucket.find(id);\n if (it == bucket.end()) return GetResult::unmarkedNotExist();\n\n auto &entry = it->second;\n if (expired(entry, now)) {\n bucket.erase(it);\n return GetResult::unmarkedNotExist();\n }\n\n if (entry.attr)\n return GetResult::exist(*entry.attr);\n else\n return GetResult::markedNotExist();\n }\n\n void set(Uid id, std::optional attr) {\n auto lock = lockManager_.lock(id);\n auto &bucket = buckets_[lockManager_.idx(id)];\n auto &entry = bucket[id];\n auto now = SteadyClock::now();\n entry.setTs = now;\n entry.attr = std::move(attr);\n }\n\n void clear(Uid id) {\n auto lock = lockManager_.lock(id);\n auto &bucket = buckets_[lockManager_.idx(id)];\n bucket.erase(id);\n }\n\n void clear() {\n for (uint32_t i = 0; i < lockManager_.numBuckets(); ++i) {\n auto lock = lockManager_.lock_at(i);\n auto &bucket = buckets_[i];\n bucket.clear();\n }\n }\n\n void clearRetired() {\n std::vector uids;\n for (uint32_t i = 0; i < lockManager_.numBuckets(); ++i) {\n auto lock = lockManager_.lock_at(i);\n auto &bucket = buckets_[i];\n auto now = SteadyClock::now();\n for (const auto &[id, entry] : bucket) {\n if (expired(entry, now)) uids.push_back(id);\n }\n }\n if (!uids.empty()) {\n for (uint32_t i = 0; i < lockManager_.numBuckets(); ++i) {\n auto lock = lockManager_.lock_at(i);\n auto &bucket = buckets_[i];\n auto now = SteadyClock::now();\n for (auto id : uids) {\n auto it = bucket.find(id);\n if (expired(it->second, now)) bucket.erase(it);\n }\n }\n }\n }\n\n private:\n struct Entry {\n std::optional attr;\n SteadyTime setTs;\n };\n\n bool expired(const Entry &entry, SteadyTime now) const {\n auto timeout = entry.attr ? cfg_.exist_ttl().asUs() : cfg_.inexist_ttl().asUs();\n return now - entry.setTs >= timeout;\n }\n\n using Bucket = robin_hood::unordered_node_map;\n\n const Config &cfg_;\n UniqueLockManager lockManager_;\n std::vector buckets_;\n};\n} // namespace hf3fs::core\n"], ["/3FS/src/common/app/OnePhaseApplication.h", "#pragma once\n\n#include \n\n#include \"AppInfo.h\"\n#include \"ApplicationBase.h\"\n#include \"Utils.h\"\n#include \"common/logging/LogInit.h\"\n#include \"common/net/Server.h\"\n#include \"common/net/ib/IBDevice.h\"\n#include \"common/utils/LogCommands.h\"\n#include \"common/utils/SysResource.h\"\n\nDECLARE_string(app_cfg);\nDECLARE_bool(dump_default_app_cfg);\n\nDECLARE_string(cfg);\nDECLARE_bool(dump_cfg);\nDECLARE_bool(dump_default_cfg);\n\nnamespace hf3fs {\ntemplate \nrequires requires {\n typename T::Config;\n std::string_view(T::kName);\n}\nclass OnePhaseApplication : public ApplicationBase {\n public:\n class CommonConfig : public ConfigBase {\n CONFIG_ITEM(cluster_id, \"\");\n CONFIG_OBJ(log, logging::LogConfig);\n CONFIG_OBJ(monitor, monitor::Monitor::Config);\n CONFIG_OBJ(ib_devices, net::IBDevice::Config);\n };\n\n class Config : public ConfigBase {\n public:\n CONFIG_OBJ(common, CommonConfig);\n CONFIG_OBJ(server, typename T::Config);\n };\n\n struct AppConfig : public ConfigBase {\n CONFIG_ITEM(node_id, 0);\n CONFIG_ITEM(allow_empty_node_id, true);\n };\n\n OnePhaseApplication(AppConfig &appConfig, Config &config)\n : appConfig_(appConfig),\n config_(config) {}\n\n static OnePhaseApplication &instance() {\n static AppConfig appConfig;\n static Config config;\n static OnePhaseApplication app(appConfig, config);\n return app;\n }\n\n Result parseFlags(int *argc, char ***argv) final {\n static constexpr std::string_view appConfigPrefix = \"--app_config.\";\n static constexpr std::string_view configPrefix = \"--config.\";\n\n RETURN_ON_ERROR(ApplicationBase::parseFlags(appConfigPrefix, argc, argv, appConfigFlags_));\n RETURN_ON_ERROR(ApplicationBase::parseFlags(configPrefix, argc, argv, configFlags_));\n return Void{};\n }\n\n Result initApplication() final {\n if (!FLAGS_app_cfg.empty()) {\n app_detail::initConfigFromFile(appConfig_, FLAGS_app_cfg, FLAGS_dump_default_app_cfg, appConfigFlags_);\n }\n XLOGF_IF(FATAL, !appConfig_.allow_empty_node_id() && appConfig_.node_id() == 0, \"node_id is not allowed to be 0\");\n\n if (!FLAGS_cfg.empty()) {\n app_detail::initConfigFromFile(config_, FLAGS_cfg, FLAGS_dump_default_cfg, configFlags_);\n }\n\n if (FLAGS_dump_cfg) {\n std::cout << config_.toString() << std::endl;\n exit(0);\n }\n\n // init basic components\n auto ibResult = net::IBManager::start(config_.common().ib_devices());\n XLOGF_IF(FATAL, !ibResult, \"Failed to start IBManager: {}\", ibResult.error());\n\n auto logConfigStr = logging::generateLogConfig(config_.common().log(), String(T::kName));\n XLOGF(INFO, \"LogConfig: {}\", logConfigStr);\n logging::initOrDie(logConfigStr);\n XLOGF(INFO, \"{}\", VersionInfo::full());\n XLOGF(INFO, \"Full AppConfig:\\n{}\", config_.toString());\n XLOGF(INFO, \"Full Config:\\n{}\", config_.toString());\n\n XLOGF(INFO, \"Init waiter singleton {}\", fmt::ptr(&net::Waiter::instance()));\n\n auto monitorResult = monitor::Monitor::start(config_.common().monitor());\n XLOGF_IF(FATAL, !monitorResult, \"Parse config file from flags failed: {}\", monitorResult.error());\n\n // init server and node info.\n server_ = std::make_unique(config_.server());\n auto setupResult = server_->setup();\n XLOGF_IF(FATAL, !setupResult, \"Setup server failed: {}\", setupResult.error());\n\n auto hostnameResult = SysResource::hostname(/*physicalMachineName=*/true);\n XLOGF_IF(FATAL, !hostnameResult, \"Get hostname failed: {}\", hostnameResult.error());\n\n auto podnameResult = SysResource::hostname(/*physicalMachineName=*/false);\n XLOGF_IF(FATAL, !podnameResult, \"Get podname failed: {}\", podnameResult.error());\n\n info_.nodeId = flat::NodeId(appConfig_.node_id());\n info_.clusterId = config_.common().cluster_id();\n info_.hostname = *hostnameResult;\n info_.podname = *podnameResult;\n info_.pid = SysResource::pid();\n info_.releaseVersion = flat::ReleaseVersion::fromVersionInfo();\n for (auto &group : server_->groups()) {\n info_.serviceGroups.emplace_back(group->serviceNameList(), group->addressList());\n }\n XLOGF(INFO, \"{}\", server_->describe());\n\n // 5. start server.\n auto startResult = server_->start(info_);\n XLOGF_IF(FATAL, !startResult, \"Start server failed: {}\", startResult.error());\n\n return Void{};\n }\n\n config::IConfig *getConfig() final { return &config_; }\n\n const flat::AppInfo *info() const final { return &info_; }\n\n void stop() final { stopAndJoin(server_.get()); }\n\n private:\n OnePhaseApplication() = default;\n\n ConfigFlags appConfigFlags_;\n ConfigFlags configFlags_;\n\n AppConfig &appConfig_;\n Config &config_;\n flat::AppInfo info_;\n std::unique_ptr server_;\n};\n\n} // namespace hf3fs\n"], ["/3FS/src/common/net/ThreadPoolGroup.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/utils/CPUExecutorGroup.h\"\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/ExecutorStatsReporter.h\"\n\nnamespace hf3fs::net {\n\nclass ThreadPoolGroup {\n public:\n struct Config : public ConfigBase {\n CONFIG_ITEM(num_proc_threads, 2ul);\n CONFIG_ITEM(num_io_threads, 2ul);\n CONFIG_ITEM(num_bg_threads, 2ul);\n CONFIG_ITEM(num_connect_threads, 2ul);\n CONFIG_ITEM(collect_stats, false);\n CONFIG_ITEM(enable_work_stealing, false); // deprecated\n CONFIG_ITEM(proc_thread_pool_stratetry, CPUExecutorGroup::ExecutorStrategy::SHARED_QUEUE);\n CONFIG_ITEM(io_thread_pool_stratetry, CPUExecutorGroup::ExecutorStrategy::SHARED_QUEUE);\n CONFIG_ITEM(bg_thread_pool_stratetry, CPUExecutorGroup::ExecutorStrategy::SHARED_QUEUE);\n };\n\n ThreadPoolGroup(const std::string &name, const Config &config)\n : fullname_(fmt::format(\"{}@{}\", name, fmt::ptr(&config))),\n startStacktrace_(folly::symbolizer::getStackTraceStr()),\n procThreadPool_(config.num_proc_threads(), name + \"Proc\", config.proc_thread_pool_stratetry()),\n ioThreadPool_(config.num_io_threads(), name + \"IO\", config.io_thread_pool_stratetry()),\n bgThreadPool_(config.num_bg_threads(), name + \"BG\", config.bg_thread_pool_stratetry()),\n connThreadPool_(config.num_connect_threads(),\n config.num_connect_threads(),\n std::make_shared(name + \"Conn\")),\n procThreadPoolReporter_(procThreadPool_),\n ioThreadPoolReporter_(ioThreadPool_),\n bgThreadPoolReporter_(bgThreadPool_),\n connThreadPoolReporter_(connThreadPool_),\n stopping_(false) {\n if (config.collect_stats()) {\n future_ = co_withCancellation(cancel_.getToken(), collectStatsPeriodically())\n .scheduleOn(&bgThreadPool_.randomPick())\n .start();\n }\n }\n\n ~ThreadPoolGroup() {\n if (!stopping_) {\n XLOGF(WARN, \"Thread pool group '{}' not stopped before destructed, created by {}\", fullname_, startStacktrace_);\n stopAndJoin();\n }\n }\n\n auto &procThreadPool() { return procThreadPool_; }\n auto &ioThreadPool() { return ioThreadPool_; }\n auto &bgThreadPool() { return bgThreadPool_; }\n auto &connThreadPool() { return connThreadPool_; }\n\n void stopAndJoin();\n\n private:\n CoTask collectStatsPeriodically();\n\n private:\n ConstructLog<\"net::ThreadPoolGroup\"> constructLog_;\n std::string fullname_;\n std::string startStacktrace_;\n CPUExecutorGroup procThreadPool_;\n CPUExecutorGroup ioThreadPool_;\n CPUExecutorGroup bgThreadPool_;\n folly::IOThreadPoolExecutor connThreadPool_;\n ExecutorStatsReporter procThreadPoolReporter_;\n ExecutorStatsReporter ioThreadPoolReporter_;\n ExecutorStatsReporter bgThreadPoolReporter_;\n ExecutorStatsReporter connThreadPoolReporter_;\n folly::CancellationSource cancel_;\n folly::SemiFuture future_;\n std::atomic_bool stopping_;\n};\n\n} // namespace hf3fs::net\n"], ["/3FS/src/common/net/Server.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/app/AppInfo.h\"\n#include \"common/net/ServiceGroup.h\"\n#include \"common/net/ThreadPoolGroup.h\"\n#include \"common/serde/ClientContext.h\"\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/Result.h\"\n\nnamespace hf3fs::net {\n\nclass Server {\n public:\n static constexpr auto kName = \"Server\";\n\n struct Config : public ConfigBase {\n CONFIG_OBJ(thread_pool, ThreadPoolGroup::Config);\n CONFIG_OBJ(independent_thread_pool, ThreadPoolGroup::Config);\n CONFIG_OBJ_ARRAY(groups, ServiceGroup::Config, 4);\n };\n\n Server(const Config &config);\n virtual ~Server() { stopAndJoin(); }\n\n // get service groups.\n auto &groups() { return groups_; }\n auto &groups() const { return groups_; }\n\n auto serdeCtxCreator() {\n return [this](Address addr) { return serde::ClientContext(groups_.front()->ioWorker(), addr, options_); };\n }\n\n // add service into group.\n template \n Result addSerdeService(std::unique_ptr &&obj, bool strict = false) {\n for (auto &group : groups_) {\n if (group->serviceNameList().contains(std::string{Service::kServiceName})) {\n return group->addSerdeService(std::move(obj));\n }\n }\n if (strict) {\n return makeError(RPCCode::kInvalidServiceName);\n }\n return groups_.front()->addSerdeService(std::move(obj));\n }\n\n // setup the server.\n Result setup();\n\n // start the server.\n Result start(const flat::AppInfo &info = {});\n\n // stop the server.\n void stopAndJoin();\n\n // set processor frozen.\n void setFrozen(bool frozen = true);\n\n // get the primary thread pool group.\n auto &tpg() { return tpg_; }\n\n // get the app info.\n const auto &appInfo() const { return appInfo_; }\n\n // describe the server.\n std::string describe() const;\n\n std::vector getServiceGroupInfos() const;\n\n protected:\n // call it before start.\n virtual Result beforeStart() { return Void{}; }\n\n // call it after start.\n virtual Result afterStart() { return Void{}; }\n\n // call it before stop.\n virtual Result beforeStop() { return Void{}; }\n\n // call it after stop.\n virtual Result afterStop() { return Void{}; }\n\n private:\n ConstructLog<\"net::Server\"> constructLog_;\n const Config &config_;\n ThreadPoolGroup tpg_;\n ThreadPoolGroup independentTpg_;\n std::vector> groups_;\n flat::AppInfo appInfo_;\n std::atomic_flag stopped_;\n folly::atomic_shared_ptr options_{std::make_shared()};\n};\n\n} // namespace hf3fs::net\n"], ["/3FS/src/common/net/sync/Client.h", "#pragma once\n\n#include \"common/net/sync/ConnectionPool.h\"\n#include \"common/serde/ClientContext.h\"\n\nnamespace hf3fs::net::sync {\n\nclass Client {\n public:\n struct Config : public ConfigBase {\n CONFIG_HOT_UPDATED_ITEM(default_timeout, kClientRequestDefaultTimeout);\n CONFIG_HOT_UPDATED_ITEM(default_send_retry_times, kDefaultMaxRetryTimes, ConfigCheckers::checkPositive);\n CONFIG_HOT_UPDATED_ITEM(default_compression_level, 0u);\n CONFIG_HOT_UPDATED_ITEM(default_compression_threshold, 128_KB);\n CONFIG_OBJ(connection_pool, ConnectionPool::Config);\n };\n\n explicit Client(const Config &config)\n : config_(config),\n connectionPool_(config_.connection_pool()),\n clientConfigGuard_(config_.addCallbackGuard([&] { updateDefaultOptions(); })) {\n updateDefaultOptions();\n }\n\n auto serdeCtx(Address serverAddr) { return serde::ClientContext(connectionPool_, serverAddr, options_); }\n\n protected:\n void updateDefaultOptions() {\n auto options = std::make_shared();\n options->timeout = config_.default_timeout();\n options->sendRetryTimes = config_.default_send_retry_times();\n options->compression = {config_.default_compression_level(), config_.default_compression_threshold()};\n options_ = std::move(options);\n }\n\n private:\n const Config &config_;\n ConnectionPool connectionPool_;\n std::unique_ptr clientConfigGuard_;\n folly::atomic_shared_ptr options_{std::make_shared()};\n};\n\n} // namespace hf3fs::net::sync\n"], ["/3FS/src/client/cli/admin/FileWrapper.h", "#pragma once\n\n#include \n#include \n#define OPENSSL_SUPPRESS_DEPRECATED\n#include \n#include \n#include \n\n#include \"client/cli/admin/AdminEnv.h\"\n#include \"client/cli/admin/Layout.h\"\n#include \"client/cli/common/Dispatcher.h\"\n#include \"client/cli/common/Utils.h\"\n#include \"client/storage/StorageClient.h\"\n#include \"client/storage/TargetSelection.h\"\n#include \"common/serde/Serde.h\"\n#include \"common/utils/Result.h\"\n#include \"fbs/meta/Common.h\"\n#include \"fbs/storage/Common.h\"\n\nnamespace hf3fs::client::cli {\n\nstruct Block {\n SERDE_STRUCT_FIELD(chainId, storage::ChainId{});\n SERDE_STRUCT_FIELD(chunkId, storage::ChunkId{});\n SERDE_STRUCT_FIELD(offset, uint64_t{});\n SERDE_STRUCT_FIELD(length, uint64_t{});\n};\n\nclass FileWrapper {\n public:\n FileWrapper(AdminEnv &env)\n : env_(env) {}\n\n auto &file() { return inode_.asFile(); }\n auto &file() const { return inode_.asFile(); }\n auto length() const { return file().length; }\n\n auto truncate(size_t end) { return env_.metaClientGetter()->truncate(env_.userInfo, inode_.id, end); }\n auto sync() { return env_.metaClientGetter()->sync(env_.userInfo, inode_.id, false, true, std::nullopt); }\n\n Result> prepareBlocks(size_t offset, size_t end, const flat::RoutingInfo &routingInfo);\n Result replicasNum();\n Result showChunks(size_t offset, size_t length);\n\n CoTryTask readFile(\n std::ostream &out,\n size_t length,\n size_t offset,\n bool checksum = true,\n bool hex = false,\n storage::client::TargetSelectionMode mode = storage::client::TargetSelectionMode::Default,\n MD5_CTX *md5 = nullptr,\n bool fillZero = false,\n bool verbose = false,\n uint32_t targetIndex = 0);\n\n static CoTryTask readFile(\n AdminEnv &env,\n std::ostream &out,\n const std::vector &blocks,\n bool checksum = true,\n bool hex = false,\n storage::client::TargetSelectionMode mode = storage::client::TargetSelectionMode::Default,\n MD5_CTX *md5 = nullptr,\n bool fillZero = false,\n bool verbose = false,\n uint32_t targetIndex = 0);\n\n CoTryTask writeFile(std::istream &in,\n size_t length,\n size_t offset,\n Duration timeout,\n bool syncAfterWrite = true);\n\n static CoTryTask openOrCreateFile(AdminEnv &env, const Path &src, bool createIsMissing = false);\n\n private:\n AdminEnv &env_;\n SERDE_CLASS_FIELD(inode, meta::Inode{});\n};\n\n} // namespace hf3fs::client::cli\n"], ["/3FS/src/common/utils/LockManager.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/FairSharedMutex.h\"\n#include \"common/utils/RobinHood.h\"\n\nnamespace hf3fs {\n\ntemplate \ninline std::string hashKeyToString(const Hash &) noexcept {\n return \"\";\n}\n\ntemplate \nstd::string hashKeyToString(const Hash &h, const T &t, const Ts &...ts) {\n if (sizeof...(ts) == 0) return fmt::format(\"{}#{:#x}\", t, h);\n return fmt::format(\"{}/{}\", t, hashKeyToString(h, ts...));\n}\n\ntemplate \nclass LockManager {\n public:\n LockManager(uint32_t numBuckets = 4099u)\n : numBuckets_(numBuckets),\n mutexes_(std::make_unique(numBuckets)),\n owners_(numBuckets) {\n for (auto &owner : owners_) owner = std::make_shared(\"(unknown)\");\n }\n\n auto lock(auto &&...args) { return std::unique_lock{mutexes_[idx(args...)]}; }\n auto try_lock(auto &&...args) { return std::unique_lock{mutexes_[idx(args...)], std::try_to_lock}; }\n\n auto lock_shared(auto &&...args) { return std::shared_lock{mutexes_[idx(args...)]}; }\n auto try_lock_shared(auto &&...args) { return std::shared_lock{mutexes_[idx(args...)], std::try_to_lock}; }\n\n auto co_scoped_lock(auto &&...args) { return mutexes_[idx(args...)].co_scoped_lock(); }\n\n CoTask> co_scoped_lock_log_owner(auto &&...args) {\n auto index = idx(args...);\n auto &mutex = mutexes_[index];\n auto &owner = owners_[index];\n\n std::unique_lock lock{mutex, std::try_to_lock};\n\n if (!lock) {\n XLOGF(DBG3, \"Key {} is waiting on mutex #{} ownerd by {}\", hashKeyToString(index, args...), index, *owner.load());\n auto waitLock = co_await mutex.co_scoped_lock();\n lock.swap(waitLock);\n XLOGF(DBG3, \"Key {} just got a lock on mutex #{}\", hashKeyToString(index, args...), index);\n }\n\n if (XLOG_IS_ON(DBG3)) owner = std::make_shared(hashKeyToString(index, args...));\n\n co_return lock;\n }\n\n auto lock_at(uint64_t index) { return std::unique_lock{mutexes_[index]}; }\n auto try_lock_at(uint64_t index) { return std::unique_lock{mutexes_[index], std::try_to_lock}; }\n\n auto lock_shared_at(uint64_t index) { return std::shared_lock{mutexes_[index]}; }\n auto try_lock_shared_at(uint64_t index) { return std::shared_lock{mutexes_[index], std::try_to_lock}; }\n\n auto co_scoped_lock_at(uint64_t index) { return mutexes_[index].co_scoped_lock(); }\n\n uint64_t idx(auto &&...args) const {\n if constexpr (sizeof...(args) == 0) {\n return 0;\n } else {\n return folly::hash::hash_combine(args...) % numBuckets_;\n }\n }\n\n uint32_t numBuckets() const { return numBuckets_; }\n\n private:\n uint32_t numBuckets_{};\n std::unique_ptr mutexes_;\n std::vector> owners_;\n};\n\nusing UniqueLockManager = LockManager;\nusing SharedLockManager = LockManager;\nusing CoUniqueLockManager = LockManager;\n\n} // namespace hf3fs\n"], ["/3FS/src/common/net/RDMAControl.h", "#pragma once\n\n#include \"common/serde/CallContext.h\"\n#include \"common/serde/Service.h\"\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/Semaphore.h\"\n\nnamespace hf3fs::net {\n\nstruct RDMATransmissionReq {\n SERDE_STRUCT_FIELD(uuid, size_t{});\n};\n\nstruct RDMATransmissionRsp {\n SERDE_STRUCT_FIELD(dummy, Void{});\n};\n\nSERDE_SERVICE(RDMAControl, 10) { SERDE_SERVICE_METHOD(apply, 1, RDMATransmissionReq, RDMATransmissionRsp); };\n\nclass RDMATransmissionLimiter {\n public:\n RDMATransmissionLimiter(uint32_t maxConcurrentTransmission)\n : semaphore_(maxConcurrentTransmission) {}\n\n CoTask co_wait();\n\n void signal(Duration latency);\n\n void updateMaxConcurrentTransmission(uint32_t value) { semaphore_.changeUsableTokens(value); }\n\n private:\n Semaphore semaphore_;\n std::atomic current_{};\n};\nusing RDMATransmissionLimiterPtr = std::shared_ptr;\n\nclass RDMAControlImpl : public serde::ServiceWrapper {\n public:\n class Config : public ConfigBase {\n CONFIG_HOT_UPDATED_ITEM(max_concurrent_transmission, 64u);\n };\n RDMAControlImpl(const Config &config)\n : config_(config),\n limiter_(std::make_shared(config_.max_concurrent_transmission())),\n guard_(config_.addCallbackGuard(\n [&] { limiter_->updateMaxConcurrentTransmission(config_.max_concurrent_transmission()); })) {}\n\n CoTryTask apply(serde::CallContext &, const RDMATransmissionReq &req);\n\n private:\n const Config &config_;\n RDMATransmissionLimiterPtr limiter_;\n std::unique_ptr guard_;\n};\n\n} // namespace hf3fs::net\n"], ["/3FS/src/fdb/FDB.h", "#pragma once\n\n#include \n#include \n#include \n#include \n\n#include \"common/kv/ITransaction.h\"\n#include \"common/utils/String.h\"\n#include \"foundationdb/fdb_c_options.g.h\"\n#include \"foundationdb/fdb_c_types.h\"\n\n#define FDB_API_VERSION 710\n#include \n\nnamespace hf3fs::kv {\n\nclass FDBKVEngine;\n\nnamespace fdb {\n\nusing folly::coro::Task;\nusing KeyValue = IReadOnlyTransaction::KeyValue;\n\n// Structs for returned values.\nstruct KeyRange {\n String beginKey;\n String endKey;\n};\n\n// Structs for parameters.\nstruct KeyRangeView {\n std::string_view beginKey;\n std::string_view endKey;\n};\n\nstruct KeySelector {\n std::string_view key; // Find the last item less than key\n bool orEqual = true; // (or equal to key, if this is true)\n int offset = 0; // and then move forward this many items (or backward if negative)\n\n KeySelector() = default;\n KeySelector(std::string_view key, bool orEqual, int offset)\n : key(std::move(key)),\n orEqual(orEqual),\n offset(offset) {}\n};\n\nstruct GetRangeLimits {\n std::optional rows;\n std::optional bytes;\n\n explicit GetRangeLimits(std::optional r = {}, std::optional b = {})\n : rows(r),\n bytes(b) {}\n};\n\ntemplate \nclass Result {\n public:\n fdb_error_t error() const { return error_; };\n V &value() { return value_; }\n const V &value() const { return value_; }\n\n protected:\n friend class DB;\n friend class Transaction;\n\n static Task toTask(FDBFuture *f);\n void extractValue();\n\n protected:\n struct FDBFutureDeleter {\n constexpr FDBFutureDeleter() noexcept = default;\n void operator()(FDBFuture *future) const { future ? fdb_future_destroy(future) : void(); }\n };\n std::unique_ptr future_;\n fdb_error_t error_ = 0;\n V value_{};\n};\n\nclass Int64Result : public Result {};\nclass KeyResult : public Result {};\nclass ValueResult : public Result> {};\nclass KeyArrayResult : public Result> {};\nclass StringArrayResult : public Result> {};\nclass KeyValueArrayResult : public Result, bool>> {};\nclass KeyRangeArrayResult : public Result> {};\nstruct EmptyValue {};\nclass EmptyResult : public Result {};\n\nclass DB {\n public:\n static fdb_error_t selectAPIVersion(int version);\n static std::string_view errorMsg(fdb_error_t code);\n static bool evaluatePredicate(int predicate_test, fdb_error_t code);\n\n // network\n static fdb_error_t setNetworkOption(FDBNetworkOption option, std::string_view value = {});\n static fdb_error_t setupNetwork();\n static fdb_error_t runNetwork();\n static fdb_error_t stopNetwork();\n\n public:\n DB() = default;\n explicit DB(const String &clusterFilePath, bool readonly)\n : readonly_(readonly) {\n auto path = clusterFilePath.empty() ? nullptr : clusterFilePath.c_str();\n FDBDatabase *db;\n error_ = fdb_create_database(path, &db);\n if (error_ == 0) {\n db_.reset(db);\n }\n }\n\n fdb_error_t error() const { return error_; }\n explicit operator bool() const { return error() == 0; }\n operator FDBDatabase *() const { return db_.get(); }\n\n fdb_error_t setOption(FDBDatabaseOption option, std::string_view value = {});\n\n Task rebootWorker(std::string_view address, bool check = false, int duration = 0);\n Task forceRecoveryWithDataLoss(std::string_view dcid);\n Task createSnapshot(std::string_view uid, std::string_view snapCommand);\n Task purgeBlobGranules(const KeyRangeView &range, int64_t purgeVersion, fdb_bool_t force);\n Task waitPurgeGranulesComplete(std::string_view purgeKey);\n\n bool readonly() const { return readonly_; }\n\n private:\n friend class hf3fs::kv::FDBKVEngine;\n\n struct FDBDatabaseDeleter {\n constexpr FDBDatabaseDeleter() noexcept = default;\n void operator()(FDBDatabase *db) const { db ? fdb_database_destroy(db) : void(); }\n };\n std::unique_ptr db_;\n bool readonly_ = false;\n fdb_error_t error_ = 1;\n};\n\nclass Transaction final {\n public:\n Transaction(DB &db)\n : readonly_(db.readonly()) {\n FDBTransaction *tr;\n error_ = fdb_database_create_transaction(db, &tr);\n if (error_ == 0) {\n tr_.reset(tr);\n }\n }\n\n fdb_error_t error() const { return error_; }\n explicit operator bool() const { return error_ == 0 && tr_; }\n\n fdb_error_t setOption(FDBTransactionOption option, std::string_view value = {});\n\n // Read transaction\n void setReadVersion(int64_t version);\n Task getReadVersion();\n\n Task get(std::string_view key, fdb_bool_t snapshot = false);\n Task getKey(const KeySelector &selector, fdb_bool_t snapshot = false);\n Task watch(std::string_view key);\n\n Task getAddressesForKey(std::string_view key);\n Task getRange(const KeySelector &begin,\n const KeySelector &end,\n GetRangeLimits limits = GetRangeLimits(),\n int iteration = 0,\n bool snapshot = false,\n bool reverse = false,\n FDBStreamingMode streamingMode = FDB_STREAMING_MODE_SERIAL);\n\n Task getEstimatedRangeSizeBytes(const KeyRangeView &range);\n Task getRangeSplitPoints(const KeyRangeView &range, int64_t chunkSize);\n\n Task onError(fdb_error_t err);\n\n void cancel();\n void reset();\n\n // Write transaction\n fdb_error_t addConflictRange(const KeyRangeView &range, FDBConflictRangeType type);\n\n void atomicOp(std::string_view key, std::string_view param, FDBMutationType operationType);\n void set(std::string_view key, std::string_view value);\n void clear(std::string_view key);\n void clearRange(const KeyRangeView &range);\n\n Task commit();\n fdb_error_t getCommittedVersion(int64_t *outVersion);\n Task getApproximateSize();\n Task getVersionstamp();\n\n private:\n struct FDBTransactionDeleter {\n constexpr FDBTransactionDeleter() noexcept = default;\n void operator()(FDBTransaction *tr) const { tr ? fdb_transaction_destroy(tr) : void(); }\n };\n std::unique_ptr tr_;\n bool readonly_ = false;\n fdb_error_t error_ = 1;\n};\n} // namespace fdb\n} // namespace hf3fs::kv\n"], ["/3FS/src/monitor_collector/service/MonitorCollectorService.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"common/monitor/Monitor.h\"\n#include \"common/serde/Service.h\"\n#include \"common/utils/ConfigBase.h\"\n#include \"fbs/monitor_collector/MonitorCollectorService.h\"\n\nnamespace hf3fs::monitor {\nclass MonitorCollectorOperator;\nclass MonitorCollectorService : public serde::ServiceWrapper {\n public:\n class Config : public ConfigBase {\n CONFIG_OBJ(reporter, hf3fs::monitor::Monitor::ReporterConfig, [](hf3fs::monitor::Monitor::ReporterConfig &c) {\n c.set_type(\"clickhouse\");\n });\n CONFIG_ITEM(conn_threads, 32);\n CONFIG_ITEM(queue_capacity, 204800);\n CONFIG_ITEM(batch_commit_size, 4096);\n CONFIG_ITEM(blacklisted_metric_names, std::set{});\n };\n\n MonitorCollectorService(MonitorCollectorOperator &monitorCollectorOperator)\n : monitorCollectorOperator_(monitorCollectorOperator) {}\n\n CoTryTask write(serde::CallContext &ctx, std::vector &samples);\n\n private:\n MonitorCollectorOperator &monitorCollectorOperator_;\n};\n\n} // namespace hf3fs::monitor\n"], ["/3FS/src/common/kv/mem/MemTransaction.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/kv/ITransaction.h\"\n#include \"common/kv/mem/MemKV.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/FaultInjection.h\"\n#include \"common/utils/RandomUtils.h\"\n#include \"common/utils/Result.h\"\n#include \"common/utils/Status.h\"\n#include \"common/utils/String.h\"\n\n#define FAULT_INJECTION_ON_GET(op_name) \\\n do { \\\n if (FAULT_INJECTION()) { \\\n auto delayMs = folly::Random::rand32(10, 100); \\\n auto errCode = \\\n hf3fs::RandomUtils::randomSelect(std::vector{TransactionCode::kThrottled, TransactionCode::kTooOld}); \\\n XLOGF(WARN, \"Inject fault on \" #op_name \", errCode: {}, delayMs: {}.\", errCode, delayMs); \\\n co_await folly::coro::sleep(std::chrono::milliseconds(delayMs)); \\\n co_return makeError(errCode, \"Inject fault on \" #op_name); \\\n } \\\n } while (0)\n\n#define FAULT_INJECTION_ON_COMMIT(db_name, injectMaybeCommitted) \\\n do { \\\n if (FAULT_INJECTION()) { \\\n auto delayMs = folly::Random::rand32(10, 100); \\\n auto errCode = hf3fs::RandomUtils::randomSelect( \\\n std::vector{TransactionCode::kConflict, TransactionCode::kTooOld, TransactionCode::kMaybeCommitted}); \\\n XLOGF(WARN, \"Inject fault on commit, errCode: {}, delayMs: {}.\", errCode, delayMs); \\\n if (errCode == TransactionCode::kMaybeCommitted && folly::Random::oneIn(2)) { \\\n injectMaybeCommitted = true; \\\n XLOGF(WARN, \"Inject maybeCommitted on commit, commit transaction in \" #db_name \".\"); \\\n } else { \\\n co_return makeError(errCode, \"Inject fault on commit.\"); \\\n } \\\n } \\\n } while (0)\n\nnamespace hf3fs::kv {\n\nclass MemTransaction : public IReadWriteTransaction {\n public:\n MemTransaction(mem::MemKV &mem)\n : mem_(mem),\n readVersion_(mem.version()) {}\n\n CoTryTask> snapshotGet(std::string_view key) override {\n FAULT_INJECTION_ON_GET(snapshotGet);\n co_return getImpl(key, true);\n }\n\n CoTryTask snapshotGetRange(const KeySelector &begin, const KeySelector &end, int32_t limit) override {\n FAULT_INJECTION_ON_GET(snapshotGetRange);\n co_return getRangeImpl(begin, end, limit, true);\n }\n\n CoTryTask cancel() override {\n std::scoped_lock guard(mutex_);\n canceled_ = true;\n co_return Void{};\n }\n\n CoTryTask addReadConflict(std::string_view key) override {\n std::scoped_lock guard(mutex_);\n if (canceled_) {\n co_return makeError(TransactionCode::kCanceled, \"Canceled transaction!\");\n }\n if (changes_.contains(key)) {\n co_return Void{};\n }\n readKeys_.insert(String(key));\n co_return Void{};\n }\n\n CoTryTask addReadConflictRange(std::string_view begin, std::string_view end) override {\n std::scoped_lock guard(mutex_);\n if (canceled_) {\n co_return makeError(TransactionCode::kCanceled, \"Canceled transaction!\");\n }\n readRanges_.push_back({std::string(begin), std::string(end)});\n co_return Void{};\n }\n\n CoTryTask> get(std::string_view key) override {\n FAULT_INJECTION_ON_GET(get);\n co_return getImpl(key, false);\n }\n\n CoTryTask getRange(const KeySelector &begin, const KeySelector &end, int32_t limit) override {\n FAULT_INJECTION_ON_GET(getRange);\n co_return getRangeImpl(begin, end, limit, false);\n }\n\n CoTryTask set(std::string_view key, std::string_view value) override {\n std::scoped_lock guard(mutex_);\n if (canceled_) {\n co_return makeError(TransactionCode::kCanceled, \"Canceled transaction!\");\n }\n changes_[String(key)] = value;\n co_return Void{};\n }\n\n CoTryTask setVersionstampedKey(std::string_view key, uint32_t offset, std::string_view value) override {\n std::scoped_lock guard(mutex_);\n if (canceled_) {\n co_return makeError(TransactionCode::kCanceled, \"Canceled transaction!\");\n }\n if (offset + sizeof(kv::Versionstamp) > key.size()) {\n co_return makeError(\n StatusCode::kInvalidArg,\n fmt::format(\"setVersionstampedKey: {} + sizeof(kv::Versionstamp) > key.size {}\", offset, key.size()));\n }\n versionstampedChanges_.push_back(\n mem::MemKV::VersionstampedKV::versionstampedKey(std::string(key), offset, std::string(value)));\n co_return Void{};\n }\n\n CoTryTask setVersionstampedValue(std::string_view key, std::string_view value, uint32_t offset) override {\n std::scoped_lock guard(mutex_);\n if (canceled_) {\n co_return makeError(TransactionCode::kCanceled, \"Canceled transaction!\");\n }\n if (offset + sizeof(kv::Versionstamp) > value.size()) {\n co_return makeError(\n StatusCode::kInvalidArg,\n fmt::format(\"setVersionstampedValue: {} + sizeof(kv::Versionstamp) > value.size {}\", offset, value.size()));\n }\n versionstampedChanges_.push_back(\n mem::MemKV::VersionstampedKV::versionstampedValue(std::string(key), std::string(value), offset));\n co_return Void{};\n }\n\n // Check given keys are in transaction's conflict set.\n bool checkConflictSet(const std::vector &readConflict,\n const std::vector &writeConflict,\n bool exactly = false) {\n std::scoped_lock guard(mutex_);\n for (auto &key : readConflict) {\n if (!readKeys_.contains(key)) {\n XLOGF(ERR, \"Read conflict set doesn't contains key {}\", key);\n return false;\n }\n }\n for (auto &key : writeConflict) {\n auto iter = std::find_if(changes_.begin(), changes_.end(), [&](auto &iter) -> bool { return iter.first == key; });\n if (iter == changes_.end()) {\n XLOGF(ERR, \"Write conflict set doesn't contains key {}\", key);\n return false;\n }\n }\n if (!exactly) {\n return true;\n }\n\n // transaction's conflict set should only given keys\n for (auto &key : readKeys_) {\n if (std::find(readConflict.begin(), readConflict.end(), key) == readConflict.end()) {\n XLOGF(ERR, \"Read conflict contains unexpected key {}\", key);\n return false;\n }\n }\n for (auto &change : changes_) {\n if (std::find(writeConflict.begin(), writeConflict.end(), change.first) == writeConflict.end()) {\n XLOGF(ERR, \"Write conflict contains unexpected key {}\", change.first);\n return false;\n }\n }\n return true;\n }\n\n CoTryTask clear(std::string_view key) override {\n std::scoped_lock guard(mutex_);\n if (canceled_) {\n co_return makeError(TransactionCode::kCanceled, \"Canceled transaction!\");\n }\n changes_[String(key)] = std::optional();\n co_return Void{};\n }\n\n CoTryTask commit() override {\n bool injectMaybeCommitted = false;\n FAULT_INJECTION_ON_COMMIT(MemKV, injectMaybeCommitted);\n\n std::scoped_lock guard(mutex_);\n if (canceled_) {\n co_return makeError(TransactionCode::kCanceled, \"Canceled transaction!\");\n }\n\n std::vector>> vec;\n vec.reserve(changes_.size());\n for (auto iter : changes_) {\n vec.emplace_back(iter.first, iter.second);\n }\n auto result = mem_.commit(readVersion(), readKeys_, readRanges_, vec, versionstampedChanges_, writeConflicts_);\n if (UNLIKELY(injectMaybeCommitted)) {\n XLOGF(ERR,\n \"Inject mayebeCommitted error after commit, MemKV commit result is {}.\",\n result.hasError() ? result.error().describe() : \"OK\");\n co_return makeError(TransactionCode::kMaybeCommitted, \"Fault injection commit unknown result.\");\n }\n CO_RETURN_ON_ERROR(result);\n commitVersion_ = *result;\n co_return Void{};\n }\n\n void setReadVersion(int64_t version) override {\n std::scoped_lock guard(mutex_);\n if (version >= 0) {\n readVersion_ = version;\n }\n }\n\n int64_t getCommittedVersion() override {\n std::scoped_lock guard(mutex_);\n return commitVersion_;\n };\n\n void reset() override {\n std::scoped_lock guard(mutex_);\n readVersion_ = -1;\n commitVersion_ = -1;\n canceled_ = false;\n readKeys_.clear();\n readRanges_.clear();\n changes_.clear();\n versionstampedChanges_.clear();\n writeConflicts_.clear();\n }\n\n // check txn1 updated txn2's read set\n static bool checkConflict(MemTransaction &txn1, MemTransaction &txn2) {\n std::scoped_lock guard1(txn1.mutex_);\n std::scoped_lock guard2(txn2.mutex_);\n\n for (auto &change : txn1.changes_) {\n auto &key = change.first;\n if (std::find(txn2.readKeys_.begin(), txn2.readKeys_.end(), key) != txn2.readKeys_.end()) {\n return true;\n }\n for (auto &range : txn2.readRanges_) {\n if (key >= range.first && key < range.second) {\n return true;\n }\n }\n }\n return false;\n }\n\n mem::MemKV &kv() { return mem_; }\n\n private:\n int64_t readVersion() {\n if (readVersion_ < 0) {\n readVersion_ = mem_.version();\n }\n return readVersion_;\n }\n\n Result> getImpl(std::string_view key, bool snapshot) {\n std::scoped_lock guard(mutex_);\n if (canceled_) {\n return makeError(TransactionCode::kCanceled, \"Canceled transaction!\");\n }\n\n if (changes_.count(key)) {\n return changes_.at(String(key));\n }\n if (!snapshot) {\n readKeys_.insert(String(key));\n }\n return mem_.get(key, readVersion());\n }\n\n Result getRangeImpl(const KeySelector &begin, const KeySelector &end, int32_t limit, bool snapshot) {\n std::scoped_lock guard(mutex_);\n if (canceled_) {\n return makeError(TransactionCode::kCanceled, \"Canceled transaction!\");\n }\n // always get all kvs in range\n auto result = mem_.getRange(begin, end, std::numeric_limits::max(), readVersion());\n RETURN_ON_ERROR(result);\n\n auto changeIt = changes_.lower_bound(begin.key);\n if (changeIt != changes_.end() && !begin.inclusive) ++changeIt;\n\n if (changeIt != changes_.end()) {\n std::vector newKvs;\n auto originIt = result->kvs.begin();\n auto originEnded = [&] { return originIt == result->kvs.end(); };\n auto changeEnded = [&] {\n if (changeIt == changes_.end()) return true;\n if (end.inclusive && changeIt->first > end.key) return true;\n if (!end.inclusive && changeIt->first >= end.key) return true;\n if (result->hasMore) {\n assert(!result->kvs.empty());\n if (changeIt->first > result->kvs.back().key) return true;\n }\n return false;\n };\n auto pushChange = [&] {\n if (changeIt->second.has_value()) newKvs.emplace_back(changeIt->first, *changeIt->second);\n };\n for (;;) {\n if (originEnded() || changeEnded()) break;\n if (originIt->key < changeIt->first) {\n newKvs.push_back(*originIt);\n ++originIt;\n } else if (originIt->key > changeIt->first) {\n pushChange();\n ++changeIt;\n } else {\n pushChange();\n ++changeIt;\n ++originIt;\n }\n }\n for (; !originEnded(); ++originIt) {\n newKvs.push_back(*originIt);\n }\n for (; !changeEnded(); ++changeIt) {\n pushChange();\n }\n result->kvs = std::move(newKvs);\n }\n\n if (limit < 1) {\n limit = mem::memKvDefaultLimit;\n }\n if (result->kvs.size() > (size_t)limit) {\n result->kvs = std::vector(&result->kvs[0], &result->kvs[(size_t)limit]);\n result->hasMore = true;\n assert(result->kvs.size() == (size_t)limit);\n }\n\n String rangeBegin = begin.inclusive ? String(begin.key) : TransactionHelper::keyAfter(begin.key);\n String rangeEnd;\n if (result->hasMore) {\n rangeEnd = TransactionHelper::keyAfter(result->kvs.end()[-1].key);\n } else {\n rangeEnd = end.inclusive ? TransactionHelper::keyAfter(end.key) : String(end.key);\n }\n if (!snapshot) {\n readRanges_.push_back({rangeBegin, rangeEnd});\n }\n\n return result;\n }\n\n std::mutex mutex_;\n mem::MemKV &mem_;\n bool canceled_ = false;\n int64_t readVersion_ = -1;\n int64_t commitVersion_ = -1;\n std::unordered_set readKeys_;\n std::vector> readRanges_;\n std::map, std::less<>> changes_;\n std::vector versionstampedChanges_;\n std::set writeConflicts_;\n};\n\n} // namespace hf3fs::kv\n"], ["/3FS/src/storage/store/StorageTarget.h", "#pragma once\n\n#include \n#include \n\n#include \"chunk_engine/src/cxx.rs.h\"\n#include \"common/monitor/Recorder.h\"\n#include \"common/utils/CoLockManager.h\"\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/LockManager.h\"\n#include \"common/utils/Path.h\"\n#include \"storage/aio/BatchReadJob.h\"\n#include \"storage/store/ChunkEngine.h\"\n#include \"storage/store/ChunkStore.h\"\n#include \"storage/store/PhysicalConfig.h\"\n#include \"storage/update/UpdateJob.h\"\n\nnamespace hf3fs::storage {\n\nclass StorageTarget : public enable_shared_from_this {\n protected:\n StorageTarget(const ChunkStore::Config &config,\n GlobalFileStore &globalFileStore,\n uint32_t diskIndex,\n chunk_engine::Engine *engine);\n\n public:\n using Config = ChunkStore::Config;\n\n ~StorageTarget();\n\n // create storage target.\n Result create(const PhysicalConfig &config);\n\n // load storage target.\n Result load(const Path &path);\n\n // add new chunk size.\n Result addChunkSize(const std::vector &sizeList);\n\n // get target id. [guaranteed loaded]\n TargetId targetId() const { return TargetId{targetConfig_.target_id}; }\n\n // get chain id. [guaranteed loaded]\n ChainId chainId() const { return ChainId{targetConfig_.chain_id}; }\n\n // set chain id.\n Result setChainId(ChainId chainId);\n\n // get disk index.\n uint32_t diskIndex() const { return diskIndex_; }\n\n // get target path. [guaranteed loaded]\n Path path() const { return targetConfig_.path; }\n\n // get all chunk metadata\n Result getAllMetadata(ChunkMetaVector &metadataVec);\n Result getAllMetadataMap(std::unordered_map &metas);\n\n // lock chunk.\n auto lockChunk(folly::coro::Baton &baton, const ChunkId &chunk, const std::string &tag) {\n return chunkLocks_.lock(baton, chunk.data(), tag);\n }\n\n // try lock channel.\n auto tryLockChannel(folly::coro::Baton &baton, const std::string &key) { return channelLocks_.tryLock(baton, key); }\n\n // prepare aio read.\n Result aioPrepareRead(AioReadJob &job);\n\n // finish aio read.\n Result aioFinishRead(AioReadJob &job);\n\n // update chunk (write/remove/truncate).\n void updateChunk(UpdateJob &job, folly::CPUThreadPoolExecutor &executor);\n\n // query chunks: the chunk ids in result are in reverse lexicographical order\n Result>> queryChunks(const ChunkIdRange &chunkIdRange);\n\n // query chunk.\n Result queryChunk(const ChunkId &chunkId);\n\n // recycle a batch of chunks. return true if all holes are punched.\n Result punchHole() {\n if (useChunkEngine()) {\n return true;\n } else {\n return chunkStore_.punchHole();\n }\n }\n\n // sync meta kv.\n Result sync() {\n if (useChunkEngine()) {\n return Void{};\n } else {\n return chunkStore_.sync();\n }\n }\n\n // report unrecycled size.\n Result reportUnrecycledSize();\n\n // get used size.\n uint64_t usedSize() const {\n if (useChunkEngine()) {\n return ChunkEngine::chainUsedSize(*engine_, ChainId{targetConfig_.chain_id});\n } else {\n return chunkStore_.usedSize();\n }\n }\n\n // get unused size.\n uint64_t unusedSize() const { return unusedSize_; }\n\n // get all uncommitted chunk ids.\n Result> uncommitted() {\n if (useChunkEngine()) {\n return ChunkEngine::queryUncommittedChunks(*engine_, chainId());\n } else {\n return chunkStore_.uncommitted();\n }\n }\n\n // reset uncommitted chunk to committed state.\n Result resetUncommitted(ChainVer chainVer) {\n if (useChunkEngine()) {\n return ChunkEngine::resetUncommittedChunks(*engine_, chainId(), chainVer);\n } else {\n return chunkStore_.resetUncommitted(chainVer);\n }\n }\n\n // enable or disable emergency recycling.\n void setEmergencyRecycling(bool enable) {\n if (useChunkEngine()) {\n return;\n } else {\n return chunkStore_.setEmergencyRecycling(enable);\n }\n }\n\n // record real read.\n void recordRealRead(uint32_t bytes, Duration latency) const;\n\n // disk monitor tag.\n auto &tag() const { return diskTag_; }\n\n // check alive or not.\n std::weak_ptr aliveWeakPtr() const { return alive_; }\n\n // global serial number.\n auto generationId() const { return generationId_; }\n\n // release self.\n Result release() {\n released_ = true;\n return sync();\n }\n\n // check if chunk engine is used.\n inline bool useChunkEngine() const { return targetConfig_.only_chunk_engine; }\n\n private:\n const Config &config_;\n std::shared_ptr alive_ = std::make_shared();\n uint32_t diskIndex_;\n uint32_t generationId_;\n chunk_engine::Engine *engine_{};\n std::atomic unusedSize_{};\n monitor::TagSet diskTag_;\n monitor::TagSet targetTag_;\n monitor::Recorder::TagRef readCountPerDisk_;\n monitor::Recorder::TagRef readBytesPerDisk_;\n monitor::Recorder::TagRef readSuccBytesPerDisk_;\n monitor::Recorder::TagRef readSuccLatencyPerDisk_;\n monitor::Recorder::TagRef targetUsedSize_;\n monitor::Recorder::TagRef targetReservedSize_;\n monitor::Recorder::TagRef targetUnrecycledSize_;\n PhysicalConfig targetConfig_;\n ChunkStore chunkStore_;\n CoLockManager<> chunkLocks_;\n CoLockManager<> channelLocks_;\n folly::Synchronized, std::mutex> chunkSizeList_;\n bool released_ = false;\n};\n\n} // namespace hf3fs::storage\n"], ["/3FS/src/common/serde/CallContext.h", "#pragma once\n\n#include \"common/net/Transport.h\"\n#include \"common/net/ib/IBSocket.h\"\n#include \"common/serde/MessagePacket.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/Size.h\"\n#include \"common/utils/Tracing.h\"\n#include \"common/utils/VersionInfo.h\"\n\nnamespace hf3fs::serde {\n\nclass CallContext {\n public:\n using MethodType = CoTask (CallContext::*)();\n using OnErrorType = Status (CallContext::*)(Status);\n struct ServiceWrapper {\n using MethodGetter = MethodType (*)(uint16_t);\n MethodGetter getter = &CallContext::invalidServiceId;\n OnErrorType onError = &CallContext::serviceOnError;\n void *object = nullptr;\n std::shared_ptr alive = nullptr;\n };\n\n CallContext(MessagePacket<> &packet, net::TransportPtr tr, ServiceWrapper &service)\n : packet_(packet),\n tr_(std::move(tr)),\n service_(service) {}\n\n const auto &packet() { return packet_; }\n auto &transport() const { return tr_; }\n auto &responseOptions() { return responseOptions_; }\n std::string peer() { return LIKELY(tr_ != nullptr) ? tr_->peerIP().str() : std::string{\"null\"}; }\n\n CoTask handle() {\n auto method = service_.getter(packet_.methodId);\n co_await (this->*method)();\n }\n\n CoTask invalidId() {\n XLOGF(INFO, \"method {}:{} not found!\", packet_.serviceId, packet_.methodId);\n onError(makeError(RPCCode::kInvalidMethodID));\n co_return;\n }\n\n template \n CoTask call() {\n // deserialize payload.\n if (packet_.timestamp) {\n packet_.timestamp->serverWaked = UtcClock::now().time_since_epoch().count();\n }\n typename F::ReqType req;\n auto deserializeResult = serde::deserialize(req, packet_.payload);\n if (UNLIKELY(!deserializeResult)) {\n onDeserializeFailed();\n co_return;\n }\n\n // call method.\n auto obj = reinterpret_cast(service_.object);\n auto result = co_await folly::coro::co_awaitTry((obj->*F::method)(*this, req));\n if (UNLIKELY(result.hasException())) {\n XLOGF(FATAL,\n \"Processor has exception: {}, request {}:{} {}\",\n result.exception().what(),\n packet_.serviceId,\n packet_.methodId,\n serde::toJsonString(req));\n co_return;\n }\n if (packet_.timestamp) {\n packet_.timestamp->serverProcessed = UtcClock::now().time_since_epoch().count();\n }\n makeResponse(result.value());\n co_return;\n }\n\n void onError(folly::Unexpected &&status) {\n makeResponse(Result(makeError((this->*service_.onError)(std::move(status.error())))));\n }\n\n Status serviceOnError(Status status) { return status; }\n\n template \n Status customOnError(Status status) {\n auto obj = reinterpret_cast(service_.object);\n return (obj->*Method)(std::move(status));\n }\n\n void onDeserializeFailed();\n\n tracing::Points &tracingPoints() { return tracingPoints_; }\n\n class RDMATransmission {\n public:\n RDMATransmission(CallContext &ctx, ibv_wr_opcode opcode)\n : ctx_(ctx),\n batch_(ctx_.tr_->ibSocket(), opcode) {}\n\n Result add(const net::RDMARemoteBuf &remoteBuf, net::RDMABuf localBuf) {\n return batch_.add(remoteBuf, localBuf);\n }\n\n CoTask applyTransmission(Duration timeout);\n\n CoTryTask post() { return batch_.post(); }\n\n private:\n CallContext &ctx_;\n net::IBSocket::RDMAReqBatch batch_;\n };\n\n RDMATransmission readTransmission() { return RDMATransmission{*this, IBV_WR_RDMA_READ}; }\n RDMATransmission writeTransmission() { return RDMATransmission{*this, IBV_WR_RDMA_WRITE}; }\n\n private:\n static MethodType invalidServiceId(uint16_t) { return &CallContext::invalidId; }\n\n void makeResponse(const auto &payload) {\n MessagePacket send(payload);\n send.uuid = packet_.uuid;\n send.serviceId = packet_.serviceId;\n send.methodId = packet_.methodId;\n send.flags = 0;\n send.version = packet_.version;\n send.timestamp = packet_.timestamp;\n tr_->send(net::WriteList(net::WriteItem::createMessage(send, responseOptions_)));\n }\n\n private:\n MessagePacket<> &packet_;\n net::TransportPtr tr_;\n ServiceWrapper &service_;\n\n net::CoreRequestOptions responseOptions_;\n tracing::Points tracingPoints_;\n};\n\n} // namespace hf3fs::serde\n"], ["/3FS/src/common/kv/ITransaction.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/Result.h\"\n#include \"common/utils/Status.h\"\n#include \"common/utils/String.h\"\n#include \"common/utils/Transform.h\"\n\nnamespace hf3fs::kv {\n\n// - The metadata version key \"\\xff/metadataVersion\" is a key intended to help layers deal with hot keys. The value of\n// this key is sent to clients along with the read version from the proxy, so a client can read its value without\n// communicating with a storage server. The value of this key can only be set with SetVersionStampValue operations.\n// - fdbdr will always capture changes to this key, regardless of the specified range for the DR.\n// - Restore will set this key right before a restore is complete.\n// - Calling setVersion on a transaction does not include the value of the metadataVersionKey, so a cache of recent\n// version to metadataVersion mappings are kept in the database context. This is useful when caching read versions from\n// one transaction and calling setVersion on a different transaction to avoid waiting for read version there.\nstatic constexpr std::string_view kMetadataVersionKey = \"\\xff/metadataVersion\";\n\n// A versionstamp is a 10 byte, unique, monotonically (but not sequentially) increasing value for each committed\n// transaction. The first 8 bytes are the committed version of the database (serialized in big-endian order). The last\n// 2 bytes are monotonic in the serialization order for transactions (serialized in big-endian order).\nusing Versionstamp = std::array;\nstatic_assert(sizeof(Versionstamp) == 10);\n\nclass IReadOnlyTransaction {\n public:\n virtual ~IReadOnlyTransaction() = default;\n\n virtual void setReadVersion(int64_t version) = 0;\n\n virtual CoTryTask> snapshotGet(std::string_view key) = 0;\n\n virtual CoTryTask> get(std::string_view key) {\n // fallback to snapshotGet by default.\n co_return co_await snapshotGet(key);\n }\n\n struct KeyValue {\n String key;\n String value;\n\n KeyValue(String k, String v)\n : key(std::move(k)),\n value(std::move(v)) {}\n\n KeyValue(std::string_view k, std::string_view v)\n : key(k),\n value(v) {}\n\n std::tuple pair() const { return {key, value}; }\n };\n\n struct KeySelector {\n std::string_view key;\n bool inclusive;\n\n KeySelector(std::string_view k, bool argInclusive)\n : key(k),\n inclusive(argInclusive) {}\n };\n\n struct GetRangeResult : public folly::MoveOnly {\n std::vector kvs;\n bool hasMore;\n\n GetRangeResult(std::vector argKvs, bool argHasMore)\n : kvs(std::move(argKvs)),\n hasMore(argHasMore) {}\n };\n virtual CoTryTask snapshotGetRange(const KeySelector &begin,\n const KeySelector &end,\n int32_t limit) = 0;\n virtual CoTryTask getRange(const KeySelector &begin, const KeySelector &end, int32_t limit) = 0;\n\n virtual CoTryTask cancel() = 0;\n virtual void reset() = 0;\n};\n\nclass IReadWriteTransaction : public IReadOnlyTransaction {\n public:\n ~IReadWriteTransaction() override = default;\n\n // The difference of `snapshotGet` and `get` is the former needs no conflict validation and hence won't cause a\n // read-write transaction fail.\n CoTryTask> get(std::string_view key) override = 0;\n CoTryTask getRange(const KeySelector &begin, const KeySelector &end, int32_t limit) override = 0;\n\n // Add a read conflict key to transaction without performing associated read.\n virtual CoTryTask addReadConflict(std::string_view key) = 0;\n virtual CoTryTask addReadConflictRange(std::string_view begin, std::string_view end) = 0;\n\n virtual CoTryTask set(std::string_view key, std::string_view value) = 0;\n virtual CoTryTask clear(std::string_view key) = 0;\n\n // A versionstamp is a 10 byte, unique, monotonically (but not sequentially) increasing value for each committed\n // transaction. The first 8 bytes are the committed version of the database (serialized in big-endian order). The last\n // 2 bytes are monotonic in the serialization order for transactions (serialized in big-endian order).\n virtual CoTryTask setVersionstampedKey(std::string_view key, uint32_t offset, std::string_view value) = 0;\n virtual CoTryTask setVersionstampedValue(std::string_view key, std::string_view value, uint32_t offset) = 0;\n\n virtual CoTryTask commit() = 0;\n virtual int64_t getCommittedVersion() = 0;\n};\n\nstruct TransactionHelper {\n static bool isTransactionError(const Status &error);\n\n static bool isRetryable(const Status &error, bool allowMaybeCommitted);\n\n static String keyAfter(std::string_view key);\n\n static String prefixListEndKey(std::string_view prefix);\n\n struct ListByPrefixOptions {\n bool snapshot = true;\n bool inclusive = true;\n size_t limit = 0;\n\n ListByPrefixOptions() = default;\n ListByPrefixOptions &withSnapshot(bool v) {\n snapshot = v;\n return *this;\n }\n ListByPrefixOptions &withInclusive(bool v) {\n inclusive = v;\n return *this;\n }\n ListByPrefixOptions &withLimit(size_t v) {\n limit = v;\n return *this;\n }\n };\n\n using KeyValue = IReadOnlyTransaction::KeyValue;\n static CoTryTask> listByPrefix(IReadOnlyTransaction &txn,\n std::string_view prefix,\n ListByPrefixOptions options);\n\n template \n static CoTryTask> listByPrefix(IReadOnlyTransaction &txn,\n std::string_view prefix,\n ListByPrefixOptions options,\n Fn &&unpack) {\n auto listRes = co_await listByPrefix(txn, prefix, options);\n CO_RETURN_ON_ERROR(listRes);\n std::vector res;\n for (auto &[k, v] : *listRes) {\n auto entry = unpack(k, v);\n CO_RETURN_ON_ERROR(entry);\n res.push_back(std::move(*entry));\n }\n co_return res;\n }\n};\n\n} // namespace hf3fs::kv\n"], ["/3FS/src/fdb/FDBRetryStrategy.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/kv/ITransaction.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/Duration.h\"\n#include \"common/utils/Result.h\"\n#include \"common/utils/Status.h\"\n#include \"fdb/FDBTransaction.h\"\n\nnamespace hf3fs::kv {\n\nclass FDBRetryStrategy {\n public:\n static constexpr Duration kMinBackoff = 10_ms; // same with FDB, 0.01s\n\n struct Config {\n Duration maxBackoff = 1_s;\n size_t maxRetryCount = 10;\n bool retryMaybeCommitted = true;\n };\n\n FDBRetryStrategy()\n : FDBRetryStrategy(Config()) {}\n FDBRetryStrategy(Config config)\n : config_(config),\n backoff_(kMinBackoff),\n retry_(0) {}\n\n template \n Result init(Txn *txn) {\n retry_ = 0;\n backoff_ = kMinBackoff;\n\n auto *fdbTransaction = dynamic_cast(txn);\n if (fdbTransaction) {\n uint64_t value = std::chrono::duration_cast(config_.maxBackoff).count();\n auto result = fdbTransaction->setOption(FDBTransactionOption::FDB_TR_OPTION_MAX_RETRY_DELAY,\n std::string_view((char *)&value, sizeof(value)));\n if (result.hasError()) {\n XLOGF(ERR, \"Failed to set option on FDBTransaction, {}\", result.error().describe());\n RETURN_ERROR(result);\n }\n }\n\n return Void{};\n }\n\n template \n CoTryTask onError(Txn *txn, Status error) {\n if (retry_ >= config_.maxRetryCount) {\n XLOGF(ERR, \"Transaction failed after retry {} times, error {}\", retry_, error.describe());\n co_return makeError(std::move(error));\n }\n if (!TransactionHelper::isTransactionError(error)) {\n XLOGF(DBG, \"Not transaction error {}\", error);\n co_return makeError(std::move(error));\n }\n XLOGF(DBG, \"Transaction error {}\", error);\n\n SCOPE_EXIT {\n // update retry and backoff before exit.\n backoff_ = std::min(config_.maxBackoff, Duration(backoff_ * 2));\n retry_++;\n };\n\n auto *fdbTransaction = dynamic_cast(txn);\n if (fdbTransaction) {\n co_return co_await fdbBackoff(fdbTransaction, std::move(error));\n } else {\n co_return co_await defaultBackoff(txn, std::move(error));\n }\n }\n\n CoTryTask fdbBackoff(FDBTransaction *txn, Status error) {\n auto errcode = txn->errcode();\n if (UNLIKELY(!errcode)) {\n XLOGF_IF(CRITICAL,\n error.code() != TransactionCode::kTooOld,\n \"Failed to get FDB errcode, error {}, stacktrace {}\",\n error,\n folly::symbolizer::getStackTraceStr());\n co_return co_await defaultBackoff(txn, std::move(error));\n }\n\n FDBErrorPredicate predict =\n config_.retryMaybeCommitted ? FDB_ERROR_PREDICATE_RETRYABLE : FDB_ERROR_PREDICATE_RETRYABLE_NOT_COMMITTED;\n if (!fdb_error_predicate(predict, errcode)) {\n XLOGF(ERR, \"Transaction error not retryable: {}, errcode {}\", error, errcode);\n co_return makeError(std::move(error));\n }\n\n XLOGF(DBG, \"FDBRetryStrategy backoff by FoundationDB\");\n auto ok = co_await txn->onError(errcode);\n if (!ok) {\n co_return makeError(std::move(error));\n }\n co_return Void{};\n }\n\n template \n CoTryTask defaultBackoff(Txn *txn, Status error) {\n // fallback to our backoff implementation\n if (!TransactionHelper::isRetryable(error, config_.retryMaybeCommitted)) {\n XLOGF(ERR, \"Transaction error not retryable: {}\", error);\n co_return makeError(std::move(error));\n }\n XLOGF(WARN, \"Transaction retryable error: {}\", error);\n\n XLOGF(DBG, \"FDBRetryStrategy backoff transaction {}ms\", backoff_.count());\n txn->reset();\n\n auto duration = Duration(backoff_ / 100 * folly::Random::rand32(80, 120));\n co_await folly::coro::sleep(duration.asUs());\n co_return Void{};\n }\n\n private:\n Config config_;\n Duration backoff_;\n size_t retry_;\n};\n\n} // namespace hf3fs::kv"], ["/3FS/src/core/app/ServerEnv.h", "#pragma once\n\n#include \"common/app/AppInfo.h\"\n#include \"common/kv/IKVEngine.h\"\n#include \"common/utils/CPUExecutorGroup.h\"\n#include \"stubs/common/IStubFactory.h\"\n#include \"stubs/mgmtd/IMgmtdServiceStub.h\"\n\nnamespace hf3fs::core {\nclass ServerEnv {\n public:\n const flat::AppInfo &appInfo() const { return appInfo_; }\n\n void setAppInfo(flat::AppInfo appInfo);\n\n const std::shared_ptr &kvEngine() const { return kvEngine_; }\n\n void setKvEngine(std::shared_ptr engine);\n\n using MgmtdStubFactory = stubs::IStubFactory;\n const std::shared_ptr &mgmtdStubFactory() const { return mgmtdStubFactory_; }\n\n void setMgmtdStubFactory(std::shared_ptr factory);\n\n using UtcTimeGenerator = std::function;\n const UtcTimeGenerator &utcTimeGenerator() const { return utcTimeGenerator_; }\n\n void setUtcTimeGenerator(UtcTimeGenerator generator);\n\n CPUExecutorGroup *backgroundExecutor() const { return backgroundExecutor_; }\n\n void setBackgroundExecutor(CPUExecutorGroup *executor);\n\n using ConfigUpdater = std::function(const String &, const String &)>;\n const ConfigUpdater &configUpdater() const { return configUpdater_; }\n\n void setConfigUpdater(ConfigUpdater updater);\n\n using ConfigValidater = std::function(const String &, const String &)>;\n const ConfigValidater &configValidater() const { return configValidater_; }\n\n void setConfigValidater(ConfigValidater validater);\n\n private:\n flat::AppInfo appInfo_;\n std::shared_ptr kvEngine_;\n std::shared_ptr mgmtdStubFactory_;\n UtcTimeGenerator utcTimeGenerator_ = &UtcClock::now;\n CPUExecutorGroup *backgroundExecutor_ = nullptr;\n ConfigUpdater configUpdater_;\n ConfigValidater configValidater_;\n};\n} // namespace hf3fs::core\n"], ["/3FS/src/common/kv/mem/MemKV.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/kv/ITransaction.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/Result.h\"\n#include \"common/utils/StatusCode.h\"\n#include \"common/utils/String.h\"\n\nnamespace hf3fs::kv::mem {\n\ninline int32_t memKvDefaultLimit = 25;\n\nclass MemKV : public folly::MoveOnly {\n public:\n struct VersionstampedKV {\n std::string key;\n std::string value;\n bool onKey;\n uint32_t offset;\n\n static VersionstampedKV versionstampedKey(std::string key, uint32_t offset, std::string value) {\n return {key, value, true, offset};\n }\n\n static VersionstampedKV versionstampedValue(std::string key, std::string value, uint32_t offset) {\n return {key, value, false, offset};\n }\n };\n\n Result> get(std::string_view key, int64_t readVersion) const {\n std::shared_lock lock(mutex_);\n\n auto it = map_.find(String(key));\n if (it == map_.end()) {\n return std::optional();\n }\n\n auto version_it = it->second.upper_bound(readVersion);\n if (version_it != it->second.begin()) {\n --version_it;\n if (version_it->second.has_value()) {\n return std::make_optional(version_it->second.value());\n }\n }\n return std::optional();\n }\n\n Result getRange(const IReadOnlyTransaction::KeySelector &begin,\n const IReadOnlyTransaction::KeySelector &end,\n int32_t limit,\n int64_t readVersion) const {\n if (limit < 1) {\n limit = memKvDefaultLimit;\n }\n std::shared_lock lock(mutex_);\n\n std::vector kvs;\n\n if (begin.key > end.key || (begin.key == end.key && !(begin.inclusive && end.inclusive))) {\n return IReadOnlyTransaction::GetRangeResult(std::move(kvs), false);\n }\n\n auto begin_it = begin.inclusive ? map_.lower_bound(begin.key) : map_.upper_bound(begin.key);\n auto end_it = end.inclusive ? map_.upper_bound(end.key) : map_.lower_bound(end.key);\n while (begin_it != end_it && kvs.size() < (size_t)limit) {\n auto version_it = begin_it->second.upper_bound(readVersion);\n if (version_it != begin_it->second.begin()) {\n --version_it;\n if (version_it->second.has_value()) {\n kvs.emplace_back(begin_it->first, version_it->second.value());\n }\n }\n ++begin_it;\n }\n\n return IReadOnlyTransaction::GetRangeResult(std::move(kvs), begin_it != end_it);\n }\n\n Result commit(int64_t readVersion,\n const std::unordered_set &readKeys,\n const std::vector> readRanges,\n const std::vector>> changes,\n const std::vector versionstampedChanges,\n const std::set writeConflicts) {\n // if transaction contains no updates, don't need commit.\n if (changes.empty() && versionstampedChanges.empty() && writeConflicts.empty()) {\n return -1; // return a invalid version\n }\n if (readVersion < 0) {\n return makeError(TransactionCode::kFailed, \"MemKV transaction invalid version!\");\n }\n\n std::unique_lock lock(mutex_);\n\n // check conflict\n for (auto &key : readKeys) {\n auto it = map_.find(key);\n if (it != map_.end()) {\n auto version_it = it->second.upper_bound(readVersion);\n if (version_it != it->second.end()) {\n return makeError(TransactionCode::kConflict, \"MemKV transaction conflicts!\");\n }\n }\n }\n for (auto &range : readRanges) {\n auto it = map_.lower_bound(range.first);\n while (it != map_.end() && it->first < range.second) {\n auto version_it = it->second.upper_bound(readVersion);\n if (version_it != it->second.end()) {\n return makeError(TransactionCode::kConflict, \"MemKV transaction conflicts!\");\n }\n it++;\n }\n }\n\n auto version = ++version_;\n uint16_t seq = 0;\n for (auto change : versionstampedChanges) {\n Versionstamp(version, seq++).update(change);\n XLOGF_IF(FATAL, change.onKey && map_.contains(change.key), \"shouldn't happen\");\n map_[change.key][version] = change.value;\n }\n for (auto &change : changes) {\n if (change.second.has_value()) {\n map_[change.first][version] = change.second.value();\n } else {\n map_[change.first][version] = std::nullopt;\n }\n }\n for (const auto &conflict : writeConflicts) {\n if (map_.contains(conflict)) {\n auto value = map_[conflict].rbegin()->second;\n map_[conflict][version] = value;\n } else {\n map_[conflict][version] = std::nullopt;\n }\n }\n return version;\n }\n\n int64_t version() const {\n std::shared_lock lock(mutex_);\n return version_;\n }\n\n void backup() { states_.lock()->push(version()); }\n\n void restore() {\n auto guard = states_.lock();\n auto version = guard->front();\n guard->pop();\n restore(version);\n }\n\n private:\n struct Versionstamp {\n std::array version;\n std::array seq;\n\n Versionstamp(uint64_t version, uint16_t seq)\n : version(folly::bit_cast>(folly::Endian::big64(version))),\n seq(folly::bit_cast>(folly::Endian::big16(seq))) {}\n\n void update(VersionstampedKV &kv) const {\n auto &str = kv.onKey ? kv.key : kv.value;\n auto offset = kv.offset;\n XLOGF_IF(FATAL, offset + 10 > str.size(), \"{} {}\", offset, str.size());\n memcpy(str.data() + offset, (char *)this, 10);\n }\n };\n static_assert(sizeof(Versionstamp) == 10);\n\n void restore(int64_t version) {\n std::unique_lock lock(mutex_);\n version_ = version;\n\n // remove all modification after version\n auto iter = map_.begin();\n while (iter != map_.end()) {\n auto &values = iter->second;\n auto pos = values.lower_bound(version_ + 1);\n if (pos != values.end()) {\n values.erase(pos, values.end());\n }\n if (values.empty()) {\n map_.erase(iter++);\n } else {\n iter++;\n }\n }\n }\n\n void clear() {\n std::unique_lock lock(mutex_);\n map_.clear();\n version_ = 0;\n }\n\n private:\n mutable std::shared_mutex mutex_;\n folly::Synchronized, std::mutex> states_;\n std::map>, std::less<>> map_;\n int64_t version_ = 0;\n};\n\n} // namespace hf3fs::kv::mem\n"], ["/3FS/src/common/utils/CPUExecutorGroup.h", "#pragma once\n\n#include \n\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/ConstructLog.h\"\n\nnamespace hf3fs {\nclass CPUExecutorGroup {\n public:\n enum class ExecutorStrategy {\n SHARED_QUEUE, // fallback to CPUThreadPoolExecutor\n SHARED_NOTHING,\n WORK_STEALING,\n ROUND_ROBIN,\n GROUP_WAITING_4,\n GROUP_WAITING_8,\n };\n\n struct Config : public ConfigBase {\n CONFIG_ITEM(threadCount, 32);\n CONFIG_ITEM(strategy, ExecutorStrategy::ROUND_ROBIN);\n };\n\n CPUExecutorGroup(uint32_t threadCount,\n std::string name,\n ExecutorStrategy executorStrategy = ExecutorStrategy::SHARED_QUEUE);\n\n CPUExecutorGroup(std::string name, const Config &config)\n : CPUExecutorGroup(config.threadCount(), std::move(name), config.strategy()) {}\n\n ~CPUExecutorGroup();\n\n folly::CPUThreadPoolExecutor &get(size_t i) const { return *executors_[i]; };\n\n folly::CPUThreadPoolExecutor &randomPick() const;\n\n folly::CPUThreadPoolExecutor &pickNext() const {\n auto pos = next_.fetch_add(1, std::memory_order_acq_rel);\n return get(pos % size());\n }\n\n folly::CPUThreadPoolExecutor &pickNextFree() const;\n\n size_t size() const { return executors_.size(); }\n\n void join();\n\n auto &getAll() { return executors_; }\n auto &getAll() const { return executors_; }\n\n const std::string &getName() const { return name_; }\n folly::ThreadPoolExecutor::PoolStats getPoolStats() const;\n\n private:\n ConstructLog<\"CPUExecutorGroup\"> constructLog_;\n const std::string name_;\n std::vector> executors_;\n mutable std::atomic next_{0};\n};\n} // namespace hf3fs\n"], ["/3FS/src/common/net/WriteItem.h", "#pragma once\n\n#include \n#include \n#include \n#include \n\n#include \"common/net/Allocator.h\"\n#include \"common/net/MessageHeader.h\"\n#include \"common/net/RequestOptions.h\"\n#include \"common/serde/MessagePacket.h\"\n#include \"common/serde/Serde.h\"\n#include \"common/utils/DownwardBytes.h\"\n#include \"common/utils/ObjectPool.h\"\n#include \"common/utils/ZSTD.h\"\n\nnamespace hf3fs::net {\n\n/*\n * A buffer serialized by serde.\n * +----------+-----------------------------------------+\n * | | buffer to write |\n * | headroom +-------------------------------+---------+\n * | | MessageHeader(checksum, size) | message |\n * +----------+-------------------------------+---------+\n */\nclass SerdeBuffer {\n public:\n // buffer to write, include message header and content.\n uint8_t *buff() { return self() + headroom_; }\n const uint8_t *buff() const { return self() + headroom_; }\n\n // message header, include checksum and size of message content.\n auto &header() { return *reinterpret_cast(buff()); }\n auto &header() const { return *reinterpret_cast(buff()); }\n\n // message serialized by serde.\n uint8_t *rawMsg() { return buff() + kMessageHeaderSize; }\n const uint8_t *rawMsg() const { return buff() + kMessageHeaderSize; }\n\n // length of whole message.\n uint32_t length() const { return kMessageHeaderSize + header().size; }\n // length of whole buffer.\n size_t capacity() const { return capacity_; }\n\n template \n struct Deleter {\n void operator()(SerdeBuffer *buf) { Allocator::deallocate(buf->self(), buf->capacity()); }\n };\n\n template >\n static auto create(const T &packet, const CoreRequestOptions &options) {\n serde::Out> out;\n serde::serialize(packet, out);\n MessageHeader header;\n header.size = out.bytes().size();\n out.bytes().append(&header, sizeof(header));\n out.bytes().reserve(header.size + kMessageHeaderSize + sizeof(SerdeBuffer)); // for headroom.\n\n uint32_t offset;\n uint32_t capacity;\n std::unique_ptr> ptr{\n reinterpret_cast(out.bytes().release(offset, capacity))};\n ptr->headroom_ = offset; // size of headroom.\n ptr->capacity_ = capacity;\n\n if (packet.timestamp.has_value()) {\n auto timestamp = reinterpret_cast(ptr->rawMsg() + ptr->header().size -\n sizeof(hf3fs::serde::Timestamp));\n if (packet.isRequest()) {\n timestamp->clientSerialized = UtcClock::now().time_since_epoch().count();\n } else {\n timestamp->serverSerialized = UtcClock::now().time_since_epoch().count();\n }\n }\n\n auto compress = options.compression.enable(capacity);\n if (compress) {\n auto originalSize = ptr->header().size;\n auto compressedOffset = sizeof(SerdeBuffer) + sizeof(MessageHeader);\n auto compressedBound = ZSTD_compressBound(originalSize);\n auto compressedCapacity = compressedOffset + compressedBound;\n std::unique_ptr> compressed{\n reinterpret_cast(Allocator::allocate(compressedCapacity))};\n compressed->headroom_ = sizeof(SerdeBuffer);\n compressed->capacity_ = compressedCapacity;\n int ret = ZSTD_compress(compressed->rawMsg(),\n compressedBound,\n ptr->rawMsg(),\n ptr->header().size,\n options.compression.level);\n if (LIKELY(!ZSTD_isError(ret))) {\n compressed->header().size = ret;\n ptr = std::move(compressed);\n } else {\n compress = false;\n }\n }\n\n ptr->header().checksum = Checksum::calcSerde(ptr->rawMsg(), ptr->header().size, compress);\n return ptr;\n }\n\n protected:\n SerdeBuffer() = default;\n uint8_t *self() { return reinterpret_cast(this); }\n const uint8_t *self() const { return reinterpret_cast(this); }\n\n private:\n uint32_t headroom_;\n uint32_t capacity_;\n};\nstatic_assert(sizeof(SerdeBuffer) == 8);\nstatic_assert(std::is_trivial_v, \"SerdeBuffer is not trivial\");\n\n// An item containing a buffer to be written.\nstruct WriteItem {\n using Pool = ObjectPool;\n\n std::atomic next = nullptr;\n decltype(SerdeBuffer::create(serde::MessagePacket<>{}, {})) buf;\n\n uint32_t retryTimes = 0;\n uint32_t maxRetryTimes = kDefaultMaxRetryTimes;\n\n size_t uuid = std::numeric_limits::max();\n bool isReq() const { return uuid != std::numeric_limits::max(); }\n\n template \n static auto createMessage(const T &packet, const CoreRequestOptions &options) {\n auto item = Pool::get();\n item->buf = SerdeBuffer::create(packet, options);\n item->maxRetryTimes = options.sendRetryTimes;\n return item;\n }\n};\nusing WriteItemPtr = WriteItem::Pool::Ptr;\n\nclass Transport;\n\nclass WriteList {\n public:\n WriteList() = default;\n explicit WriteList(WriteItemPtr item) { head_ = tail_ = item.release(); }\n WriteList(WriteItem *head, WriteItem *tail)\n : head_(head),\n tail_(tail) {}\n WriteList(const WriteList &) = delete;\n WriteList(WriteList &&o)\n : head_(std::exchange(o.head_, nullptr)),\n tail_(std::exchange(o.tail_, nullptr)) {}\n ~WriteList() { clear(); }\n\n bool empty() const { return head_ == nullptr; }\n\n void clear();\n\n WriteList extractForRetry();\n\n void concat(WriteList &&o) {\n if (o.empty()) {\n return;\n }\n if (empty()) {\n head_ = std::exchange(o.head_, nullptr);\n tail_ = std::exchange(o.tail_, nullptr);\n } else {\n tail_->next.store(std::exchange(o.head_, nullptr), std::memory_order_relaxed);\n tail_ = std::exchange(o.tail_, nullptr);\n }\n }\n\n void setTransport(std::shared_ptr tr);\n\n protected:\n friend class MPSCWriteList;\n WriteItem *head_ = nullptr;\n WriteItem *tail_ = nullptr;\n};\n\nclass WriteListWithProgress : public WriteList {\n public:\n using WriteList::WriteList;\n\n uint32_t toIOVec(struct iovec *iovec, uint32_t len, size_t &size);\n void advance(size_t written);\n\n private:\n // the write offset of the first write item.\n uint32_t firstOffset_ = 0;\n};\n\nclass MPSCWriteList {\n public:\n ~MPSCWriteList() { takeOut().clear(); }\n\n // add a list of items. [thread-safe]\n void add(WriteList list);\n\n // fetch a batch of write items.\n WriteList takeOut();\n\n private:\n alignas(folly::hardware_destructive_interference_size) std::atomic head_;\n};\n\n} // namespace hf3fs::net\n"], ["/3FS/src/meta/event/Event.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/serde/Serde.h\"\n#include \"common/utils/MagicEnum.hpp\"\n#include \"common/utils/Path.h\"\n#include \"common/utils/UtcTime.h\"\n#include \"fbs/meta/Common.h\"\n#include \"fbs/meta/Schema.h\"\n#include \"fbs/mgmtd/MgmtdTypes.h\"\n\nnamespace hf3fs::meta::server {\n\nstruct Event {\n enum class Type { Create, Mkdir, HardLink, Remove, Truncate, OpenWrite, CloseWrite, Rename, Symlink, GC };\n\n Type type;\n folly::dynamic data;\n\n Event(Type type)\n : Event(type, folly::dynamic::object()) {\n addField(\"event\", magic_enum::enum_name(type));\n addField(\"ts\", UtcClock::now().toMicroseconds());\n }\n Event(Type type, folly::dynamic data)\n : type(type),\n data(std::move(data)) {}\n\n void log() const;\n void log(const folly::json::serialization_opts &opts) const;\n\n Event &addField(folly::dynamic key, folly::dynamic value) {\n data.insert(std::move(key), std::move(value));\n return *this;\n }\n};\n\nstruct MetaEventTrace {\n SERDE_STRUCT_FIELD(eventType, Event::Type::Create);\n SERDE_STRUCT_FIELD(inodeId, InodeId());\n SERDE_STRUCT_FIELD(parentId, InodeId());\n SERDE_STRUCT_FIELD(entryName, std::string());\n SERDE_STRUCT_FIELD(dstParentId, InodeId());\n SERDE_STRUCT_FIELD(dstEntryName, std::string());\n SERDE_STRUCT_FIELD(ownerId, Uid(0));\n SERDE_STRUCT_FIELD(userId, Uid());\n SERDE_STRUCT_FIELD(client, ClientId{Uuid::zero()});\n SERDE_STRUCT_FIELD(tableId, flat::ChainTableId());\n SERDE_STRUCT_FIELD(inodeType, InodeType::File);\n SERDE_STRUCT_FIELD(nlink, uint16_t(0));\n SERDE_STRUCT_FIELD(length, uint64_t(0));\n SERDE_STRUCT_FIELD(truncateVer, uint64_t(0));\n SERDE_STRUCT_FIELD(dynStripe, uint32_t(0));\n SERDE_STRUCT_FIELD(oflags, OpenFlags());\n SERDE_STRUCT_FIELD(recursiveRemove, false);\n SERDE_STRUCT_FIELD(removedChunks, size_t(0));\n SERDE_STRUCT_FIELD(pruneSession, false);\n SERDE_STRUCT_FIELD(symLinkTarget, Path());\n SERDE_STRUCT_FIELD(origPath, Path());\n};\n\n} // namespace hf3fs::meta::server\n"], ["/3FS/src/meta/components/AclCache.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"common/monitor/Recorder.h\"\n#include \"common/utils/Duration.h\"\n#include \"common/utils/UtcTime.h\"\n#include \"fbs/meta/Common.h\"\n#include \"fbs/meta/Schema.h\"\nnamespace hf3fs::meta::server {\n\nclass AclCache {\n public:\n AclCache(size_t cacheSize) {\n for (size_t i = 0; i < kNumShards; i++) {\n shardedMaps_.emplace_back(\n folly::EvictingCacheMap(std::max(cacheSize / kNumShards, 1ul << 10), 128));\n }\n }\n\n std::optional get(InodeId inode, Duration ttl) {\n static monitor::CountRecorder hit(\"meta_server.aclcache_hit\");\n static monitor::CountRecorder miss(\"meta_server.aclcache_miss\");\n\n if (ttl.count() == 0) {\n return std::nullopt;\n }\n std::optional cached;\n {\n auto &shard = getShard(inode);\n auto guard = shard.lock();\n auto iter = guard->find(inode);\n if (iter != guard->end()) {\n cached = iter->second;\n }\n }\n\n if (!cached.has_value()) {\n miss.addSample(1);\n return std::nullopt;\n }\n auto deadline = cached->timestamp + ttl * folly::Random::randDouble(0.8, 1.0);\n if (deadline < SteadyClock::now()) {\n miss.addSample(1);\n return std::nullopt;\n }\n hit.addSample(1);\n return cached->acl;\n }\n\n void set(InodeId inode, Acl acl) {\n auto &shard = getShard(inode);\n shard.lock()->set(inode, {SteadyClock::now(), acl});\n }\n\n void invalid(InodeId inode) { getShard(inode).lock()->erase(inode); }\n\n private:\n static constexpr auto kNumShards = 32u;\n\n struct CacheEntry {\n SteadyTime timestamp;\n Acl acl;\n };\n using CacheMap = folly::Synchronized, std::mutex>;\n\n CacheMap &getShard(InodeId inode) {\n auto shardId = inode.u64() % kNumShards;\n return shardedMaps_[shardId];\n }\n\n std::vector shardedMaps_;\n};\n\n} // namespace hf3fs::meta::server\n"], ["/3FS/src/common/monitor/Recorder.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"DigestBuilder.h\"\n#include \"common/monitor/Sample.h\"\n#include \"common/utils/Address.h\"\n#include \"common/utils/Duration.h\"\n#include \"common/utils/RobinHood.h\"\n#include \"common/utils/Size.h\"\n#include \"common/utils/UtcTime.h\"\n\nnamespace hf3fs::monitor {\n\nclass MonitorInstance;\nclass Collector;\n\nclass Recorder {\n public:\n Recorder(std::string_view name, std::optional tag, MonitorInstance &monitor)\n : register_(false),\n monitor_(monitor) {\n if (tag.has_value()) {\n name_ = name;\n tag_ = tag.value();\n } else {\n name_ = name;\n }\n }\n virtual ~Recorder();\n\n const std::string &name() { return name_; }\n\n virtual void collectAndClean(std::vector &samples, bool cleanInactive);\n\n virtual void collect(std::vector &samples) = 0;\n\n static void setHostname(std::string hostname, std::string podname);\n\n public:\n using ConcurrentMap = folly::ConcurrentHashMap,\n folly::HeterogeneousAccessHash,\n folly::HeterogeneousAccessEqualTo>;\n\n template \n class TagRef : public ConcurrentMap::ConstIterator {\n public:\n TagRef(ConcurrentMap::ConstIterator &&iter)\n : ConcurrentMap::ConstIterator(std::move(iter)) {}\n\n T *operator->() const {\n auto ptr = ConcurrentMap::ConstIterator::operator->()->second.get();\n return static_cast(ptr);\n }\n };\n\n // Expose recorder associated with a tag set\n template \n TagRef getRecorderWithTag(const TagSet &tag);\n\n protected:\n friend class Collector;\n friend bool checkRecorderHasTag(const Recorder &rec, const TagSet &tag);\n\n protected:\n void registerRecorder();\n void unregisterRecorder();\n\n protected:\n std::string name_;\n TagSet tag_;\n bool register_;\n bool logPer30s_ = true;\n UtcTime lastLogTime_;\n bool active_ = true;\n\n ConcurrentMap map_;\n MonitorInstance &monitor_;\n};\n\ntemplate \nclass CountRecorderWithTLSTag final : public Recorder {\n public:\n CountRecorderWithTLSTag(std::string_view name, bool resetWhenCollect)\n : CountRecorderWithTLSTag(name, std::nullopt, resetWhenCollect) {}\n\n CountRecorderWithTLSTag(std::string_view name,\n std::optional tag = std::nullopt,\n bool resetWhenCollect = true);\n CountRecorderWithTLSTag(MonitorInstance &monitor,\n std::string_view name,\n std::optional tag = std::nullopt,\n bool resetWhenCollect = true)\n : CountRecorderWithTLSTag(monitor, name, tag, resetWhenCollect, true) {}\n CountRecorderWithTLSTag(CountRecorderWithTLSTag &parent, const TagSet &tag)\n : CountRecorderWithTLSTag(parent.monitor_, parent.name(), tag, parent.resetWhenCollect_, false) {}\n ~CountRecorderWithTLSTag() final { unregisterRecorder(); }\n\n void collectAndClean(std::vector &samples, bool cleanInactive) final;\n void collect(std::vector &samples) final;\n void addSample(int64_t val) { tls_->addSample(val); }\n void addSample(int64_t val, const TagSet &tag);\n\n TagRef getRecorderWithTag(const TagSet &tag) {\n return Recorder::getRecorderWithTag(tag);\n }\n\n private:\n CountRecorderWithTLSTag(MonitorInstance &monitor,\n std::string_view name,\n std::optional tag,\n bool resetWhenCollect,\n bool needRegister)\n : Recorder(name, tag, monitor),\n resetWhenCollect_(resetWhenCollect) {\n if (needRegister) {\n registerRecorder();\n }\n }\n\n struct TLS {\n TLS(CountRecorderWithTLSTag *parent)\n : parent_(parent) {}\n ~TLS() { parent_->sum_ += exchange(); }\n void addSample(int64_t val) { val_ += val; }\n int64_t exchange() { return val_.exchange(0); }\n int64_t load() { return val_.load(std::memory_order_acquire); }\n\n private:\n CountRecorderWithTLSTag *parent_ = nullptr;\n std::atomic val_{0};\n };\n\n std::atomic sum_{0};\n folly::ThreadLocal tls_{[this] { return new TLS(this); }};\n\n bool resetWhenCollect_;\n int64_t cumulativeVal_ = 0;\n};\n\nstruct SharedThreadLocalTag {};\nstruct AllocatedMemoryCounterTag {};\n\nusing CountRecorder = CountRecorderWithTLSTag;\n\nclass DistributionRecorder : public Recorder {\n public:\n DistributionRecorder(std::string_view name, std::optional tag = std::nullopt);\n DistributionRecorder(MonitorInstance &monitor, std::string_view name, std::optional tag = std::nullopt)\n : DistributionRecorder(monitor, name, tag, true) {}\n DistributionRecorder(DistributionRecorder &parent, const TagSet &tag)\n : DistributionRecorder(parent.monitor_, parent.name(), tag, false) {}\n ~DistributionRecorder() override { unregisterRecorder(); }\n\n void collect(std::vector &samples) override;\n void addSample(double value) { tdigest_.append(value); }\n void addSample(double val, const TagSet &tag);\n virtual void logPer30s(const folly::TDigest &digest);\n\n TagRef getRecorderWithTag(const TagSet &tag) {\n return Recorder::getRecorderWithTag(tag);\n }\n\n protected:\n DistributionRecorder(MonitorInstance &monitor, std::string_view name, std::optional tag, bool needRegister)\n : Recorder(name, tag, monitor) {\n if (needRegister) {\n registerRecorder();\n }\n }\n\n static constexpr size_t kDigestMaxSize = 512;\n static constexpr size_t kDigestBufferSize = 128_KB;\n folly::DigestBuilder tdigest_{kDigestBufferSize, kDigestMaxSize};\n std::vector cumulativeDigests_;\n};\n\nclass LatencyRecorder : public DistributionRecorder {\n public:\n LatencyRecorder(std::string_view name, std::optional tag = std::nullopt);\n LatencyRecorder(LatencyRecorder &parent, const TagSet &tag);\n ~LatencyRecorder() override { unregisterRecorder(); }\n\n void addSample(double value) = delete;\n void addSample(uint64_t val, const TagSet &tag) = delete;\n\n void addSample(std::chrono::nanoseconds duration) { tdigest_.append(duration.count()); }\n void addSample(std::chrono::nanoseconds duration, const TagSet &tag);\n void logPer30s(const folly::TDigest &digest) override;\n\n TagRef getRecorderWithTag(const TagSet &tag) {\n return Recorder::getRecorderWithTag(tag);\n }\n};\n\nclass SimpleDistributionRecorder : public Recorder {\n public:\n SimpleDistributionRecorder(std::string_view name, std::optional tag = std::nullopt);\n SimpleDistributionRecorder(MonitorInstance &monitor, std::string_view name, std::optional tag = std::nullopt)\n : SimpleDistributionRecorder(monitor, name, tag, true) {}\n SimpleDistributionRecorder(SimpleDistributionRecorder &parent, const TagSet &tag)\n : SimpleDistributionRecorder(parent.monitor_, parent.name(), tag, false) {}\n ~SimpleDistributionRecorder() override { unregisterRecorder(); }\n\n void collect(std::vector &samples) override;\n void addSample(int64_t val) { tls_->addSample(val); }\n void addSample(int64_t val, const TagSet &tag);\n\n void addSample(std::chrono::nanoseconds duration) { addSample(duration.count()); }\n void addSample(std::chrono::nanoseconds duration, const TagSet &tag) { addSample(duration.count(), tag); }\n\n TagRef getRecorderWithTag(const TagSet &tag) {\n return Recorder::getRecorderWithTag(tag);\n }\n\n protected:\n SimpleDistributionRecorder(MonitorInstance &monitor,\n std::string_view name,\n std::optional tag,\n bool needRegister)\n : Recorder(name, tag, monitor) {\n if (needRegister) {\n registerRecorder();\n }\n }\n\n struct Tls {\n Tls(SimpleDistributionRecorder *parent)\n : parent_(parent) {}\n\n ~Tls() {\n parent_->sum_.fetch_add(exchangeSum(), std::memory_order_relaxed);\n parent_->count_.fetch_add(exchangeCount(), std::memory_order_relaxed);\n parent_->min_.store(std::min(parent_->min_.load(std::memory_order_relaxed), exchangeMin()),\n std::memory_order_relaxed);\n parent_->max_.store(std::max(parent_->max_.load(std::memory_order_relaxed), exchangeMax()),\n std::memory_order_relaxed);\n }\n\n void addSample(int64_t val) {\n sum_.fetch_add(val, std::memory_order_relaxed);\n count_.fetch_add(1, std::memory_order_relaxed);\n min_.store(std::min(min_.load(std::memory_order_relaxed), val), std::memory_order_relaxed);\n max_.store(std::max(max_.load(std::memory_order_relaxed), val), std::memory_order_relaxed);\n }\n\n int64_t exchangeSum() { return sum_.exchange(0); }\n int64_t exchangeCount() { return count_.exchange(0); }\n int64_t exchangeMin() { return min_.exchange(std::numeric_limits::max()); }\n int64_t exchangeMax() { return max_.exchange(0); }\n\n private:\n SimpleDistributionRecorder *parent_ = nullptr;\n std::atomic sum_{0};\n std::atomic count_{0};\n std::atomic min_{std::numeric_limits::max()};\n std::atomic max_{0};\n };\n\n struct TlsTag {};\n\n std::atomic sum_{0};\n std::atomic count_{0};\n std::atomic min_{std::numeric_limits::max()};\n std::atomic max_{0};\n folly::ThreadLocal tls_{[this] { return new Tls(this); }};\n};\n\ntemplate \nclass OperationRecorderT {\n public:\n OperationRecorderT(std::string_view name, std::optional tag = std::nullopt, bool recordErrorCode = false);\n\n struct Guard {\n explicit Guard(OperationRecorderT &recorder)\n : recorder_(recorder) {}\n Guard(OperationRecorderT &recorder, const TagSet &tags)\n : recorder_(recorder),\n tags_(tags) {}\n ~Guard() { report(false); }\n\n void reportWithCode(status_code_t code);\n void report(bool success) {\n if (success) {\n reportWithCode(StatusCode::kOK);\n } else {\n reportWithCode(StatusCode::kUnknown);\n }\n }\n void succ() { success_ = true; }\n std::optional latency() const { return latency_; }\n Duration ellipse() const { return RelativeTime::now() - startTime_; }\n void dismiss() {\n if (!std::exchange(reported_, true)) {\n if (tags_.has_value()) {\n recorder_.current_.addSample(-1, *tags_);\n } else {\n recorder_.current_.addSample(-1);\n }\n }\n }\n RelativeTime startTime() const { return startTime_; }\n\n private:\n OperationRecorderT &recorder_;\n RelativeTime startTime_ = RelativeTime::now();\n std::optional tags_;\n bool success_ = false;\n bool reported_ = false;\n std::optional latency_;\n };\n\n [[nodiscard]] Guard record() {\n total_.addSample(1);\n current_.addSample(1);\n return Guard(*this);\n }\n [[nodiscard]] Guard record(const TagSet &tag) {\n total_.addSample(1, tag);\n current_.addSample(1, tag);\n return Guard(*this, tag);\n }\n\n private:\n CountRecorder total_;\n CountRecorder fails_;\n CountRecorder current_;\n LatencyRecorderT succ_latencies_;\n LatencyRecorderT fail_latencies_;\n bool recordErrorCode_;\n};\n\nusing OperationRecorder = OperationRecorderT;\nusing SimpleOperationRecorder = OperationRecorderT;\n\nclass ValueRecorder : public Recorder {\n public:\n ValueRecorder(std::string_view name, std::optional tag = std::nullopt, bool resetWhenCollect = true);\n ValueRecorder(MonitorInstance &monitor,\n std::string_view name,\n std::optional tag = std::nullopt,\n bool resetWhenCollect = true)\n : ValueRecorder(monitor, name, tag, true, resetWhenCollect) {}\n ValueRecorder(ValueRecorder &parent, const TagSet &tag)\n : ValueRecorder(parent.monitor_, parent.name(), tag, false, parent.resetWhenCollect_) {}\n ~ValueRecorder() override { unregisterRecorder(); }\n\n void collectAndClean(std::vector &samples, bool cleanInactive) override;\n void collect(std::vector &samples) override;\n void set(int64_t val) { val_.store(val, std::memory_order_release); }\n void set(int64_t val, const TagSet &tag);\n auto value() { return val_.load(); }\n\n TagRef getRecorderWithTag(const TagSet &tag) { return Recorder::getRecorderWithTag(tag); }\n\n private:\n ValueRecorder(MonitorInstance &monitor,\n std::string_view name,\n std::optional tag,\n bool needRegister,\n bool resetWhenCollect)\n : Recorder(name, tag, monitor),\n resetWhenCollect_(resetWhenCollect) {\n if (needRegister) {\n registerRecorder();\n }\n }\n\n std::atomic val_{0};\n bool resetWhenCollect_;\n};\n\nclass LambdaRecorder : public Recorder {\n public:\n LambdaRecorder(std::string_view name, std::optional tag = std::nullopt);\n ~LambdaRecorder() override {\n unregisterRecorder();\n reset();\n }\n\n void setLambda(auto &&f) {\n auto lock = std::unique_lock(mutex_);\n getter_ = std::forward(f);\n }\n\n void reset() {\n auto lock = std::unique_lock(mutex_);\n getter_ = [] { return 0; };\n }\n\n void collect(std::vector &samples) override;\n\n private:\n std::mutex mutex_;\n std::function getter_ = [] { return 0; };\n};\n\n} // namespace hf3fs::monitor\n"], ["/3FS/src/client/mgmtd/MgmtdClientForAdmin.h", "#pragma once\n\n#include \"CommonMgmtdClient.h\"\n#include \"IMgmtdClientForAdmin.h\"\n\nnamespace hf3fs::client {\nclass MgmtdClientForAdmin : public CommonMgmtdClient {\n public:\n struct Config : MgmtdClient::Config {\n Config() {\n set_enable_auto_refresh(false);\n set_enable_auto_heartbeat(false);\n set_enable_auto_extend_client_session(false);\n set_accept_incomplete_routing_info_during_mgmtd_bootstrapping(true);\n }\n };\n\n explicit MgmtdClientForAdmin(std::shared_ptr client)\n : CommonMgmtdClient(std::move(client)) {}\n\n MgmtdClientForAdmin(String clusterId,\n std::unique_ptr stubFactory,\n const Config &config)\n : CommonMgmtdClient(std::make_shared(std::move(clusterId), std::move(stubFactory), config)) {}\n\n CoTryTask setChains(const flat::UserInfo &userInfo,\n const std::vector &chains) final {\n return client_->setChains(userInfo, chains);\n }\n\n CoTryTask setChainTable(const flat::UserInfo &userInfo,\n flat::ChainTableId tableId,\n const std::vector &chains,\n const String &desc) final {\n return client_->setChainTable(userInfo, tableId, chains, desc);\n }\n\n CoTryTask setConfig(const flat::UserInfo &userInfo,\n flat::NodeType nodeType,\n const String &content,\n const String &desc) final {\n return client_->setConfig(userInfo, nodeType, content, desc);\n }\n\n CoTryTask enableNode(const flat::UserInfo &userInfo, flat::NodeId nodeId) final {\n return client_->enableNode(userInfo, nodeId);\n }\n\n CoTryTask disableNode(const flat::UserInfo &userInfo, flat::NodeId nodeId) final {\n return client_->disableNode(userInfo, nodeId);\n }\n\n CoTryTask registerNode(const flat::UserInfo &userInfo, flat::NodeId nodeId, flat::NodeType type) final {\n return client_->registerNode(userInfo, nodeId, type);\n }\n\n CoTryTask setNodeTags(const flat::UserInfo &userInfo,\n flat::NodeId nodeId,\n const std::vector &tags,\n flat::SetTagMode mode) final {\n return client_->setNodeTags(userInfo, nodeId, tags, mode);\n }\n\n CoTryTask unregisterNode(const flat::UserInfo &userInfo, flat::NodeId nodeId) final {\n return client_->unregisterNode(userInfo, nodeId);\n }\n\n CoTryTask> setUniversalTags(const flat::UserInfo &userInfo,\n const String &universalId,\n const std::vector &tags,\n flat::SetTagMode mode) final {\n return client_->setUniversalTags(userInfo, universalId, tags, mode);\n }\n\n CoTryTask rotateLastSrv(const flat::UserInfo &userInfo, flat::ChainId chainId) final {\n return client_->rotateLastSrv(userInfo, chainId);\n }\n\n CoTryTask rotateAsPreferredOrder(const flat::UserInfo &userInfo, flat::ChainId chainId) final {\n return client_->rotateAsPreferredOrder(userInfo, chainId);\n }\n\n CoTryTask setPreferredTargetOrder(const flat::UserInfo &userInfo,\n flat::ChainId chainId,\n const std::vector &preferredTargetOrder) final {\n return client_->setPreferredTargetOrder(userInfo, chainId, preferredTargetOrder);\n }\n\n CoTryTask updateChain(const flat::UserInfo &userInfo,\n flat::ChainId cid,\n flat::TargetId tid,\n mgmtd::UpdateChainReq::Mode mode) final {\n return client_->updateChain(userInfo, cid, tid, mode);\n }\n\n CoTryTask listOrphanTargets() final { return client_->listOrphanTargets(); }\n};\n} // namespace hf3fs::client\n"], ["/3FS/src/common/serde/Serde.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/net/Allocator.h\"\n#include \"common/serde/TypeName.h\"\n#include \"common/utils/DownwardBytes.h\"\n#include \"common/utils/MagicEnum.hpp\"\n#include \"common/utils/NameWrapper.h\"\n#include \"common/utils/Path.h\"\n#include \"common/utils/Reflection.h\"\n#include \"common/utils/Result.h\"\n#include \"common/utils/Thief.h\"\n#include \"common/utils/TypeTraits.h\"\n#include \"common/utils/Varint32.h\"\n#include \"common/utils/Varint64.h\"\n\n#define SERDE_CLASS_TYPED_FIELD(TYPE, NAME, DEFAULT, ...) \\\n private: \\\n friend struct ::hf3fs::refl::Helper; \\\n struct T##NAME : std::type_identity {}; \\\n TYPE NAME##_ = DEFAULT; \\\n \\\n public: \\\n auto &NAME() { return NAME##_; } \\\n const auto &NAME() const { return NAME##_; } \\\n \\\n protected: \\\n constexpr auto T##NAME()->::hf3fs::thief::steal>; \\\n REFL_ADD_SAFE( \\\n (::hf3fs::serde::FieldInfo<#NAME, \\\n &::hf3fs::thief::retrieve::NAME##_ __VA_OPT__(, __VA_ARGS__)>{}), \\\n typename T##NAME::type)\n\n#define SERDE_STRUCT_TYPED_FIELD(TYPE, NAME, DEFAULT, ...) \\\n private: \\\n friend struct ::hf3fs::refl::Helper; \\\n struct T##NAME : std::type_identity {}; \\\n \\\n public: \\\n TYPE NAME = DEFAULT; \\\n \\\n protected: \\\n constexpr auto T##NAME()->::hf3fs::thief::steal>; \\\n REFL_ADD_SAFE( \\\n (::hf3fs::serde::FieldInfo<#NAME, &::hf3fs::thief::retrieve::NAME __VA_OPT__(, __VA_ARGS__)>{}), \\\n typename T##NAME::type)\n\n#define SERDE_CLASS_FIELD(NAME, DEFAULT, ...) \\\n SERDE_CLASS_TYPED_FIELD(std::decay_t, NAME, DEFAULT __VA_OPT__(, __VA_ARGS__))\n\n#define SERDE_STRUCT_FIELD(NAME, DEFAULT, ...) \\\n SERDE_STRUCT_TYPED_FIELD(std::decay_t, NAME, DEFAULT __VA_OPT__(, __VA_ARGS__))\n\nnamespace hf3fs::serde {\n\ntemplate \nstruct FieldInfo {\n static constexpr std::string_view name = Name;\n static constexpr auto getter = Getter;\n static constexpr auto checker = Checker;\n};\n\ntemplate \nconstexpr inline std::true_type is_field_info(FieldInfo);\ntemplate \nconstexpr inline bool is_field_infos = false;\ntemplate \nconstexpr inline bool is_field_infos> = (requires { is_field_info(std::declval()); } && ...);\n\ntemplate \nconcept SerdeType = bool(refl::Helper::Size) && is_field_infos>;\n\ntemplate \nconcept SerdeCopyable =\n std::is_same_v || std::is_integral_v || std::is_floating_point_v || std::is_enum_v || requires {\n typename T::is_serde_copyable;\n};\n\ntemplate \nconstexpr inline auto count() {\n return refl::Helper::Size;\n}\ntemplate \nconstexpr inline auto name() {\n return refl::Helper::FieldInfo::name;\n}\ntemplate \nconstexpr inline auto getter() {\n return refl::Helper::FieldInfo::getter;\n}\nconstexpr inline auto count(auto &&o) { return count>(); }\ntemplate \nconstexpr inline auto name(auto &&o) {\n return name, Index>();\n}\ntemplate \nconstexpr inline auto &value(auto &&o) {\n return o.*getter, Index>();\n}\n\ntemplate \nconstexpr inline auto iterate(auto &&f, auto &&o, auto &&...args) {\n return refl::Helper::iterate>(\n [&](auto type) { return f(type.name, o.*type.getter, args...); });\n}\n\ntemplate \nstruct SerdeMethod {\n static auto serialize(const T &o, auto &out) = delete;\n static auto serializeReadable(const T &o, auto &out) = delete;\n static auto deserialize(T &o, auto &in) = delete;\n static Result deserializeReadable(T &o, auto &out) = delete;\n\n static auto serdeTo(const T &t) = delete;\n static auto serdeToReadable(const T &o) = delete;\n static Result serdeFrom(auto) = delete;\n static Result serdeFromReadable(auto) = delete;\n};\n\ntemplate \nstruct DefaultConstructor {\n static T construct() { return T{}; }\n};\n\ntemplate <>\nstruct DefaultConstructor {\n static Status construct() { return Status::OK; }\n};\n\ntemplate \nstruct DefaultConstructor> {\n static Result construct() { return T{}; }\n};\n} // namespace hf3fs::serde\n\ntemplate <>\nstruct hf3fs::serde::SerdeMethod {\n static auto serialize(const Varint32 &o, auto &out) {\n constexpr int B = 128;\n uint8_t buf[5];\n auto ptr = buf;\n if (o < (1 << 7)) {\n *(ptr++) = o;\n } else if (o < (1 << 14)) {\n *(ptr++) = o | B;\n *(ptr++) = o >> 7;\n } else if (o < (1 << 21)) {\n *(ptr++) = o | B;\n *(ptr++) = (o >> 7) | B;\n *(ptr++) = o >> 14;\n } else if (o < (1 << 28)) {\n *(ptr++) = o | B;\n *(ptr++) = (o >> 7) | B;\n *(ptr++) = (o >> 14) | B;\n *(ptr++) = o >> 21;\n } else {\n *(ptr++) = o | B;\n *(ptr++) = (o >> 7) | B;\n *(ptr++) = (o >> 14) | B;\n *(ptr++) = (o >> 21) | B;\n *(ptr++) = o >> 28;\n }\n out.append(buf, ptr - buf);\n }\n\n static Result deserialize(Varint32 &o, auto &in) {\n o.value = 0;\n for (uint32_t shift = 0; shift <= 28 && !in.str().empty(); shift += 7) {\n uint32_t byte = static_cast(in.str()[0]);\n in.str().remove_prefix(1);\n if (byte & 128) {\n // More bytes are present\n o.value |= ((byte & 127) << shift);\n } else {\n o.value |= (byte << shift);\n return Void{};\n }\n }\n return makeError(StatusCode::kSerdeInsufficientLength, fmt::format(\"varint32 is short\"));\n }\n\n static uint32_t serdeToReadable(Varint32 o) { return o; }\n};\n\ntemplate <>\nstruct hf3fs::serde::SerdeMethod {\n static auto serialize(const Varint64 &o, auto &out) {\n static const int B = 128;\n uint8_t buf[10];\n auto ptr = reinterpret_cast(buf);\n\n uint64_t v = o;\n while (v >= B) {\n *(ptr++) = o | B;\n v >>= 7;\n }\n *(ptr++) = static_cast(v);\n out.append(buf, ptr - buf);\n }\n\n static Result deserialize(Varint64 &o, auto &in) {\n o.value = 0;\n for (uint32_t shift = 0; shift <= 63 && !in.str().empty(); shift += 7) {\n uint64_t byte = static_cast(in.str()[0]);\n in.str().remove_prefix(1);\n if (byte & 128) {\n // More bytes are present\n o.value |= ((byte & 127) << shift);\n } else {\n o.value |= (byte << shift);\n return Void{};\n }\n }\n return makeError(StatusCode::kSerdeInsufficientLength, fmt::format(\"varint64 is short\"));\n }\n\n static uint64_t serdeToReadable(Varint64 o) { return o; }\n};\n\nnamespace hf3fs::serde {\n\nenum class Optional : uint8_t { NullOpt, HasValue };\nstruct VariantIndex {\n uint8_t index;\n};\n\ntemplate \nclass Out {\n public:\n auto tableBegin(bool isInline); // begin a table.\n void tableEnd(auto); // end a table.\n void arrayBegin(); // begin an array.\n void arrayEnd(uint32_t size); // end an array.\n void key(std::string_view key); // prepare the key in a key-value pair.\n void value(auto &&value); // prepare the value in a key-value pair or an array.\n};\n\ntemplate \nclass In {\n public:\n auto parseKey(std::string_view);\n auto parseTable();\n\n // for binary.\n Result parseCopyable(auto &o);\n\n // for Json/Toml.\n Result parseBoolean();\n Result parseInteger();\n Result parseFloat();\n\n // for both.\n Result parseString();\n Result parseOptional(Optional &optional);\n Result> parseVariant();\n};\n\ntemplate \ninline void serialize(auto &&o, Out &out) {\n using T = std::decay_t;\n constexpr bool isBinaryOut = requires { typename Out::is_binary_out; };\n if constexpr (requires { o.serdeToReadable(); } && !isBinaryOut) {\n serialize(o.serdeToReadable(), out);\n } else if constexpr (requires { SerdeMethod::serializeReadable(o, out); } && !isBinaryOut) {\n SerdeMethod::serializeReadable(o, out);\n } else if constexpr (requires { SerdeMethod::serdeToReadable(o); } && !isBinaryOut) {\n serialize(SerdeMethod::serdeToReadable(o), out);\n } else if constexpr (requires { SerdeMethod::serialize(o, out); }) {\n static_assert(requires(T t, In in) { Result{SerdeMethod::deserialize(t, in)}; });\n SerdeMethod::serialize(o, out);\n } else if constexpr (requires { SerdeMethod::serdeTo(o); }) {\n static_assert(requires { SerdeMethod::serdeFrom(SerdeMethod::serdeTo(o)); });\n serialize(SerdeMethod::serdeTo(o), out);\n } else if constexpr (SerdeType) {\n auto start = out.tableBegin(false);\n if constexpr (isBinaryOut) {\n refl::Helper::iterate([&](auto type) { serialize(o.*type.getter, out); },\n [&] { out.tableEnd(start), start = out.tableBegin(false); });\n } else {\n refl::Helper::iterate([&](auto type) { out.key(type.name), serialize(o.*type.getter, out); });\n }\n out.tableEnd(start);\n } else if constexpr (std::is_same_v) {\n out.value(o);\n } else if constexpr (std::is_convertible_v) {\n out.value(std::string_view(o));\n } else if constexpr (is_optional_v) {\n if (o.has_value()) {\n serialize(o.value(), out);\n out.value(Optional::HasValue);\n } else {\n out.value(Optional::NullOpt);\n }\n } else if constexpr (is_unique_ptr_v || is_shared_ptr_v) {\n if (o) {\n serialize(*o, out);\n out.value(Optional::HasValue);\n } else {\n out.value(Optional::NullOpt);\n }\n } else if constexpr (is_variant_v && isBinaryOut) {\n static_assert(std::variant_size_v <= std::numeric_limits::max());\n std::visit(\n [&out](auto &&v) {\n serialize(v, out);\n serialize(type_name_v>, out);\n },\n o);\n } else if constexpr (is_variant_v) {\n static_assert(std::variant_size_v <= std::numeric_limits::max());\n auto start = out.tableBegin(true);\n out.key(\"type\");\n std::visit(\n [&out](auto &&v) {\n serialize(type_name_v>, out);\n out.key(\"value\");\n serialize(v, out);\n },\n o);\n out.tableEnd(start);\n } else if constexpr (is_generic_pair_v && isBinaryOut) {\n serialize(o.second, out);\n serialize(o.first, out);\n } else if constexpr (Container && isBinaryOut) {\n out.arrayBegin();\n if constexpr (requires { o.rbegin(); }) {\n for (auto it = o.rbegin(); it != o.rend(); ++it) {\n serialize(*it, out);\n }\n } else {\n for (auto &item : o) {\n serialize(item, out);\n }\n }\n out.arrayEnd(o.size());\n } else if constexpr (is_vector_v && std::is_arithmetic_v && isBinaryOut) {\n out.value(o);\n } else if constexpr (is_vector_v || is_set_v) {\n out.arrayBegin();\n for (const auto &item : o) {\n serialize(item, out);\n }\n out.arrayEnd(o.size());\n } else if constexpr (is_map_v) {\n auto start = out.tableBegin(true);\n for (const auto &pair : o) {\n if constexpr (requires { out.key(pair.first); }) {\n out.key(pair.first);\n } else if constexpr (requires { pair.first.toUnderType(); }) {\n out.key(fmt::format(\"{}\", pair.first.toUnderType()));\n } else {\n out.key(fmt::format(\"{}\", pair.first));\n }\n serialize(pair.second, out);\n }\n out.tableEnd(start);\n } else if constexpr (isBinaryOut && SerdeCopyable) {\n out.value(o);\n } else if constexpr (std::is_same_v) {\n out.value(o);\n } else if constexpr (std::is_integral_v) {\n out.value(int64_t(o));\n } else if constexpr (std::is_floating_point_v) {\n out.value(double(o));\n } else if constexpr (std::is_enum_v) {\n out.value(magic_enum::enum_name(o));\n } else {\n return notSupportToSerialize(o);\n }\n}\n\nstruct JsonObject;\nstruct TomlObject;\n\ntemplate \nconcept IsJsonOrToml = std::is_same_v || std::is_same_v;\ntemplate \nconcept IsBinaryOut = std::is_same_v || is_specialization_of_v;\n\ntemplate \nclass Out {\n public:\n Out();\n ~Out();\n int tableBegin(bool);\n void tableEnd(auto) { end(); }\n void arrayBegin();\n void arrayEnd(uint32_t) { end(); }\n void end();\n\n void key(std::string_view key) { add(key); }\n void value(bool value) { add(value); }\n void value(int64_t value) { add(value); }\n void value(double value) { add(value); }\n void value(std::string &&str) { add(std::move(str)); }\n void value(std::string_view str) { add(str); }\n void value(Optional);\n void value(VariantIndex) {}\n\n std::string toString(bool sortKeys = false, bool prettyFormatting = false);\n\n protected:\n void add(auto &&v);\n bool inTable();\n bool inArray();\n\n private:\n std::vector root_;\n};\n\ntemplate \nclass Out {\n public:\n using is_binary_out = void;\n\n uint32_t tableBegin(bool) { return out_.size(); }\n void tableEnd(uint32_t start) { serde::serialize(Varint32(out_.size() - start), *this); }\n void arrayBegin() {}\n void arrayEnd(uint32_t size) { serde::serialize(Varint32(size), *this); }\n\n inline void key(std::string_view) {} // ignore key.\n void value(auto &&value) requires(std::is_trivially_copyable_v>) {\n append(&value, sizeof(value));\n }\n void value(std::string_view str) {\n append(str.data(), str.size());\n serde::serialize(Varint32(str.size()), *this);\n }\n template \n requires(std::is_arithmetic_v) void value(const std::vector &vec) {\n append(vec.data(), vec.size() * sizeof(V));\n serde::serialize(Varint32(vec.size()), *this);\n }\n\n auto &bytes() { return out_; }\n\n inline void append(auto *data, size_t size) { out_.append(reinterpret_cast(data), size); }\n\n private:\n T out_;\n};\n\nstruct UnknownVariantType {\n SERDE_STRUCT_FIELD(type, String{});\n // TODO: add serializedBytes\n};\n\ntemplate \nusing AutoFallbackVariant = std::variant;\n\ntemplate \nconstexpr bool is_auto_fallback_variant_v = false;\n\ntemplate \nconstexpr bool is_auto_fallback_variant_v> = true;\n\ninline Result deserialize(auto &o, auto &&in) requires is_specialization, In> {\n using T = std::decay_t;\n using I = std::decay_t;\n constexpr bool isBinaryIn = requires { typename I::is_binary_in; };\n if constexpr (!isBinaryIn && requires { function_first_parameter_t<&T::serdeFromReadable>{}; }) {\n // 0. custom serde impl.\n function_first_parameter_t<&T::serdeFromReadable> from{};\n RETURN_AND_LOG_ON_ERROR(deserialize(from, in));\n auto result = T::serdeFromReadable(from);\n RETURN_AND_LOG_ON_ERROR(result);\n o = std::move(*result);\n return Void{};\n } else if constexpr (!isBinaryIn && requires { function_first_parameter_t<&SerdeMethod::serdeFromReadable>{}; }) {\n function_first_parameter_t<&SerdeMethod::serdeFromReadable> from{};\n RETURN_AND_LOG_ON_ERROR(deserialize(from, in));\n auto result = SerdeMethod::serdeFromReadable(from);\n RETURN_AND_LOG_ON_ERROR(result);\n o = std::move(*result);\n return Void{};\n } else if constexpr (requires { function_first_parameter_t<&SerdeMethod::serdeFrom>{}; }) {\n // 0. custom serde impl.\n function_first_parameter_t<&SerdeMethod::serdeFrom> from{};\n RETURN_AND_LOG_ON_ERROR(deserialize(from, in));\n auto result = SerdeMethod::serdeFrom(from);\n RETURN_AND_LOG_ON_ERROR(result);\n o = std::move(*result);\n return Void{};\n } else if constexpr (!isBinaryIn && requires { SerdeMethod::deserializeReadable(o, in); }) {\n return SerdeMethod::deserializeReadable(o, in);\n } else if constexpr (requires { SerdeMethod::deserialize(o, in); }) {\n return SerdeMethod::deserialize(o, in);\n } else if constexpr (SerdeType) {\n auto table = in.parseTable();\n RETURN_AND_LOG_ON_ERROR(table);\n if constexpr (isBinaryIn) {\n return refl::Helper::iterate(\n [&](auto type) -> Result {\n if (LIKELY(*table)) {\n return deserialize(o.*type.getter, *table);\n }\n // Missing fields at the end are acceptable.\n return Void{};\n },\n [&]() -> Result {\n table = in.parseTable();\n RETURN_AND_LOG_ON_ERROR(table);\n return Void{};\n });\n } else {\n return refl::Helper::iterate([&](auto type) -> Result {\n auto value = table->parseKey(type.name);\n if (LIKELY(bool(value))) {\n return deserialize(o.*type.getter, *value);\n } else {\n using ItemType = std::decay_t;\n if constexpr (is_optional_v) {\n o.*type.getter = std::nullopt;\n } else if constexpr (is_unique_ptr_v || is_shared_ptr_v) {\n o.*type.getter = nullptr;\n }\n }\n return Void{};\n });\n }\n } else if constexpr (std::is_same_v || std::is_same_v) {\n auto result = in.parseString();\n RETURN_AND_LOG_ON_ERROR(result);\n o = *result;\n return Void{};\n } else if constexpr (is_optional_v) {\n Optional optional;\n RETURN_AND_LOG_ON_ERROR(in.parseOptional(optional));\n if (optional == Optional::HasValue) {\n std::remove_cv_t value;\n RETURN_AND_LOG_ON_ERROR(deserialize(value, in));\n o = std::move(value);\n } else {\n o = std::nullopt;\n }\n return Void{};\n } else if constexpr (is_unique_ptr_v || is_shared_ptr_v) {\n Optional optional;\n RETURN_AND_LOG_ON_ERROR(in.parseOptional(optional));\n if (optional == Optional::HasValue) {\n if constexpr (is_unique_ptr_v) {\n o = std::make_unique();\n } else {\n o = std::make_shared();\n }\n RETURN_AND_LOG_ON_ERROR(deserialize(*o, in));\n } else {\n o = nullptr;\n }\n return Void{};\n } else if constexpr (is_variant_v) {\n auto variant = in.parseVariant();\n RETURN_AND_LOG_ON_ERROR(variant);\n return callByIdx>(\n [&](auto type) -> Result {\n if constexpr (std::is_same_v) {\n if constexpr (is_auto_fallback_variant_v) {\n UnknownVariantType uvt;\n uvt.type = variant->first;\n o = std::move(uvt);\n return Void{};\n } else {\n return makeError(StatusCode::kSerdeVariantIndexExceeded);\n }\n } else {\n RETURN_AND_LOG_ON_ERROR(deserialize(type, variant->second));\n o = std::move(type);\n return Void{};\n }\n },\n variantTypeNameToIndex(variant->first));\n return Void{};\n } else if constexpr (is_generic_pair_v && isBinaryIn) {\n RETURN_AND_LOG_ON_ERROR(deserialize(o.first, in));\n RETURN_AND_LOG_ON_ERROR(deserialize(o.second, in));\n return Void{};\n } else if constexpr (Container && isBinaryIn) {\n Varint64 size = 0;\n RETURN_AND_LOG_ON_ERROR(deserialize(size, in));\n o.clear();\n if constexpr (requires { o.reserve(size); }) {\n o.reserve(size);\n }\n auto inserter = std::inserter(o, o.end());\n for (uint32_t i = 0; i < size; ++i) {\n if constexpr (is_generic_pair_v) {\n std::remove_cv_t first;\n RETURN_AND_LOG_ON_ERROR(deserialize(first, in));\n std::remove_cv_t second;\n RETURN_AND_LOG_ON_ERROR(deserialize(second, in));\n inserter++ = typename T::value_type{std::move(first), std::move(second)};\n } else {\n auto value = DefaultConstructor>::construct();\n RETURN_AND_LOG_ON_ERROR(deserialize(value, in));\n inserter++ = std::move(value);\n }\n }\n return Void{};\n } else if constexpr (is_vector_v || is_set_v || is_map_v) {\n auto containerResult = in.parseContainer();\n RETURN_AND_LOG_ON_ERROR(containerResult);\n auto size = containerResult->first;\n auto it = std::move(containerResult->second);\n o.clear();\n if constexpr (requires { o.reserve(size); }) {\n o.reserve(size);\n }\n auto inserter = std::inserter(o, o.end());\n for (uint32_t i = 0; i < size; ++i) {\n if constexpr (is_map_v) {\n auto keyResult = in.fetchKey(it);\n RETURN_AND_LOG_ON_ERROR(keyResult);\n std::string_view key = *keyResult;\n using KeyType = std::remove_cv_t;\n KeyType first;\n if constexpr (requires { first = KeyType{key}; }) {\n first = KeyType{key};\n } else if constexpr (requires { scn::scan(key, \"{}\", first); }) {\n auto result = scn::scan(key, \"{}\", first);\n if (!result) {\n return makeError(StatusCode::kInvalidArg);\n }\n } else if constexpr (requires { scn::scan(key, \"{}\", first.toUnderType()); }) {\n auto result = scn::scan(key, \"{}\", first.toUnderType());\n if (!result) {\n return makeError(StatusCode::kInvalidArg);\n }\n } else {\n return makeError(StatusCode::kInvalidArg);\n }\n std::remove_cv_t second;\n RETURN_AND_LOG_ON_ERROR(deserialize(second, in.fetchValue(it)));\n inserter++ = typename T::value_type{std::move(first), std::move(second)};\n in.next(it);\n } else {\n std::remove_cv_t value;\n RETURN_AND_LOG_ON_ERROR(deserialize(value, in.fetchAndNext(it)));\n inserter++ = std::move(value);\n }\n }\n return Void{};\n } else if constexpr (isBinaryIn && SerdeCopyable) {\n return in.parseCopyable(o);\n } else if constexpr (std::is_same_v) {\n auto result = in.parseBoolean();\n RETURN_AND_LOG_ON_ERROR(result);\n o = *result;\n return Void{};\n } else if constexpr (std::is_integral_v) {\n auto result = in.parseInteger();\n RETURN_AND_LOG_ON_ERROR(result);\n o = *result;\n return Void{};\n } else if constexpr (std::is_floating_point_v) {\n auto result = in.parseFloat();\n RETURN_AND_LOG_ON_ERROR(result);\n o = *result;\n return Void{};\n } else if constexpr (std::is_enum_v) {\n std::string_view str;\n RETURN_AND_LOG_ON_ERROR(deserialize(str, in));\n auto result = magic_enum::enum_cast(str);\n if (result.has_value()) {\n o = *result;\n return Void{};\n }\n return makeError(StatusCode::kSerdeUnknownEnumValue,\n fmt::format(\"unknown enum value {} for type {}\", str, nameof::nameof_full_type()));\n } else {\n return notSupportToDeserialize(o, in);\n }\n}\n\ntemplate <>\nclass In {\n public:\n using is_binary_in = void;\n\n In(std::string_view str)\n : str_(str) {}\n\n operator bool() const { return !str_.empty(); }\n\n Result parseTable() {\n Varint64 length;\n RETURN_AND_LOG_ON_ERROR(serde::deserialize(length, *this));\n if (UNLIKELY(length > str_.length())) {\n return makeError(StatusCode::kSerdeInsufficientLength,\n fmt::format(\"string short {} > {}\", length, str_.length()));\n }\n auto table = In{str_.substr(0, length)};\n str_.remove_prefix(length);\n return table;\n }\n\n Result parseString() {\n Varint64 length;\n RETURN_AND_LOG_ON_ERROR(serde::deserialize(length, *this));\n if (UNLIKELY(length > str_.length())) {\n return makeError(StatusCode::kSerdeInsufficientLength,\n fmt::format(\"string short {} > {}\", length, str_.length()));\n }\n auto value = str_.substr(0, length);\n str_.remove_prefix(length);\n return value;\n }\n\n Result> parseVariant() {\n std::string_view typeName;\n RETURN_AND_LOG_ON_ERROR(serde::deserialize(typeName, *this));\n return std::pair(typeName, *this);\n }\n\n Result parseOptional(Optional &optional) { return serde::deserialize(optional, *this); }\n\n Result parseCopyable(auto &o) {\n if (UNLIKELY(sizeof(o) > str_.length())) {\n return makeError(StatusCode::kSerdeInsufficientLength,\n fmt::format(\"trivially copyable {} > {}\", sizeof(o), str_.length()));\n }\n std::memcpy(&o, str_.data(), sizeof(o));\n str_.remove_prefix(sizeof(o));\n return Void{};\n }\n\n auto &str() { return str_; }\n\n private:\n std::string_view str_;\n};\n\ntemplate <>\nclass In {\n public:\n In(const JsonObject &obj)\n : obj_(obj) {}\n template \n In(const T &obj);\n static Result parse(std::string_view str, std::function(const JsonObject &)> func);\n\n Result parseKey(std::string_view key) const;\n Result parseTable() const;\n\n Result parseBoolean() const;\n Result parseInteger() const;\n Result parseFloat() const;\n\n Result parseString() const;\n Result> parseVariant() const;\n\n Result parseOptional(Optional &optional) const;\n\n Result>> parseContainer() const;\n\n In fetchAndNext(std::unique_ptr &it) const;\n Result fetchKey(std::unique_ptr &it) const;\n In fetchValue(std::unique_ptr &it) const;\n void next(std::unique_ptr &it) const;\n\n private:\n const JsonObject &obj_;\n};\n\ntemplate <>\nclass In {\n public:\n In(const TomlObject &obj)\n : obj_(obj) {}\n template \n In(const T &obj);\n static Result parse(std::string_view str, std::function(const TomlObject &)> func);\n static Result parseFile(const Path &path, std::function(const TomlObject &)> func);\n\n Result parseKey(std::string_view key) const;\n Result parseTable() const;\n\n Result parseBoolean() const;\n Result parseInteger() const;\n Result parseFloat() const;\n\n Result parseString() const;\n Result> parseVariant() const;\n\n Result parseOptional(Optional &optional) const;\n\n Result>> parseContainer() const;\n\n In fetchAndNext(std::unique_ptr &it) const;\n Result fetchKey(std::unique_ptr &it) const;\n In fetchValue(std::unique_ptr &it) const;\n void next(std::unique_ptr &it) const;\n\n private:\n const TomlObject &obj_;\n};\n\ninline std::string serialize(const auto &o) {\n Out>> out;\n serialize(o, out);\n return out.bytes().toString();\n}\n\ninline DownwardBytes> serializeBytes(const auto &o) {\n Out>> out;\n serialize(o, out);\n return std::move(out.bytes());\n}\n\ninline void serializeToUserBuffer(const auto &o, uint8_t *data, uint32_t capacity) {\n Out> out;\n out.bytes().setBuffer(data, capacity);\n serialize(o, out);\n}\n\ninline auto serializeLength(const auto &o) {\n Out> out;\n serialize(o, out);\n return out.bytes().size();\n}\n\ninline Result deserialize(auto &o, std::string_view str) {\n serde::In in(str);\n return deserialize(o, in);\n}\n\ninline std::string toTomlString(const auto &o) {\n Out out;\n serialize(o, out);\n return out.toString();\n}\n\ninline std::string toJsonString(const auto &o, bool sortKeys = false, bool prettyFormatting = false) {\n Out out;\n serialize(o, out);\n return out.toString(sortKeys, prettyFormatting);\n}\n\ninline Result fromJsonString(auto &o, std::string_view str) {\n return In::parse(str, [&](const JsonObject &obj) { return deserialize(o, In(obj)); });\n}\n\ninline Result fromTomlString(auto &o, std::string_view str) {\n return In::parse(str, [&](const TomlObject &obj) { return deserialize(o, In(obj)); });\n}\n\ninline Result fromTomlFile(auto &o, const Path &path) {\n return In::parseFile(path, [&](const TomlObject &obj) { return deserialize(o, In(obj)); });\n}\n\ntemplate \nconcept SerializableToBytes = requires(const T &o) {\n serialize(o);\n};\n\ntemplate \nconcept SerializableToToml = requires(const T &o) {\n toTomlString(o);\n};\n\ntemplate \nconcept SerializableToJson = requires(const T &o) {\n toJsonString(o);\n};\n\ntemplate \nconcept Serializable = requires(const T &o) {\n serialize(o);\n toJsonString(o);\n};\n\n} // namespace hf3fs::serde\n\ntemplate <>\nstruct ::hf3fs::serde::SerdeMethod<::hf3fs::Void> {\n static constexpr auto serialize(Void, auto &&) {} // DO NOTHING.\n static Result deserialize(Void, auto &) { return Void{}; } // DO NOTHING.\n static constexpr std::string_view serdeToReadable(Void) { return \"Void\"; };\n};\n\ntemplate <>\nstruct ::hf3fs::serde::SerdeMethod<::hf3fs::Status> {\n static constexpr auto serialize(const Status &status, auto &out) {\n std::optional msg = std::nullopt;\n if (!status.message().empty()) {\n msg = status.message();\n }\n serde::serialize(msg, out);\n serde::serialize(status.code(), out);\n }\n\n static Result deserialize(Status &status, auto &&in) {\n status_code_t code;\n RETURN_AND_LOG_ON_ERROR(serde::deserialize(code, in));\n std::optional msg;\n RETURN_AND_LOG_ON_ERROR(serde::deserialize(msg, in));\n if (msg.has_value()) {\n status = Status(code, msg.value());\n } else {\n status = Status(code);\n }\n return Void{};\n }\n\n struct InnerStatus {\n SERDE_STRUCT_FIELD(code, uint16_t{});\n SERDE_STRUCT_FIELD(msg, std::string{});\n };\n\n static auto serdeToReadable(const Status &status) {\n return InnerStatus{status.code(), std::string(status.message())};\n }\n\n static Result serdeFromReadable(const InnerStatus &inner) {\n if (inner.msg.empty()) {\n return folly::makeExpected(Status{inner.code});\n } else {\n return folly::makeExpected(Status{inner.code, inner.msg});\n }\n }\n};\n\ntemplate \nstruct ::hf3fs::serde::SerdeMethod<::hf3fs::Result> {\n static auto serialize(const ::hf3fs::Result &result, auto &out) {\n bool hasValue = result.hasValue();\n if (hasValue) {\n serde::serialize(result.value(), out);\n } else {\n serde::serialize(result.error(), out);\n }\n out.value(hasValue);\n }\n\n static auto serializeReadable(const ::hf3fs::Result &result, auto &out) {\n auto start = out.tableBegin(false);\n {\n if (result.hasValue()) {\n out.key(\"value\");\n serde::serialize(result.value(), out);\n } else {\n out.key(\"error\");\n serde::serialize(result.error(), out);\n }\n }\n out.tableEnd(start);\n }\n\n static Result deserialize(::hf3fs::Result &result, auto &&in) {\n bool hasValue = false;\n RETURN_AND_LOG_ON_ERROR(serde::deserialize(hasValue, in));\n if (hasValue) {\n T value;\n RETURN_AND_LOG_ON_ERROR(serde::deserialize(value, in));\n result = std::move(value);\n } else {\n Status status = Status::OK;\n RETURN_AND_LOG_ON_ERROR(serde::deserialize(status, in));\n result = makeError(std::move(status));\n }\n return Void{};\n }\n};\n\ntemplate <>\nstruct hf3fs::serde::SerdeMethod {\n static auto serdeTo(const hf3fs::Path &p) { return p.string(); }\n static Result serdeFrom(std::string_view str) { return hf3fs::Path{std::string{str}}; }\n};\n\nFMT_BEGIN_NAMESPACE\n\ntemplate <::hf3fs::serde::SerdeType T>\nrequires(::hf3fs::serde::SerializableToJson) struct formatter : formatter {\n detail::dynamic_format_specs specs_;\n /* Copy from https://fmt.dev/latest/api.html#formatting-user-defined-types */\n template \n constexpr auto parse(ParseContext &ctx) -> decltype(ctx.begin()) {\n auto end = detail::parse_format_specs(ctx.begin(), ctx.end(), specs_, ctx, detail::type::char_type);\n detail::check_char_specs(specs_);\n return end;\n }\n\n template \n auto format(const T &t, FormatContext &ctx) const {\n bool debug = specs_.type == presentation_type::debug;\n return formatter::format(\n hf3fs::serde::toJsonString(t, debug /*sortKeys*/, debug /*prettyFormatting*/),\n ctx);\n }\n};\n\nFMT_END_NAMESPACE\n"], ["/3FS/src/common/net/sync/ConnectionPool.h", "#pragma once\n\n#include \n\n#include \"common/net/Network.h\"\n#include \"common/net/tcp/TcpSocket.h\"\n#include \"common/utils/BoundedQueue.h\"\n#include \"common/utils/ConfigBase.h\"\n\nnamespace hf3fs::net::sync {\n\nclass ConnectionPool {\n public:\n struct Config : public ConfigBase {\n CONFIG_HOT_UPDATED_ITEM(max_connection_num, 16ul);\n CONFIG_HOT_UPDATED_ITEM(tcp_connect_timeout, 1000_ms);\n };\n\n ConnectionPool(const Config &config)\n : config_(config) {}\n\n Result> acquire(Address addr);\n\n void restore(Address addr, std::unique_ptr socket);\n\n private:\n using Connections = BoundedQueue>;\n Connections *getConnections(Address addr);\n\n private:\n [[maybe_unused]] const Config &config_;\n std::mutex mutex_;\n robin_hood::unordered_map> map_;\n folly::ThreadLocal> tlsCache_;\n};\n\n} // namespace hf3fs::net::sync\n"], ["/3FS/src/common/net/EventLoop.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"common/utils/FdWrapper.h\"\n#include \"common/utils/Result.h\"\n#include \"common/utils/TypeTraits.h\"\n\nnamespace hf3fs::net {\n\n// EventLoop provides a main loop that notifies EventHandler callback objects when I/O is ready on a file descriptor.\nclass EventLoop : public hf3fs::enable_shared_from_this {\n struct HandlerWrapper;\n\n protected:\n EventLoop() = default;\n\n public:\n ~EventLoop() { stopAndJoin(); }\n\n // start and stop.\n Result start(const std::string &threadName = \"EventLoop\");\n Result wakeUp();\n void stopAndJoin();\n\n class EventHandler {\n public:\n virtual ~EventHandler() = default;\n virtual int fd() const = 0;\n virtual void handleEvents(uint32_t epollEvents) = 0;\n\n protected:\n friend class EventLoop;\n std::weak_ptr eventLoop_;\n std::list::iterator it_;\n };\n\n // add a event handler with interest events into event loop.\n Result add(const std::shared_ptr &handler, uint32_t interestEvents);\n\n // remove a event handler from event loop.\n Result remove(EventHandler *handler);\n\n private:\n struct HandlerWrapper {\n std::weak_ptr handler;\n };\n\n void loop();\n\n private:\n FdWrapper epfd_;\n FdWrapper eventfd_;\n\n std::atomic stop_{false};\n std::jthread thread_;\n\n std::mutex mutex_;\n std::list wrapperList_;\n\n // wake up the event loop to do deletion if the size of delete queue greater than this threshold.\n constexpr static size_t kDeleteQueueWakeUpLoopThreshold = 128u;\n // deletion of the wrapper object is done in the loop thread.\n folly::UMPSCQueue::iterator, true> deleteQueue_;\n};\n\nclass EventLoopPool {\n public:\n EventLoopPool(size_t numThreads);\n\n // start and stop.\n Result start(const std::string &threadName);\n void stopAndJoin();\n\n // add a event handler with interest events into event loop.\n Result add(const std::shared_ptr &handler, uint32_t interestEvents);\n\n private:\n std::vector> eventLoops_;\n};\n\n} // namespace hf3fs::net\n"], ["/3FS/src/common/net/IfAddrs.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/utils/Result.h\"\n#include \"ifaddrs.h\"\n\nnamespace hf3fs::net {\n\nclass IfAddrs {\n public:\n struct Addr {\n folly::IPAddressV4 ip;\n size_t mask;\n bool up;\n\n Addr(folly::IPAddressV4 ip, size_t mask, bool up)\n : ip(ip),\n mask(mask),\n up(up) {}\n folly::CIDRNetworkV4 subnet() const { return {ip.mask(mask), mask}; }\n };\n using Map = std::multimap;\n\n static Result> load() {\n static Result> result = loadOnce();\n return result;\n }\n\n private:\n static Result loadOnce() {\n Map net2addr;\n struct ifaddrs *ifaddrList;\n if (getifaddrs(&ifaddrList)) {\n XLOGF(ERR, \"Failed to call getifaddrs, errno {}\", errno);\n return makeError(StatusCode::kOSError, \"Failed to call getifaddrs\");\n }\n\n for (auto ifaddrIter = ifaddrList; ifaddrIter != nullptr; ifaddrIter = ifaddrIter->ifa_next) {\n auto name = ifaddrIter->ifa_name;\n if (ifaddrIter->ifa_addr == nullptr || ifaddrIter->ifa_netmask == nullptr) {\n XLOGF(DBG,\n \"Skip ifaddr of {}, ifa_addr {} or ifa_netmask {} missing.\",\n name,\n (void *)ifaddrIter->ifa_addr,\n (void *)ifaddrIter->ifa_netmask);\n continue;\n }\n if (ifaddrIter->ifa_addr->sa_family != AF_INET || ifaddrIter->ifa_netmask->sa_family != AF_INET) {\n XLOGF(DBG,\n \"Skip ifaddr of {}, address family {} {} != AF_INET\",\n name,\n ifaddrList->ifa_addr->sa_family,\n ifaddrIter->ifa_netmask->sa_family);\n continue;\n }\n\n auto ip = folly::IPAddressV4(((sockaddr_in *)ifaddrIter->ifa_addr)->sin_addr);\n auto mask = folly::IPAddressV4(((sockaddr_in *)ifaddrIter->ifa_netmask)->sin_addr).toByteArray();\n auto maskBits = folly::Bits::count(mask.begin(), mask.end());\n if (folly::IPAddressV4::fetchMask(maskBits) != mask) {\n XLOGF(WARN, \"IfAddr of {}, addr {}, mask {} is not valid!!!\", name, ip.str(), folly::IPAddressV4(mask).str());\n continue;\n }\n\n bool up = false;\n int sock = socket(AF_INET, SOCK_DGRAM, 0);\n if (sock < 0) {\n return makeError(StatusCode::kOSError, \"Failed to create socket {}\", errno);\n } else {\n struct ifreq ifr;\n strncpy(ifr.ifr_name, ifaddrIter->ifa_name, IFNAMSIZ - 1);\n if (ioctl(sock, SIOCGIFFLAGS, &ifr) != 0) {\n XLOG(ERR, \"Failed to query status of {}, errno {}\", name, errno);\n up = false;\n } else {\n up = (ifr.ifr_flags & IFF_UP);\n }\n close(sock);\n }\n\n auto addr = Addr{ip, maskBits, up};\n net2addr.emplace(name, addr);\n\n auto fbs = folly::StringPiece(ifaddrIter->ifa_name);\n XLOGF_IF(INFO,\n fbs.startsWith(\"en\") || fbs.startsWith(\"eth\") || fbs.startsWith(\"ib\") || fbs.startsWith(\"bond\"),\n \"Get ifaddr of {}, addr {}, subnet {}, up {}\",\n ifaddrIter->ifa_name,\n addr,\n addr.subnet(),\n up);\n }\n\n freeifaddrs(ifaddrList);\n\n return net2addr;\n }\n};\n\n} // namespace hf3fs::net\n\nFMT_BEGIN_NAMESPACE\n\ntemplate <>\nstruct formatter : formatter {\n template \n auto format(const hf3fs::net::IfAddrs::Addr &addr, FormatContext &ctx) const {\n return fmt::format_to(ctx.out(), \"{}/{}\", addr.ip.str(), addr.mask);\n }\n};\n\ntemplate <>\nstruct formatter : formatter {\n template \n auto format(const folly::CIDRNetworkV4 &network, FormatContext &ctx) const {\n return fmt::format_to(ctx.out(), \"{}/{}\", network.first.str(), network.second);\n }\n};\n\nFMT_END_NAMESPACE\n"], ["/3FS/src/common/serde/ClientContext.h", "#pragma once\n\n#include \"common/net/IOWorker.h\"\n#include \"common/net/Transport.h\"\n#include \"common/net/Waiter.h\"\n#include \"common/net/WriteItem.h\"\n#include \"common/net/sync/ConnectionPool.h\"\n#include \"common/serde/ClientContext.h\"\n#include \"common/serde/MessagePacket.h\"\n#include \"common/serde/Serde.h\"\n#include \"common/serde/Service.h\"\n#include \"common/utils/Duration.h\"\n\nnamespace hf3fs::serde {\n\nclass ClientContext {\n public:\n ClientContext(net::IOWorker &ioWorker,\n net::Address destAddr,\n const folly::atomic_shared_ptr &options)\n : connectionSource_(&ioWorker),\n destAddr_(destAddr),\n options_(options) {}\n\n ClientContext(net::sync::ConnectionPool &connectionPool,\n net::Address destAddr,\n const folly::atomic_shared_ptr &options)\n : connectionSource_(&connectionPool),\n destAddr_(destAddr),\n options_(options) {}\n\n ClientContext(const net::TransportPtr &tr);\n\n template \n CoTryTask call(const Req &req,\n const net::UserRequestOptions *customOptions = nullptr,\n Timestamp *timestamp = nullptr) {\n auto options = *options_.load(std::memory_order_acquire);\n if (customOptions != nullptr) {\n options.merge(*customOptions);\n }\n\n net::Waiter::Item item;\n uint64_t uuid = net::Waiter::instance().bind(item);\n\n Timestamp ts;\n if ((options.logLongRunningThreshold != 0_ms || options.reportMetrics) && timestamp == nullptr) {\n timestamp = &ts;\n }\n\n MessagePacket packet(req);\n packet.uuid = uuid;\n packet.serviceId = ServiceID;\n packet.methodId = MethodID;\n packet.flags = EssentialFlags::IsReq;\n if (options.compression) {\n packet.flags |= EssentialFlags::UseCompress;\n }\n if (options.enableRDMAControl) {\n packet.flags |= EssentialFlags::ControlRDMA;\n }\n if (timestamp != nullptr) {\n packet.timestamp = Timestamp{UtcClock::now().time_since_epoch().count()};\n }\n\n auto writeItem = net::WriteItem::createMessage(packet, options);\n writeItem->uuid = uuid;\n auto requestLength = writeItem->buf->length();\n if (LIKELY(std::holds_alternative(connectionSource_))) {\n std::get(connectionSource_)->sendAsync(destAddr_, net::WriteList(std::move(writeItem)));\n } else if (std::holds_alternative(connectionSource_)) {\n std::get(connectionSource_)->send(net::WriteList(std::move(writeItem)));\n } else {\n co_return MAKE_ERROR_F(StatusCode::kFoundBug,\n \"Sync client call async method: service id {}, method id {}\",\n ServiceID,\n MethodID);\n }\n\n net::Waiter::instance().schedule(uuid, options.timeout);\n co_await item.baton;\n\n if (UNLIKELY(!item.status)) {\n if (item.status.code() == RPCCode::kTimeout && std::holds_alternative(connectionSource_)) {\n if (item.transport) {\n XLOGF(INFO, \"req timeout and close transport {}\", fmt::ptr(item.transport.get()));\n co_await item.transport->closeIB();\n } else {\n XLOGF(INFO, \"req timeout but no transport\");\n }\n std::get(connectionSource_)->checkConnections(destAddr_, Duration::zero());\n }\n co_return makeError(std::move(item.status));\n }\n\n Result rsp = makeError(StatusCode::kUnknown);\n auto deserializeResult = serde::deserialize(rsp, item.packet.payload);\n if (UNLIKELY(!deserializeResult)) {\n XLOGF(ERR, \"deserialize rsp error: {}\", deserializeResult.error());\n if (item.transport) {\n item.transport->invalidate();\n }\n co_return makeError(std::move(deserializeResult.error()));\n }\n if (timestamp != nullptr && item.packet.timestamp.has_value()) {\n *timestamp = *item.packet.timestamp;\n timestamp->clientWaked = UtcClock::now().time_since_epoch().count();\n }\n if (options.logLongRunningThreshold != 0_ms && timestamp->totalLatency() >= options.logLongRunningThreshold) {\n XLOGF(WARNING,\n \"req takes too long, total {}, server {}, network {}, queue {}\\ndetails {}\",\n timestamp->totalLatency(),\n timestamp->serverLatency(),\n timestamp->networkLatency(),\n timestamp->queueLatency(),\n serde::toJsonString(*timestamp));\n }\n if (timestamp && options.reportMetrics) {\n static const auto methodName = fmt::format(\"{}::{}\",\n static_cast(kServiceName),\n static_cast(kMethodName));\n static const auto tags = monitor::TagSet::create(\"instance\", methodName);\n reportMetrics(tags, timestamp, requestLength, item.buf->length());\n }\n co_return rsp;\n }\n\n template \n Result callSync(const Req &req,\n const net::UserRequestOptions *customOptions = nullptr,\n Timestamp *timestamp = nullptr) {\n auto options = *options_.load(std::memory_order_acquire);\n if (customOptions != nullptr) {\n options.merge(*customOptions);\n }\n auto startTime = RelativeTime::now();\n\n MessagePacket packet(req);\n packet.serviceId = ServiceID;\n packet.methodId = MethodID;\n packet.flags = EssentialFlags::IsReq;\n if (timestamp != nullptr) {\n packet.timestamp = Timestamp{UtcClock::now().time_since_epoch().count()};\n }\n auto buff = net::SerdeBuffer::create, net::SystemAllocator<>>(packet, options);\n\n // acquire connection.\n if (UNLIKELY(!std::holds_alternative(connectionSource_))) {\n return makeError(RPCCode::kConnectFailed);\n }\n auto connectionPool = std::get(connectionSource_);\n auto acquireConnectionResult = connectionPool->acquire(destAddr_);\n if (UNLIKELY(!acquireConnectionResult)) {\n return makeError(RPCCode::kConnectFailed);\n }\n\n auto conn = std::move(acquireConnectionResult.value());\n RETURN_AND_LOG_ON_ERROR(conn->sendSync(buff->buff(), buff->length(), startTime, options.timeout));\n\n net::MessageHeader header;\n RETURN_AND_LOG_ON_ERROR(\n conn->recvSync(folly::MutableByteRange{reinterpret_cast(&header), net::kMessageHeaderSize},\n startTime,\n options.timeout));\n auto rspBuff = net::IOBuf::createCombined(header.size);\n rspBuff->append(header.size);\n RETURN_AND_LOG_ON_ERROR(\n conn->recvSync(folly::MutableByteRange{rspBuff->writableData(), header.size}, startTime, options.timeout));\n\n MessagePacket recv;\n RETURN_AND_LOG_ON_ERROR(\n serde::deserialize(recv, std::string_view(reinterpret_cast(rspBuff->buffer()), header.size)));\n\n Result rsp = makeError(StatusCode::kUnknown);\n RETURN_AND_LOG_ON_ERROR(serde::deserialize(rsp, recv.payload));\n if (timestamp != nullptr && recv.timestamp.has_value()) {\n *timestamp = *recv.timestamp;\n timestamp->clientWaked = UtcClock::now().time_since_epoch().count();\n }\n connectionPool->restore(destAddr_, std::move(conn));\n return rsp;\n }\n\n net::Address addr() const { return destAddr_; }\n\n private:\n static void reportMetrics(const monitor::TagSet &tags, Timestamp *ts, uint64_t requestSize, uint64_t responseSize);\n\n std::variant connectionSource_;\n net::Address destAddr_{};\n const folly::atomic_shared_ptr &options_;\n};\n\n} // namespace hf3fs::serde\n"], ["/3FS/src/mgmtd/MgmtdConfigFetcher.h", "#pragma once\n\n#include \"common/app/AppInfo.h\"\n#include \"common/kv/IKVEngine.h\"\n#include \"fbs/mgmtd/ConfigInfo.h\"\n#include \"fdb/HybridKvEngineConfig.h\"\n\nnamespace hf3fs::mgmtd {\nclass MgmtdServer;\nstruct MgmtdConfigFetcher {\n template \n explicit MgmtdConfigFetcher(const ConfigT &cfg) {\n init(cfg.kv_engine(), cfg.use_memkv(), cfg.fdb());\n }\n\n Result loadConfigTemplate(flat::NodeType nodeType);\n Result completeAppInfo(flat::AppInfo &appInfo);\n\n Result startServer(MgmtdServer &server, const flat::AppInfo &appInfo);\n\n private:\n void init(const kv::HybridKvEngineConfig &config, bool useMemKV, const kv::fdb::FDBConfig &fdbConfig);\n\n std::shared_ptr kvEngine_;\n};\n} // namespace hf3fs::mgmtd\n"], ["/3FS/src/storage/service/TargetMap.h", "#pragma once\n\n#include \n#include \n#include \n#include \n\n#include \"client/mgmtd/RoutingInfo.h\"\n#include \"common/serde/Serde.h\"\n#include \"common/utils/ConstructLog.h\"\n#include \"fbs/mgmtd/MgmtdTypes.h\"\n#include \"fbs/mgmtd/NodeInfo.h\"\n#include \"fbs/mgmtd/TargetInfo.h\"\n#include \"fbs/storage/Common.h\"\n#include \"storage/store/StorageTarget.h\"\n\nnamespace hf3fs::test {\nstruct TargetMapHelper;\n}\n\nnamespace hf3fs::storage {\n\nclass TargetMap {\n public:\n // [observers] clone current map.\n std::shared_ptr clone() const { return std::make_shared(*this); }\n\n // [observers] get target id by chain id.\n Result getTargetId(ChainId chainId) const;\n\n // [observers] get target by target id.\n Result getTarget(TargetId targetId) const;\n\n // [observers] get target by versioned chain id.\n Result getByChainId(VersionedChainId vChainId, bool allowOutdatedChainVer) const;\n\n // [observers]\n auto &getTargets() const { return targets_; }\n\n // [observers]\n auto &syncingChains() const { return syncingChains_; }\n\n // [modifiers] add a new target.\n Result addStorageTarget(const std::shared_ptr &storageTarget);\n\n // [modifiers] get target by target id.\n Result getMutableTarget(TargetId targetId);\n\n // [modifiers] sync receive is started.\n Result syncReceiveDone(VersionedChainId vChainId);\n\n // [modifiers] update by routing info.\n Result updateRouting(std::shared_ptr r, bool log = true);\n\n // [modifiers] set target as offline.\n Result removeTarget(TargetId targetId);\n\n // [modifiers] set target as offline.\n Result offlineTarget(TargetId targetId);\n\n // [modifiers] set targets in path as offline.\n Result offlineTargets(const Path &path);\n\n // [modifiers] reject create chunk for targets in path.\n Result updateDiskState(const Path &path, bool lowSpace, bool rejectCreateChunk);\n\n // update local state.\n static hf3fs::flat::LocalTargetState updateLocalState(TargetId targetId,\n hf3fs::flat::LocalTargetState localState,\n hf3fs::flat::PublicTargetState publicState);\n\n private:\n friend struct test::TargetMapHelper;\n robin_hood::unordered_map targets_;\n flat::RoutingInfoVersion routingInfoVersion_;\n robin_hood::unordered_map chainToTarget_;\n std::vector syncingChains_;\n};\n\nclass AtomicallyTargetMap {\n public:\n // [observers] get a snapshot of target map.\n auto snapshot() const { return targetMap_.load(); }\n\n // [observers] get target by chain id.\n Result> getByChainId(VersionedChainId vChainId,\n bool allowOutdatedChainVer = false) const;\n\n // [observers] get target by its id.\n Result> getByTargetId(TargetId targetId) const;\n\n // [modifiers] set update callback.\n void setUpdateCallback(auto &&func) {\n auto lock = std::unique_lock(mutex_);\n updateCallback_ = std::forward(func);\n }\n\n // [modifiers] add a target.\n Result addStorageTarget(std::shared_ptr storageTarget);\n\n // [modifiers] sync receive is done.\n Result syncReceiveDone(VersionedChainId vChainId);\n\n // [modifiers] update by routing info.\n Result updateRouting(std::shared_ptr r);\n\n // [modifiers] set target as offline.\n Result removeTarget(TargetId targetId);\n\n // [modifiers] set target as offline.\n Result offlineTarget(TargetId targetId);\n\n // [modifiers] set targets in path as offline.\n Result offlineTargets(const Path &path);\n\n // [modifiers] reject create chunk for targets in path.\n Result updateDiskState(const Path &path, bool lowSpace, bool rejectCreateChunk);\n\n // [modifiers] update target used size.\n void updateTargetUsedSize();\n\n // [modifiers] release target map.\n auto release() { return targetMap_.exchange(nullptr); }\n\n protected:\n // [modifiers] update target map atomically.\n Result updateTargetMap(auto &&updateFunc);\n\n private:\n friend struct test::TargetMapHelper;\n ConstructLog<\"storage::AtomicallyTargetMap\"> constructLog_;\n std::mutex mutex_; // for update operation.\n std::function updateCallback_ = [](auto) {};\n folly::atomic_shared_ptr targetMap_{std::make_shared()};\n};\n\n} // namespace hf3fs::storage\n"], ["/3FS/src/common/utils/WorkStealingBlockingQueue.h", "#pragma once\n\n#include \n#include \n#include \n\n#include \"common/utils/SimpleSemaphore.h\"\n\nnamespace hf3fs {\nnamespace details {\ntemplate \nclass EndValueHolder {\n public:\n explicit EndValueHolder(EndPredicate predicate)\n : isEndPredicate_(std::move(predicate)) {}\n\n bool add(T &&item) {\n if (UNLIKELY(isEndPredicate_(item))) {\n {\n auto guard = endValue_.lock();\n *guard = std::move(item);\n }\n isEnd_.store(true, std::memory_order_release);\n return true;\n }\n return false;\n }\n\n bool hasValue() const { return isEnd_.load(std::memory_order_acquire); }\n\n T forceTake() {\n auto guard = endValue_.lock();\n return std::move(**guard);\n }\n\n folly::Optional take() {\n if (UNLIKELY(isEnd_.load(std::memory_order_acquire))) {\n auto guard = endValue_.lock();\n return std::move(**guard);\n }\n return {};\n }\n\n private:\n EndPredicate isEndPredicate_;\n std::atomic isEnd_{false};\n folly::Synchronized, std::mutex> endValue_;\n};\n\ntemplate \nclass SharedNothingQueueStrategy {\n public:\n using ItemType = T;\n using Queue = folly::UnboundedBlockingQueue;\n using QueuePtr = std::shared_ptr;\n\n struct SharedState {\n explicit SharedState(size_t count) {\n queues.reserve(count);\n for (uint32_t i = 0; i < count; ++i) queues.push_back(std::make_shared());\n }\n\n std::vector queues;\n };\n\n SharedNothingQueueStrategy(const std::shared_ptr &state, uint32_t selfPos)\n : self_(state->queues[selfPos]) {}\n\n void add(T &&item) { self_->add(std::move(item)); }\n\n size_t queueSize() const { return self_->size(); }\n\n template \n folly::Optional tryTake(std::chrono::milliseconds time, EndValueHolder &endValue) {\n if (auto item = self_->try_take_for(time); item) {\n return item;\n }\n return endValue.take();\n }\n\n private:\n QueuePtr self_;\n};\n\ntemplate \nclass WorkStealingQueueStrategy {\n public:\n using ItemType = T;\n using Queue = folly::UnboundedBlockingQueue;\n using QueuePtr = std::shared_ptr;\n\n struct SharedState {\n explicit SharedState(size_t count) {\n queues.reserve(count);\n for (uint32_t i = 0; i < count; ++i) queues.push_back(std::make_shared());\n }\n\n std::vector queues;\n };\n\n WorkStealingQueueStrategy(const std::shared_ptr &state, uint32_t selfPos)\n : self_(state->queues[selfPos]),\n siblings_(state->queues) {\n siblings_.erase(siblings_.begin() + selfPos);\n std::shuffle(siblings_.begin(), siblings_.end(), folly::ThreadLocalPRNG{});\n }\n\n void add(T &&item) { self_->add(std::move(item)); }\n\n size_t queueSize() const { return self_->size(); }\n\n template \n folly::Optional tryTake(std::chrono::milliseconds time, EndValueHolder &endValue) {\n static thread_local size_t called = 0;\n if (LIKELY(called++ % 5 != 4)) {\n if (auto item = self_->try_take_for(time); item) {\n return std::move(item);\n }\n\n if (auto item = endValue.take(); item) {\n return std::move(item);\n }\n }\n\n if (!siblings_.empty()) {\n static thread_local size_t next = folly::Random::rand32();\n return siblings_[next++ % siblings_.size()]->try_take();\n }\n\n return {};\n }\n\n private:\n QueuePtr self_;\n std::vector siblings_;\n};\n\ntemplate \nclass RoundRobinQueueStrategy {\n public:\n using ItemType = T;\n using Queue = folly::UnboundedBlockingQueue;\n using QueuePtr = std::shared_ptr;\n\n struct SharedState {\n explicit SharedState(size_t count) {\n queues.reserve(count);\n for (uint32_t i = 0; i < count; ++i) queues.push_back(std::make_shared());\n }\n\n std::atomic next{0};\n std::vector queues;\n };\n\n RoundRobinQueueStrategy(const std::shared_ptr &state, uint32_t selfPos)\n : state_(state),\n selfPos_(selfPos) {\n for (size_t i = 0; i < 4 && i < state->queues.size(); ++i) {\n queues_.push_back(state->queues[(selfPos + i) % state->queues.size()]);\n }\n std::shuffle(queues_.begin() + 1, queues_.end(), folly::ThreadLocalPRNG{});\n }\n\n void add(T &&item) { queues_[0]->add(std::move(item)); }\n\n size_t queueSize() const { return queues_[0]->size(); }\n\n template \n folly::Optional tryTake(std::chrono::milliseconds time, EndValueHolder &endValue) {\n static thread_local uint64_t called = 0;\n static thread_local uint64_t next = 0;\n if (LIKELY(called++ % 5 != 4)) {\n for (size_t i = 0; i < queues_.size(); ++i, ++next) {\n auto pos = next % queues_.size();\n if (auto item = queues_[pos]->try_take(); item) {\n return std::move(item);\n }\n\n if (UNLIKELY(pos == 0 && endValue.hasValue())) {\n return endValue.forceTake();\n }\n }\n }\n\n ++next;\n return queues_[0]->try_take_for(time);\n }\n\n private:\n std::shared_ptr state_;\n std::vector queues_;\n const size_t selfPos_;\n};\n\n// NOTE: BlockingQueueBase should be used as a MPSC queue\ntemplate \nclass BlockingQueueBase : public folly::BlockingQueue {\n public:\n using StrategyType = Strategy;\n using SharedState = typename Strategy::SharedState;\n using T = typename Strategy::ItemType;\n\n BlockingQueueBase(const std::shared_ptr &state, uint32_t selfPos, EndPredicate isEnd)\n : strategy_(state, selfPos),\n endValue_(std::move(isEnd)) {}\n\n folly::BlockingQueueAddResult add(T item) override {\n if (!endValue_.add(std::move(item))) {\n strategy_.add(std::move(item));\n }\n return true;\n }\n\n T take() override {\n for (;;) {\n if (auto item = strategy_.tryTake(timeout_, endValue_); item) {\n return std::move(*item);\n }\n }\n __builtin_unreachable();\n }\n\n folly::Optional try_take_for(std::chrono::milliseconds time) override {\n auto start = std::chrono::steady_clock::now();\n auto deadline = start + time;\n time = std::min(time, timeout_);\n for (;;) {\n if (auto item = strategy_.tryTake(time, endValue_); item) {\n return std::move(item);\n }\n if (std::chrono::steady_clock::now() >= deadline) {\n return {};\n }\n }\n __builtin_unreachable();\n }\n\n size_t size() override { return strategy_.queueSize(); }\n\n private:\n static constexpr auto timeout_ = std::chrono::milliseconds(1);\n\n Strategy strategy_;\n EndValueHolder endValue_;\n};\n} // namespace details\n\ntemplate \nusing SharedNothingBlockingQueue = details::BlockingQueueBase, EndPredicate>;\n\ntemplate \nusing WorkStealingBlockingQueue = details::BlockingQueueBase, EndPredicate>;\n\ntemplate \nusing RoundRobinBlockingQueue = details::BlockingQueueBase, EndPredicate>;\n} // namespace hf3fs\n"], ["/3FS/src/common/net/Transport.h", "#pragma once\n\n#include \n#include \n#include \n\n#include \"common/net/EventLoop.h\"\n#include \"common/net/MessageHeader.h\"\n#include \"common/net/Socket.h\"\n#include \"common/net/WriteItem.h\"\n#include \"common/net/ib/IBSocket.h\"\n#include \"common/net/tcp/TcpSocket.h\"\n#include \"common/utils/Address.h\"\n#include \"common/utils/Duration.h\"\n#include \"common/utils/Size.h\"\n\nnamespace hf3fs::net {\n\nclass IOWorker;\n\n// A wrapper of the underlying socket with read/write states.\nclass Transport : public EventLoop::EventHandler, public hf3fs::enable_shared_from_this {\n protected:\n // not allowed to construct transport directly. use create instead.\n explicit Transport(std::unique_ptr socket, IOWorker &io_worker, Address serverAddr);\n\n public:\n ~Transport() override;\n\n // create a transport from a socket with ownership.\n static std::shared_ptr create(std::unique_ptr socket, IOWorker &io_worker, Address::Type addrType);\n static std::shared_ptr create(Address addr, IOWorker &io_worker);\n\n // connect.\n CoTryTask connect(Address addr, Duration timeout);\n\n // return the address of the server.\n Address serverAddr() const { return serverAddr_; }\n\n // return IP of peer.\n folly::IPAddressV4 peerIP() const { return socket_->peerIP(); }\n\n // is TCP or RDMA connection.\n bool isTCP() const { return serverAddr_.isTCP(); }\n bool isRDMA() const { return serverAddr_.isRDMA(); }\n IBSocket *ibSocket() { return dynamic_cast(socket_.get()); }\n\n // return the address of the peer.\n std::string describe() const { return socket_->describe(); }\n\n // send a list asynchronously. return a list to be retried if send failed. [thread-safe]\n std::optional send(WriteList list);\n\n // invalidate this transport. [thread-safe]\n void invalidate(bool logError = true);\n\n // is invalidated or not.\n bool invalidated() const;\n\n // close IB socket.\n CoTask closeIB();\n\n // check socket.\n Result check() { return socket_->check(); }\n\n // get credentials for UNIX domain socket.\n Result getPeerCredentials();\n\n // return credentials for UNIX domain socket.\n auto &credentials() const { return credentials_; }\n\n // is expired or not.\n bool expired(Duration expiredTime) const {\n return expiredTime != Duration::zero() && RelativeTime::now() >= lastUsedTime_.load() + expiredTime;\n }\n\n protected:\n enum class Action { OK, Retry, Suspend, Fail };\n template \n Action tryToSuspend();\n\n // there is and at most one read task is being executed.\n void doRead(bool error, bool logError = true);\n\n // there is and at most one write task is being executed.\n void doWrite(bool error, bool logError = true);\n Action writeAll();\n\n // try to clean up the state of the socket.\n void tryToCleanUp(bool isWrite);\n\n // file descriptor monitored by epoll. [EventHandler]\n int fd() const final { return socket_->fd(); }\n // handle the events notified by epoll. [EventHandler]\n void handleEvents(uint32_t epollEvents) final;\n\n // wake up when read/write/poll finished.\n void wakeUpAfterLastReadAndWriteFinished(uint32_t flags);\n\n private:\n friend class IOWorker;\n\n // the inner socket, TCP or RDMA.\n std::unique_ptr socket_;\n // the object that actually handles the io work.\n IOWorker &ioWorker_;\n // connection executor\n std::weak_ptr> connExecutor_;\n // address of the remote server.\n Address serverAddr_;\n\n // protect the read and write for RDMA connection.\n std::mutex mutex_;\n\n // the inner state that supports atomic changes.\n alignas(folly::hardware_destructive_interference_size) std::atomic flags_{0};\n\n // last used time.\n std::atomic lastUsedTime_ = RelativeTime::now();\n\n // for read.\n IOBufPtr readBuff_ = MessageWrapper::allocate(kMessageReadBufferSize);\n\n // for UNIX domain socket.\n std::optional credentials_;\n\n // the linked list in writing.\n WriteListWithProgress inWritingList_;\n // the linked list to be written.\n MPSCWriteList mpscWriteList_;\n\n // post when last read and write are finished.\n folly::coro::Baton lastReadAndWriteFinished_;\n};\nusing TransportPtr = std::shared_ptr;\n\n} // namespace hf3fs::net\n"], ["/3FS/src/common/utils/DefaultRetryStrategy.h", "#pragma once\n\n#include \n#include \n\n#include \"common/kv/ITransaction.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/Result.h\"\n#include \"common/utils/Status.h\"\n#include \"common/utils/UtcTime.h\"\n#include \"fdb/FDBTransaction.h\"\n\nnamespace hf3fs {\nstruct CoroSleeper {\n CoTask operator()(std::chrono::milliseconds d) const { co_await folly::coro::sleep(d); }\n};\n\nstruct RetryConfig {\n using TimeUnit = std::chrono::milliseconds;\n TimeUnit minRetryInterval{0};\n TimeUnit maxRetryInterval{0};\n size_t maxRetryCount{0};\n};\n\nstruct RetryState {\n using TimeUnit = std::chrono::milliseconds;\n\n const RetryConfig config;\n TimeUnit retryInterval;\n size_t retryCount = 0;\n\n RetryState(const RetryConfig &config)\n : config(config),\n retryInterval(config.minRetryInterval) {}\n\n bool canRetry() const { return retryCount < config.maxRetryCount; }\n\n void reset() {\n retryInterval = config.minRetryInterval;\n retryCount = 0;\n }\n\n void next() {\n ++retryCount;\n retryInterval = std::min(2 * retryInterval, config.maxRetryInterval);\n }\n};\n\ntemplate \nclass DefaultRetryStrategy {\n public:\n using TimeUnit = std::chrono::milliseconds;\n DefaultRetryStrategy(RetryConfig config, Sleeper sleeper = Sleeper{})\n : state_(config),\n sleeper_(std::move(sleeper)) {}\n\n template \n Result init(Txn * /* txn */) {\n state_.reset();\n return Void{};\n }\n\n template \n CoTryTask onError(Txn *txn, Status error) {\n CO_RETURN_ON_ERROR(co_await onError(error));\n txn->reset();\n co_return Void{};\n }\n\n CoTryTask onError(Status error) {\n if (!kv::TransactionHelper::isRetryable(error, false) || !state_.canRetry()) {\n co_return makeError(std::move(error));\n }\n co_await sleeper_(state_.retryInterval);\n state_.next();\n co_return Void{};\n }\n\n Sleeper &getSleeper() { return sleeper_; }\n\n private:\n RetryState state_;\n Sleeper sleeper_;\n};\n} // namespace hf3fs\n"], ["/3FS/src/common/app/TwoPhaseApplication.h", "#pragma once\n\n#include \n\n#include \"Utils.h\"\n#include \"common/app/ApplicationBase.h\"\n#include \"common/utils/LogCommands.h\"\n\nDECLARE_string(cfg);\nDECLARE_bool(dump_default_cfg);\nDECLARE_bool(use_local_cfg);\n\nnamespace hf3fs {\ntemplate \nclass TwoPhaseApplication : public ApplicationBase {\n using Launcher = typename Server::Launcher;\n using ServerConfig = typename Server::Config;\n\n public:\n TwoPhaseApplication()\n : launcher_(std::make_unique()) {}\n\n private:\n struct Config : public ConfigBase {\n CONFIG_OBJ(common, typename Server::CommonConfig);\n CONFIG_OBJ(server, ServerConfig);\n };\n\n Result parseFlags(int *argc, char ***argv) final {\n RETURN_ON_ERROR(launcher_->parseFlags(argc, argv));\n\n static constexpr std::string_view dynamicConfigPrefix = \"--config.\";\n return ApplicationBase::parseFlags(dynamicConfigPrefix, argc, argv, configFlags_);\n }\n\n Result initApplication() final {\n if (FLAGS_dump_default_cfg) {\n fmt::print(\"{}\\n\", config_.toString());\n exit(0);\n }\n\n auto firstInitRes = launcher_->init();\n XLOGF_IF(FATAL, !firstInitRes, \"Failed to init launcher: {}\", firstInitRes.error());\n\n app_detail::loadAppInfo([this] { return launcher_->loadAppInfo(); }, appInfo_);\n app_detail::initConfig(config_, configFlags_, appInfo_, [this] { return launcher_->loadConfigTemplate(); });\n XLOGF(INFO, \"Server config inited\");\n\n app_detail::initCommonComponents(config_.common(), Server::kName, appInfo_.nodeId);\n\n onLogConfigUpdated_ = app_detail::makeLogConfigUpdateCallback(config_.common().log(), Server::kName);\n onMemConfigUpdated_ = app_detail::makeMemConfigUpdateCallback(config_.common().memory(), appInfo_.hostname);\n\n XLOGF(INFO, \"Full Config:\\n{}\", config_.toString());\n app_detail::persistConfig(config_);\n\n XLOGF(INFO, \"Start to init server\");\n auto initRes = initServer();\n XLOGF_IF(FATAL, !initRes, \"Init server failed: {}\", initRes.error());\n XLOGF(INFO, \"Init server finished\");\n\n XLOGF(INFO, \"Start to start server\");\n auto startRes = startServer();\n XLOGF_IF(FATAL, !startRes, \"Start server failed: {}\", startRes.error());\n XLOGF(INFO, \"Start server finished\");\n\n launcher_.reset();\n\n return Void{};\n }\n\n void stop() final {\n XLOGF(INFO, \"Stop TwoPhaseApplication...\");\n if (launcher_) {\n launcher_.reset();\n }\n stopAndJoin(server_.get());\n server_.reset();\n XLOGF(INFO, \"Stop TwoPhaseApplication finished\");\n }\n\n config::IConfig *getConfig() final { return &config_; }\n\n const flat::AppInfo *info() const final { return &appInfo_; }\n\n bool configPushable() const final { return FLAGS_cfg.empty() && !FLAGS_use_local_cfg; }\n\n void onConfigUpdated() { app_detail::persistConfig(config_); }\n\n private:\n Result initServer() {\n server_ = std::make_unique(config_.server());\n RETURN_ON_ERROR(server_->setup());\n XLOGF(INFO, \"{}\", server_->describe());\n return Void{};\n }\n\n Result startServer() {\n auto startResult = launcher_->startServer(*server_, appInfo_);\n XLOGF_IF(FATAL, !startResult, \"Start server failed: {}\", startResult.error());\n appInfo_ = server_->appInfo();\n return Void{};\n }\n\n ConfigFlags configFlags_;\n\n Config config_;\n flat::AppInfo appInfo_;\n std::unique_ptr launcher_;\n std::unique_ptr server_;\n std::unique_ptr onLogConfigUpdated_;\n std::unique_ptr onMemConfigUpdated_;\n};\n} // namespace hf3fs\n"], ["/3FS/src/storage/worker/CheckWorker.h", "#pragma once\n\n#include \n#include \n#include \n#include \n\n#include \"common/utils/ConfigBase.h\"\n#include \"storage/service/TargetMap.h\"\n\nnamespace hf3fs::storage {\n\nstruct Components;\n\nclass CheckWorker {\n public:\n class Config : public ConfigBase {\n CONFIG_HOT_UPDATED_ITEM(update_target_size_interval, 10_s);\n CONFIG_HOT_UPDATED_ITEM(emergency_recycling_ratio, 0.95);\n CONFIG_HOT_UPDATED_ITEM(disk_low_space_threshold, 0.96);\n CONFIG_HOT_UPDATED_ITEM(disk_reject_create_chunk_threshold, 0.98);\n };\n\n CheckWorker(const Config &config, Components &components);\n\n // start check worker.\n Result start(const std::vector &targetPaths, const std::vector &manufacturers);\n\n // stop check worker. End all tasks immediately.\n Result stopAndJoin();\n\n // check hf3fs path writable or not.\n static bool checkWritable(const Path &path);\n\n protected:\n void loop(const std::vector &targetPaths, const std::vector &manufacturers);\n\n private:\n ConstructLog<\"storage::CheckWorker\"> constructLog_;\n const Config &config_;\n Components &components_;\n folly::CPUThreadPoolExecutor executors_;\n\n std::mutex mutex_;\n std::condition_variable cond_;\n std::atomic stopping_ = false;\n std::atomic started_ = false;\n std::atomic stopped_ = false;\n};\n\n} // namespace hf3fs::storage\n"], ["/3FS/src/fuse/UserConfig.h", "#pragma once\n\n#include \"FuseConfig.h\"\n#include \"common/utils/AtomicSharedPtrTable.h\"\n#include \"fbs/meta/Common.h\"\n#include \"fbs/meta/Schema.h\"\n\nnamespace hf3fs::fuse {\nclass UserConfig {\n public:\n UserConfig() = default;\n void init(FuseConfig &config);\n Result setConfig(const char *key, const char *val, const meta::UserInfo &ui);\n Result lookupConfig(const char *key, const meta::UserInfo &ui);\n Result statConfig(meta::InodeId iid, const meta::UserInfo &ui);\n std::pair>, std::shared_ptr>>>\n listConfig(const meta::UserInfo &ui);\n\n public:\n const FuseConfig &getConfig(const meta::UserInfo &ui);\n\n public:\n const std::vector systemKeys{\"storage.net_client.rdma_control.max_concurrent_transmission\",\n \"periodic_sync.enable\",\n \"periodic_sync.interval\",\n \"periodic_sync.flush_write_buf\",\n \"io_worker_coros.hi\",\n \"io_worker_coros.lo\",\n \"max_jobs_per_ioring\",\n \"io_job_deq_timeout\"};\n const std::vector userKeys{\"enable_read_cache\",\n \"readonly\",\n \"dryrun_bench_mode\",\n \"flush_on_stat\",\n \"sync_on_stat\",\n \"attr_timeout\",\n \"entry_timeout\",\n \"negative_timeout\",\n \"symlink_timeout\"};\n\n private:\n Result> parseKey(const char *key);\n meta::InodeId configIid(bool isGet, bool isSys, int kidx) {\n return meta::InodeId{(isGet ? meta::InodeId::getConf() : meta::InodeId::setConf()).u64() - 1 -\n (isSys ? 0 : systemKeys.size()) - kidx};\n }\n\n private:\n FuseConfig *config_;\n struct LocalConfig {\n LocalConfig(const FuseConfig &globalConfig)\n : config(globalConfig) {}\n std::mutex mtx;\n FuseConfig config;\n std::vector updatedItems;\n };\n std::unique_ptr> configs_;\n std::mutex userMtx_;\n std::set users_;\n\n private:\n std::atomic storageMaxConcXmit_;\n};\n} // namespace hf3fs::fuse\n"], ["/3FS/src/common/net/ib/IBConnectService.h", "#pragma once\n\n#include \n#include \n#include \n#include \n\n#include \"common/net/ib/IBConnect.h\"\n#include \"common/net/ib/IBDevice.h\"\n#include \"common/net/ib/IBSocket.h\"\n#include \"common/serde/CallContext.h\"\n#include \"common/serde/Service.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/Duration.h\"\n\nnamespace hf3fs::net {\n\nSERDE_SERVICE(IBConnect, 11) {\n SERDE_SERVICE_METHOD(query, 1, IBQueryReq, IBQueryRsp);\n SERDE_SERVICE_METHOD(connect, 2, IBConnectReq, IBConnectRsp);\n};\n\nclass IBConnectService : public serde::ServiceWrapper {\n public:\n using AcceptFn = std::function)>;\n\n IBConnectService(const IBSocket::Config &config, AcceptFn accept, std::function acceptTimeout)\n : config_(config),\n accept_(std::move(accept)),\n acceptTimeout_(acceptTimeout) {}\n\n CoTryTask query(serde::CallContext &ctx, const IBQueryReq &req);\n CoTryTask connect(serde::CallContext &ctx, const IBConnectReq &req);\n\n private:\n FRIEND_TEST(TestRDMA, SlowConnect);\n FRIEND_TEST(TestRDMA, ConnectitonLost);\n friend class IBSocket;\n\n static std::atomic &delayMs() {\n static std::atomic delay{0};\n return delay;\n }\n\n static std::atomic &connectionLost() {\n static std::atomic val{false};\n return val;\n }\n\n const IBSocket::Config &config_;\n AcceptFn accept_;\n std::function acceptTimeout_;\n};\n\n} // namespace hf3fs::net"], ["/3FS/src/storage/update/UpdateJob.h", "#pragma once\n\n#include \n\n#include \"chunk_engine/src/cxx.rs.h\"\n#include \"fbs/storage/Common.h\"\n#include \"storage/store/ChunkMetadata.h\"\n#include \"storage/store/ChunkStore.h\"\n\nnamespace hf3fs::storage {\n\nclass StorageTarget;\n\nclass ChunkEngineUpdateJob {\n public:\n ChunkEngineUpdateJob() = default;\n ChunkEngineUpdateJob(const ChunkEngineUpdateJob &) = delete;\n ChunkEngineUpdateJob(ChunkEngineUpdateJob &&other)\n : engine_(std::exchange(other.engine_, nullptr)),\n chunk_(std::exchange(other.chunk_, nullptr)) {}\n\n void set(chunk_engine::Engine &engine, chunk_engine::WritingChunk *chunk) {\n reset();\n engine_ = &engine;\n chunk_ = chunk;\n }\n\n auto release() { return std::exchange(engine_, nullptr); }\n auto chunk() const { return chunk_; }\n\n void reset() {\n if (engine_ && chunk_) {\n release()->release_writing_chunk(chunk_);\n }\n }\n\n ~ChunkEngineUpdateJob() { reset(); }\n\n private:\n chunk_engine::Engine *engine_{};\n chunk_engine::WritingChunk *chunk_{};\n};\n\nclass UpdateJob {\n public:\n UpdateJob(ServiceRequestContext &requestCtx,\n const UpdateIO &updateIO,\n const UpdateOptions &options,\n ChunkEngineUpdateJob &chunkEngineJob,\n std::shared_ptr target,\n bool allowToAllocate = true)\n : requestCtx_(requestCtx),\n type_(updateIO.updateType),\n chunkId_(updateIO.key.chunkId),\n target_(std::move(target)),\n updateIO_(updateIO),\n chunkEngineJob_(chunkEngineJob),\n options_(options),\n allowToAllocate_(allowToAllocate) {}\n\n UpdateJob(ServiceRequestContext &requestCtx,\n const CommitIO &commitIO,\n const UpdateOptions &options,\n ChunkEngineUpdateJob &chunkEngineJob,\n std::shared_ptr target)\n : requestCtx_(requestCtx),\n type_(UpdateType::COMMIT),\n chunkId_(commitIO.key.chunkId),\n target_(std::move(target)),\n commitIO_(commitIO),\n chunkEngineJob_(chunkEngineJob),\n options_(options) {}\n\n auto &requestCtx() { return requestCtx_; }\n auto type() const { return type_; }\n const auto &chunkId() const { return chunkId_; }\n auto &target() const { return target_; }\n auto &updateIO() { return updateIO_; }\n auto &commitIO() { return commitIO_; }\n auto &chunkEngineJob() { return chunkEngineJob_; }\n auto &options() { return options_; }\n auto &result() { return result_; }\n auto &state() { return state_; }\n auto allowToAllocate() const { return allowToAllocate_; }\n ChainVer commitChainVer() const {\n if (options_.isSyncing) {\n return options_.commitChainVer;\n } else if (type() == UpdateType::COMMIT) {\n return commitIO_.commitChainVer;\n } else {\n return updateIO_.key.vChainId.chainVer;\n }\n }\n\n CoTask complete() const { co_await baton_; }\n void setResult(Result result) {\n result_.lengthInfo = std::move(result);\n baton_.post();\n }\n\n protected:\n ServiceRequestContext &requestCtx_;\n UpdateType type_;\n ChunkId chunkId_;\n std::shared_ptr target_;\n UpdateIO updateIO_;\n CommitIO commitIO_;\n ChunkEngineUpdateJob &chunkEngineJob_;\n UpdateOptions options_;\n IOResult result_;\n folly::coro::Baton baton_;\n struct State {\n const uint8_t *data = nullptr;\n } state_;\n bool allowToAllocate_ = true;\n};\n\n} // namespace hf3fs::storage\n"], ["/3FS/src/storage/store/ChunkFileStore.h", "#pragma once\n\n#include \n#include \n\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/FdWrapper.h\"\n#include \"common/utils/Path.h\"\n#include \"common/utils/Result.h\"\n#include \"common/utils/RobinHood.h\"\n#include \"common/utils/Shards.h\"\n#include \"storage/store/ChunkFileView.h\"\n#include \"storage/store/ChunkMetadata.h\"\n#include \"storage/store/GlobalFileStore.h\"\n#include \"storage/store/PhysicalConfig.h\"\n\nnamespace hf3fs::storage {\n\nclass ChunkFileStore {\n public:\n class Config : public ConfigBase {\n CONFIG_ITEM(preopen_chunk_size_list, std::set{});\n };\n\n ChunkFileStore(const Config &config, GlobalFileStore &globalFileStore)\n : config_(config),\n globalFileStore_(globalFileStore) {}\n\n // create file store.\n Result create(const PhysicalConfig &config);\n\n // load file store.\n Result load(const PhysicalConfig &config);\n\n // add new chunk size.\n Result addChunkSize(const std::vector &sizeList);\n\n // get a chunk file. [thread-safe]\n Result open(ChunkFileId fileId);\n\n // recycle a chunk. [thread-safe]\n Result punchHole(ChunkFileId fileId, size_t offset);\n\n // allocate space. [thread-safe]\n Result allocate(ChunkFileId fileId, size_t offset, size_t size);\n\n protected:\n // open inner file. [thread-safe]\n Result openInnerFile(ChunkFileId fileId, bool createFile = false);\n\n // create inner file.\n Result createInnerFile(Size chunkSize);\n\n private:\n const Config &config_;\n GlobalFileStore &globalFileStore_;\n\n Path path_;\n uint32_t physicalFileCount_{};\n\n constexpr static auto kShardsNum = 64u;\n folly::ThreadLocal> tlsCache_;\n};\n\n} // namespace hf3fs::storage\n"], ["/3FS/src/mgmtd/store/MgmtdStore.h", "#pragma once\n\n#include \n#include \n#include \n#include \n\n#include \"common/kv/ITransaction.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/UtcTime.h\"\n#include \"fbs/mgmtd/ChainInfo.h\"\n#include \"fbs/mgmtd/ChainTable.h\"\n#include \"fbs/mgmtd/ConfigInfo.h\"\n#include \"fbs/mgmtd/MgmtdLeaseInfo.h\"\n#include \"fbs/mgmtd/PersistentNodeInfo.h\"\n#include \"fbs/mgmtd/RoutingInfo.h\"\n\nnamespace hf3fs::mgmtd {\nclass MgmtdStore {\n public:\n MgmtdStore() = default;\n\n // return current lease\n CoTryTask extendLease(kv::IReadWriteTransaction &txn,\n const flat::PersistentNodeInfo &nodeInfo,\n std::chrono::microseconds leaseLength,\n UtcTime now,\n flat::ReleaseVersion rv = flat::ReleaseVersion::fromVersionInfo(),\n bool checkReleaseVersion = true);\n CoTryTask ensureLeaseValid(kv::IReadOnlyTransaction &txn, flat::NodeId nodeId, UtcTime now);\n\n CoTryTask storeNodeInfo(kv::IReadWriteTransaction &txn, const flat::PersistentNodeInfo &info);\n CoTryTask clearNodeInfo(kv::IReadWriteTransaction &txn, flat::NodeId nodeId);\n CoTryTask> loadNodeInfo(kv::IReadOnlyTransaction &txn,\n flat::NodeId nodeId,\n bool snapshotLoad = false);\n\n CoTryTask loadRoutingInfoVersion(kv::IReadOnlyTransaction &txn);\n CoTryTask storeRoutingInfoVersion(kv::IReadWriteTransaction &txn, flat::RoutingInfoVersion version);\n\n CoTryTask> loadAllNodes(kv::IReadOnlyTransaction &txn);\n\n CoTryTask> loadMgmtdLeaseInfo(kv::IReadOnlyTransaction &txn);\n\n CoTryTask storeMgmtdLeaseInfo(kv::IReadWriteTransaction &txn,\n const flat::MgmtdLeaseInfo &leaseInfo);\n\n CoTryTask storeConfig(kv::IReadWriteTransaction &txn, flat::NodeType nodeType, const flat::ConfigInfo &info);\n\n CoTryTask>> loadAllConfigs(kv::IReadOnlyTransaction &txn);\n\n CoTryTask> loadLatestConfig(kv::IReadOnlyTransaction &txn, flat::NodeType type);\n\n CoTryTask> loadConfig(kv::IReadOnlyTransaction &txn,\n flat::NodeType type,\n flat::ConfigVersion version);\n\n CoTryTask storeChainTable(kv::IReadWriteTransaction &txn, const flat::ChainTable &chainTable);\n\n CoTryTask> loadAllChainTables(kv::IReadOnlyTransaction &txn);\n\n CoTryTask storeChainInfo(kv::IReadWriteTransaction &txn, const flat::ChainInfo &chainInfo);\n\n CoTryTask> loadAllChains(kv::IReadOnlyTransaction &txn);\n\n // test only\n CoTryTask storeRoutingInfo(kv::IReadWriteTransaction &txn, const flat::RoutingInfo &routingInfo);\n\n CoTryTask storeUniversalTags(kv::IReadWriteTransaction &txn,\n std::string_view id,\n const std::vector &tags);\n\n CoTryTask> loadUniversalTags(kv::IReadOnlyTransaction &txn, std::string_view id);\n\n CoTryTask>>> loadAllUniversalTags(\n kv::IReadOnlyTransaction &txn);\n\n CoTryTask clearUniversalTags(kv::IReadWriteTransaction &txn, std::string_view id);\n\n CoTryTask shutdownAllChains(kv::IReadWriteTransaction &txn);\n\n CoTryTask> loadTargetInfo(kv::IReadOnlyTransaction &txn, flat::TargetId tid);\n\n CoTryTask storeTargetInfo(kv::IReadWriteTransaction &txn, const flat::TargetInfo &ti);\n\n CoTryTask clearTargetInfo(kv::IReadWriteTransaction &txn, flat::TargetId tid);\n\n CoTryTask> loadTargetsFrom(kv::IReadOnlyTransaction &txn, flat::TargetId tid);\n};\n} // namespace hf3fs::mgmtd\n"], ["/3FS/src/fdb/HybridKvEngine.h", "#pragma once\n\n#include \"common/kv/IKVEngine.h\"\n\nnamespace hf3fs::kv::fdb {\nstruct FDBConfig;\nclass FDBContext;\n} // namespace hf3fs::kv::fdb\n\nnamespace hf3fs::kv {\nstruct HybridKvEngineConfig;\nclass HybridKvEngine : public kv::IKVEngine {\n public:\n static std::shared_ptr fromMem();\n static std::shared_ptr fromFdb(const kv::fdb::FDBConfig &config);\n static std::shared_ptr from(bool useMemKV, const kv::fdb::FDBConfig &config);\n static std::shared_ptr from(const HybridKvEngineConfig &config);\n\n // use `config` if explicitly set, else fallback to use `useMemKV` and `fdbConfig`.\n static std::shared_ptr from(const HybridKvEngineConfig &config,\n bool useMemKV,\n const kv::fdb::FDBConfig &fdbConfig);\n\n // config contains:\n // 1. use_memkv (fallback mode)\n // 2. fdb (fallback mode)\n // 3. kv_engine (new)\n static std::shared_ptr fromSuperConfig(const auto &cfg) {\n return from(cfg.kv_engine(), cfg.use_memkv(), cfg.fdb());\n }\n\n ~HybridKvEngine();\n\n std::unique_ptr createReadonlyTransaction() override;\n std::unique_ptr createReadWriteTransaction() override;\n\n private:\n HybridKvEngine();\n\n kv::IKVEngine &pick() const;\n\n std::shared_ptr fdbContext_;\n std::vector> kvEngines_;\n};\n\n} // namespace hf3fs::kv\n"], ["/3FS/src/kv/LevelDBStore.h", "#pragma once\n\n#include \n#include \n#include \n#include \n\n#include \"LevelDBLogger.h\"\n#include \"kv/KVStore.h\"\n\nnamespace hf3fs::kv {\n\nclass LevelDBStore : public KVStore {\n public:\n LevelDBStore(const Config &config)\n : config_(config) {}\n\n // get value corresponding to key.\n Result get(std::string_view key) final;\n\n // get the first key which is greater than input key.\n Result iterateKeysWithPrefix(std::string_view prefix,\n uint32_t limit,\n IterateFunc func,\n std::optional *nextValidKey = nullptr) final;\n\n // put a key-value pair.\n Result put(std::string_view key, std::string_view value, bool sync = false) final;\n\n // remove a key-value pair.\n Result remove(std::string_view key) final;\n\n // batch operations.\n class LevelDBBatchOperations : public BatchOperations {\n public:\n LevelDBBatchOperations(LevelDBStore &db)\n : db_(db) {}\n // put a key-value pair.\n void put(std::string_view key, std::string_view value) override;\n // remove a key.\n void remove(std::string_view key) override;\n // clear a batch operations.\n void clear() override { writeBatch_.Clear(); }\n // commit a batch of operations.\n Result commit() override;\n // destroy self.\n void destroy() override;\n\n private:\n LevelDBStore &db_;\n leveldb::WriteBatch writeBatch_;\n };\n BatchOptionsPtr createBatchOps() override;\n\n // iterator.\n class LevelDBIterator : public Iterator {\n public:\n LevelDBIterator(std::unique_ptr it)\n : iterator_(std::move(it)) {}\n void seek(std::string_view key) override;\n void seekToFirst() override;\n void seekToLast() override;\n void next() override;\n Result status() const override;\n bool valid() const override;\n std::string_view key() const override;\n std::string_view value() const override;\n void destroy() override;\n\n private:\n std::unique_ptr iterator_;\n };\n IteratorPtr createIterator() override;\n\n // create a LevelDB instance.\n static std::unique_ptr create(const Config &config, const Options &options);\n\n protected:\n // initialize leveldb.\n Result init(const Options &optionsIn);\n\n private:\n const Config &config_;\n std::unique_ptr db_;\n std::unique_ptr cache_;\n std::unique_ptr logger_;\n};\n\n} // namespace hf3fs::kv\n"], ["/3FS/src/lib/common/PerProcTable.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"common/utils/Result.h\"\n#include \"common/utils/RobinHood.h\"\n\nnamespace hf3fs::lib {\ntemplate \nclass PerProcTable {\n public:\n using Item = T;\n using ItemPtr = std::shared_ptr;\n\n PerProcTable() = delete;\n PerProcTable(int p, int pp, size_t cap)\n : pid_(p),\n ppid_(pp),\n table_(cap) {\n free_.reserve(cap);\n }\n PerProcTable(const PerProcTable &rhs, int p, int pp, size_t cap)\n : pid_(p),\n ppid_(pp) {\n if (ppid_ == rhs.pid_) {\n {\n std::shared_lock lock(rhs.mtx_);\n std::vector t(std::max(rhs.table_.size(), cap));\n nextAvail_ = rhs.nextAvail_;\n for (int i = 0; i < nextAvail_; ++i) {\n t[i] = rhs.table_[i].load();\n }\n swap(t, table_);\n free_ = rhs.free_;\n }\n if (table_.size() < cap) { // we don't shrink the table or items may drop out\n free_.reserve(cap);\n }\n } else { // rhs is not our parent proc, so do not copy its fd table\n std::vector t(cap);\n swap(t, table_);\n }\n }\n int pid() const { return pid_; }\n int ppid() const { return ppid_; }\n hf3fs::Result at(int idx, bool check = true) {\n if (idx < 0) {\n XLOGF(DBG, \"bad index {}\", idx);\n return makeError(KeyError,\n fmt::format(\"invalid index {} to lookup in table for proc {} parent {}\", idx, pid_, ppid_));\n } else {\n {\n // std::shared_lock lock(mtx_);\n if (table_.size() < (size_t)idx) {\n XLOGF(DBG, \"invalid index {}\", idx);\n return makeError(KeyError, fmt::format(\"invalid index {} in table for proc {} parent {}\", idx, pid_, ppid_));\n } else {\n auto p = table_[idx].load();\n if (check && !p) {\n XLOGF(DBG, \"no item at index {}\", idx);\n return makeError(KeyError,\n fmt::format(\"index {} not found in table for proc {} parent {}\", idx, pid_, ppid_));\n }\n\n return p;\n }\n }\n }\n }\n void setAt(int idx, const ItemPtr &v) {\n std::unique_lock lock(mtx_);\n auto p = table_[idx].load();\n XLOGF(DBG,\n \"before set at idx {} table idx {} next avail {} free size {}\",\n idx,\n (void *)p.get(),\n nextAvail_,\n free_.size());\n if (!p) { // add to specific place\n if (idx >= nextAvail_) {\n for (auto i = nextAvail_; i < idx; ++i) {\n free_.push_back(i);\n }\n std::ranges::make_heap(free_, std::greater());\n nextAvail_ = idx + 1;\n } else {\n if (free_.size() == 1) {\n assert(free_[0] == idx);\n free_.clear();\n } else {\n *std::ranges::find(free_, idx) = free_.back();\n free_.pop_back();\n std::ranges::make_heap(free_, std::greater());\n }\n }\n }\n table_[idx] = v;\n }\n hf3fs::Result add(const ItemPtr &v) {\n std::unique_lock lock(mtx_);\n auto useFree = !free_.empty();\n if (!useFree && (size_t)nextAvail_ >= table_.size()) {\n return makeError(OverflowError,\n fmt::format(\"no free slot in table for proc {} parent {} table size {} next avail {}\",\n pid_,\n ppid_,\n table_.size(),\n nextAvail_));\n }\n auto idx = useFree ? free_.front() : nextAvail_++;\n if (useFree) {\n std::ranges::pop_heap(free_, std::greater());\n free_.pop_back();\n }\n auto p = table_[idx].load();\n\n XLOGF(DBG,\n \"idx {} use free {} next avail {} free size {} table idx {}\",\n idx,\n useFree,\n nextAvail_,\n free_.size(),\n (void *)p.get());\n assert(!p);\n table_[idx] = v;\n return idx;\n }\n void resetAt(int idx) {\n std::unique_lock lock(mtx_);\n table_[idx] = ItemPtr{};\n free_.push_back(idx);\n std::ranges::push_heap(free_, std::greater());\n XLOGF(DBG, \"reset idx {} next avail {} free size {} first free {}\", idx, nextAvail_, free_.size(), free_.front());\n }\n size_t size() const {\n std::shared_lock lock(mtx_);\n return (size_t)nextAvail_ - free_.size();\n }\n std::vector allUsed() const {\n std::vector used;\n used.reserve(table_.size());\n\n std::shared_lock lock(mtx_);\n for (int i = 1; i < (int)table_.size(); ++i) {\n if (table_[i].load()) {\n used.push_back(i);\n }\n }\n\n return used;\n }\n std::unique_lock lock() const { return std::unique_lock(mtx_); }\n\n private:\n int pid_;\n int ppid_;\n mutable std::shared_mutex mtx_;\n using AtomicItemPtr = folly::atomic_shared_ptr;\n std::vector table_;\n int nextAvail_ = 0;\n std::vector free_;\n};\n\ntemplate \nclass AllProcMap {\n public:\n using Table = PerProcTable;\n using TablePtr = std::shared_ptr;\n using ItemPtr = typename Table::ItemPtr;\n\n TablePtr procTable(int pid, int ppid, size_t cap) {\n TablePtr parentTable;\n {\n std::shared_lock lock(mtx_);\n auto it = map_.find(pid);\n if (it != map_.end()) {\n if (ppid == it->second->ppid()) {\n return it->second;\n } // else, same pid but diff proc, old proc must have died\n } else {\n auto it = map_.find(ppid);\n if (it != map_.end()) {\n parentTable = it->second;\n }\n }\n }\n\n TablePtr newTable;\n if (parentTable) {\n newTable = std::make_shared
(*parentTable, pid, ppid, cap);\n } else {\n newTable = std::make_shared
(pid, ppid, cap);\n }\n\n std::unique_lock lock(mtx_);\n return map_[pid] = std::move(newTable);\n }\n\n void removeProc(int pid) {\n std::unique_lock lock(mtx_);\n map_.erase(pid);\n }\n\n std::vector> allProcs() const {\n std::vector> procs;\n std::shared_lock lock(mtx_);\n procs.reserve(map_.size());\n for (auto &&p : map_) {\n if (p.first != 0) {\n procs.emplace_back(std::make_pair(p.first, p.second->ppid()));\n }\n }\n\n return procs;\n }\n\n private:\n mutable std::shared_mutex mtx_;\n robin_hood::unordered_map map_;\n};\n} // namespace hf3fs::lib\n"], ["/3FS/src/common/net/ib/IBConnect.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/net/ib/IBDevice.h\"\n#include \"common/serde/Serde.h\"\n#include \"common/utils/Result.h\"\n\nnamespace hf3fs::net {\n\nstruct IBDeviceInfo {\n public:\n struct PortInfo {\n SERDE_STRUCT_FIELD(port, uint8_t(0));\n SERDE_STRUCT_FIELD(zones, std::vector());\n SERDE_STRUCT_FIELD(link_layer, uint8_t(IBV_LINK_LAYER_UNSPECIFIED));\n };\n\n SERDE_STRUCT_FIELD(dev, uint8_t(0));\n SERDE_STRUCT_FIELD(dev_name, std::string());\n SERDE_STRUCT_FIELD(ports, std::vector());\n};\n\nstruct IBQueryReq {\n SERDE_STRUCT_FIELD(dummy, Void{});\n};\n\nstruct IBQueryRsp {\n SERDE_STRUCT_FIELD(devices, std::vector());\n\n public:\n struct Match {\n uint8_t remoteDev;\n std::string remoteDevName;\n uint8_t remotePort;\n IBDevice::Ptr localDev;\n uint8_t localPort;\n std::string zone;\n\n std::string describe() const {\n if (zone.empty()) {\n return fmt::format(\"{{local {}:{} remote {}:{}}}\", localDev->name(), localPort, remoteDevName, remotePort);\n } else {\n return fmt::format(\"{{local {}:{}, remote {}:{}, zone {}}}\",\n localDev->name(),\n localPort,\n remoteDevName,\n remotePort,\n zone);\n }\n }\n };\n Result selectDevice(const std::string &describe, uint64_t counter);\n void findMatchDevices(const std::string &describe,\n std::vector &ibMatches,\n std::vector &roceMatches,\n bool checkZone);\n};\n\nstruct IBConnectConfig {\n SERDE_STRUCT_FIELD(sl, uint8_t(0));\n SERDE_STRUCT_FIELD(traffic_class, uint8_t(0));\n SERDE_STRUCT_FIELD(gid_index, uint8_t(0)); // unused\n SERDE_STRUCT_FIELD(pkey_index, uint16_t(0));\n\n SERDE_STRUCT_FIELD(start_psn, uint32_t(0));\n SERDE_STRUCT_FIELD(min_rnr_timer, uint8_t(0));\n SERDE_STRUCT_FIELD(timeout, uint8_t(0));\n SERDE_STRUCT_FIELD(retry_cnt, uint8_t(0));\n SERDE_STRUCT_FIELD(rnr_retry, uint8_t(0));\n\n SERDE_STRUCT_FIELD(max_sge, uint32_t(0));\n SERDE_STRUCT_FIELD(max_rdma_wr, uint32_t(0));\n SERDE_STRUCT_FIELD(max_rdma_wr_per_post, uint32_t(0));\n SERDE_STRUCT_FIELD(max_rd_atomic, uint32_t(0));\n\n SERDE_STRUCT_FIELD(buf_size, uint32_t(0));\n SERDE_STRUCT_FIELD(send_buf_cnt, uint32_t(0));\n SERDE_STRUCT_FIELD(buf_ack_batch, uint32_t(0));\n SERDE_STRUCT_FIELD(buf_signal_batch, uint32_t(0));\n SERDE_STRUCT_FIELD(event_ack_batch, uint32_t(0));\n\n SERDE_STRUCT_FIELD(record_latency_per_peer, false);\n\n public:\n uint32_t qpAckBufs() const { return (send_buf_cnt + buf_ack_batch - 1) / buf_ack_batch + 4; }\n uint32_t qpMaxSendWR() const {\n return send_buf_cnt + qpAckBufs() + max_rdma_wr + 1 /* slot to send close msg */ + 1 /* slot to send check msg. */;\n }\n uint32_t qpMaxRecvWR() const { return send_buf_cnt + qpAckBufs() + 1 /* slot to recv close msg */; }\n uint32_t qpMaxCQEntries() const { return qpMaxSendWR() + qpMaxRecvWR(); }\n};\n\nstruct IBConnectIBInfo {\n SERDE_STRUCT_FIELD(lid, uint16_t(0));\n\n public:\n static constexpr auto kType = IBV_LINK_LAYER_INFINIBAND;\n};\n\nstruct IBConnectRoCEInfo {\n SERDE_STRUCT_FIELD(gid, ibv_gid{});\n\n public:\n static constexpr auto kType = IBV_LINK_LAYER_ETHERNET;\n};\n\nstruct IBConnectInfo {\n SERDE_STRUCT_FIELD(hostname, std::string());\n SERDE_STRUCT_FIELD(dev, uint8_t(0));\n SERDE_STRUCT_FIELD(dev_name, std::string());\n SERDE_STRUCT_FIELD(port, uint8_t(0));\n\n SERDE_STRUCT_FIELD(mtu, uint8_t(0));\n SERDE_STRUCT_FIELD(qp_num, uint32_t(0));\n SERDE_STRUCT_FIELD(linklayer, (std::variant()));\n\n public:\n auto getLinkerLayerType() const {\n return folly::variant_match(linklayer, [](auto &v) { return std::decay_t::kType; });\n }\n};\n\nstruct IBConnectReq : IBConnectInfo {\n SERDE_STRUCT_FIELD(target_dev, uint8_t(0));\n SERDE_STRUCT_FIELD(target_devname, std::string());\n SERDE_STRUCT_FIELD(target_port, uint8_t(0));\n SERDE_STRUCT_FIELD(config, IBConnectConfig());\n\n public:\n IBConnectReq()\n : IBConnectReq({}, 0, \"\", 0, {}) {}\n IBConnectReq(IBConnectInfo info,\n uint8_t target_dev,\n std::string target_devname,\n uint8_t target_port,\n IBConnectConfig config)\n : IBConnectInfo(info),\n target_dev(target_dev),\n target_devname(std::move(target_devname)),\n target_port(target_port),\n config(config) {}\n};\nstatic_assert(serde::SerializableToBytes && serde::SerializableToJson);\n\nstruct IBConnectRsp : IBConnectInfo {\n SERDE_STRUCT_FIELD(dummy, Void{});\n\n public:\n IBConnectRsp(IBConnectInfo info = {})\n : IBConnectInfo(info) {}\n};\nstatic_assert(serde::SerializableToBytes && serde::SerializableToJson);\n\n} // namespace hf3fs::net\n\ntemplate <>\nstruct hf3fs::serde::SerdeMethod {\n static std::string_view serdeTo(const ibv_gid &gid) {\n return std::string_view((const char *)&gid.raw[0], sizeof(ibv_gid::raw));\n }\n static Result serdeFrom(std::string_view s) {\n if (s.length() != sizeof(ibv_gid::raw)) {\n return makeError(StatusCode::kDataCorruption);\n } else {\n ibv_gid gid;\n memcpy(gid.raw, s.data(), s.length());\n return gid;\n }\n }\n};\n"], ["/3FS/src/analytics/SerdeObjectWriter.h", "#pragma once\n#include \n#include \n#include \n#include \n#include \n\n#include \"SerdeObjectVisitor.h\"\n#include \"SerdeSchemaBuilder.h\"\n#include \"common/serde/Serde.h\"\n#include \"common/utils/Nameof.hpp\"\n#include \"common/utils/StrongType.h\"\n#include \"common/utils/UtcTime.h\"\n\nnamespace hf3fs::analytics {\n\ntemplate \nclass SerdeObjectWriter : public BaseObjectVisitor> {\n public:\n SerdeObjectWriter(parquet::StreamWriter &&writer)\n : writer_(std::move(writer)),\n createTime_(UtcClock::now()) {}\n\n static std::shared_ptr open(const Path path,\n const bool append = false,\n const size_t maxRowGroupLength = 1'000'000,\n const std::vector &sortedColumns = {}) {\n // open file\n auto openStream = arrow::io::FileOutputStream::Open(path.string(), append);\n\n if (!openStream.ok()) {\n XLOGF(ERR, \"Failed to open file output stream: {}, error: {}\", path.string(), openStream.status().message());\n return nullptr;\n }\n\n std::shared_ptr outfile;\n PARQUET_ASSIGN_OR_THROW(outfile, openStream);\n\n // generate schema\n SerdeSchemaBuilder schemaBuilder;\n auto schemaNode = schemaBuilder.getSchema();\n\n if (schemaNode == nullptr) {\n return nullptr;\n }\n\n parquet::WriterProperties::Builder writerBuilder;\n writerBuilder.set_sorting_columns(sortedColumns);\n writerBuilder.max_row_group_length(maxRowGroupLength);\n writerBuilder.data_page_version(parquet::ParquetDataPageVersion::V2);\n\n // set global encoding and compression method\n // writerBuilder.encoding(parquet::Encoding::DELTA_BINARY_PACKED);\n writerBuilder.compression(parquet::Compression::ZSTD);\n\n // set encoding for string columns\n // for (int fieldIndex = 0; fieldIndex < schemaNode->field_count(); fieldIndex++) {\n // auto fieldNode = schemaNode->field(fieldIndex);\n // auto fieldType = fieldNode->logical_type();\n // if (fieldType->is_string()) writerBuilder.encoding(fieldNode->name(),\n // parquet::Encoding::DELTA_LENGTH_BYTE_ARRAY);\n // }\n\n try {\n auto fileWriter = parquet::ParquetFileWriter::Open(outfile, schemaNode, writerBuilder.build());\n if (fileWriter == nullptr) {\n XLOGF(ERR, \"Failed to open file writer: {}\", path.string());\n return nullptr;\n }\n\n parquet::StreamWriter streamWriter(std::move(fileWriter));\n return std::make_shared(std::move(streamWriter));\n\n } catch (const std::exception &ex) {\n XLOGF(ERR, \"Failed to create stream writer: {}, error: {}\", path.string(), ex.what());\n return nullptr;\n }\n }\n\n SerdeObjectWriter &operator<<(const SerdeType &v) {\n if (!bool(*this)) return *this;\n\n try {\n visit(\"\", v);\n writer_ << parquet::EndRow;\n } catch (const parquet::ParquetException &ex) {\n XLOGF(CRITICAL, \"Failed to write to parquet file, error: {}\", ex.what());\n isOk_ = false;\n }\n\n return *this;\n }\n\n void endRowGroup() { writer_.EndRowGroup(); }\n\n UtcTime createTime() { return createTime_; }\n\n operator bool() const { return ok(); }\n\n bool ok() const { return isOk_; }\n\n public:\n // default\n template \n void visit(std::string_view k, const T &v) = delete;\n\n template \n requires std::is_arithmetic_v\n void visit(std::string_view k, const T &v) {\n XLOGF(DBG3, \"arithmetic visit({})\", k);\n writer_ << v;\n }\n\n template \n requires std::is_enum_v\n void visit(std::string_view k, const T &v) {\n XLOGF(DBG3, \"enum visit({})\", k);\n writer_ << (int32_t)v;\n }\n\n template \n void visit(std::string_view k, const T &v) {\n XLOGF(DBG3, \"string visit({})\", k);\n writer_ << v;\n }\n\n template \n void visit(std::string_view k, const T &v) {\n XLOGF(DBG3, \"strongtyped visit({})\", k);\n visit(k, v.toUnderType());\n }\n\n template \n void visit(std::string_view k, const T &val) {\n auto serialized = serde::SerdeMethod::serdeToReadable(val);\n XLOGF(DBG3,\n \"WithReadableSerdeMethod visit({}), serialized: {} {}\",\n k,\n nameof::nameof_type(),\n serialized);\n visit>(k, serialized);\n }\n\n template \n void visit(std::string_view k, const T &val) {\n auto serialized = serde::SerdeMethod::serdeTo(val);\n XLOGF(DBG3,\n \"WithSerdeMethod visit({}), serialized: {} {}\",\n k,\n nameof::nameof_type(),\n serialized);\n visit(k, serialized);\n }\n\n template \n void visit(std::string_view k, const T &v) {\n auto serialized = v.serdeToReadable();\n XLOGF(DBG3,\n \"WithReadableSerdeMemberMethod visit({}), serialized: {} {}\",\n k,\n nameof::nameof_type(),\n serialized);\n visit(k, serialized);\n }\n\n template \n void visit(std::string_view k, const T &v) {\n auto serialized = v.serdeTo();\n XLOGF(DBG3,\n \"WithSerdeMemberMethod visit({}), serialized: {} {}\",\n k,\n nameof::nameof_type(),\n serialized);\n visit(k, serialized);\n }\n\n template \n void visit(std::string_view k, const T &val) {\n XLOGF(DBG3, \"serdetype visit({})\", k);\n BaseObjectVisitor::visit(k, const_cast(val));\n }\n\n template \n requires is_specialization_of_v\n void visit(std::string_view k, const T &val) {\n XLOGF(DBG3, \"result visit({})\", k);\n std::string errorColumnName = std::string{k} + kResultErrorTypeColumnSuffix;\n\n if (val.hasValue()) {\n Status ok(StatusCode::kOK);\n visit(errorColumnName, ok);\n visit(k, val.value());\n } else {\n typename T::value_type value{};\n visit(errorColumnName, val.error());\n visit(k, value);\n }\n }\n\n template \n requires is_variant_v\n void visit(std::string_view k, const T &val) {\n XLOGF(DBG3, \"variant visit({})\", k);\n std::string valIdxColumnName = std::string{k} + kVariantValueIndexColumnSuffix;\n visit(valIdxColumnName, val.index());\n BaseObjectVisitor::visit(k, const_cast(val));\n }\n\n template \n requires is_vector_v || is_set_v\n void visit(std::string_view k, const T &val) {\n XLOGF(DBG3, \"container visit({})\", k);\n auto str = serde::toJsonString(val);\n writer_ << str;\n }\n\n template \n requires is_optional_v\n void visit(std::string_view k, const T &val) {\n XLOGF(DBG3, \"optional visit({})\", k);\n if (!val.has_value()) {\n writer_ << \"\";\n } else {\n auto str = serde::toJsonString(*val);\n writer_ << str;\n }\n }\n\n private:\n parquet::StreamWriter writer_;\n UtcTime createTime_;\n bool isOk_{true};\n};\n\ntemplate \nSerdeObjectWriter &operator<<(SerdeObjectWriter &writer, parquet::EndRowGroupType) {\n writer.endRowGroup();\n return writer;\n}\n\n} // namespace hf3fs::analytics\n"], ["/3FS/src/common/utils/CoLockManager.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/Shards.h\"\n\nnamespace hf3fs {\n\ntemplate \nclass CoLockManager {\n struct State {\n std::string tag;\n folly::coro::Baton &baton;\n };\n using Queue = std::queue;\n using Map = std::unordered_map;\n using It = typename Map::iterator;\n\n public:\n struct Guard {\n static constexpr auto kInvalidPos = std::numeric_limits::max();\n Guard(CoLockManager &manager, folly::coro::Baton &baton, std::size_t pos, It it, std::string currentTag)\n : manager_(manager),\n baton_(baton),\n pos_(pos),\n it_(it),\n currentTag_(std::move(currentTag)) {}\n Guard(const Guard &) = delete;\n Guard(Guard &&o)\n : manager_(o.manager_),\n baton_(o.baton_),\n pos_(std::exchange(o.pos_, kInvalidPos)),\n it_(o.it_),\n currentTag_(std::move(o.currentTag_)) {}\n ~Guard() {\n if (pos_ != kInvalidPos) {\n if (!locked()) {\n folly::coro::blockingWait(lock());\n }\n manager_.unlock(baton_, pos_, it_);\n }\n }\n\n // check locked or not.\n bool locked() const { return baton_.ready(); }\n\n // get current locked tag.\n auto ¤tTag() const { return currentTag_; }\n\n // lock.\n [[nodiscard]] CoTask lock() { co_await baton_; }\n\n private:\n CoLockManager &manager_;\n folly::coro::Baton &baton_;\n std::size_t pos_;\n It it_;\n std::string currentTag_;\n };\n\n auto lock(folly::coro::Baton &baton, const std::string &key, const std::string &tag = \"\") {\n auto pos = shards_.position(key);\n auto [it, succ, currentTag] = shards_.withLockAt(\n [&](Map &map) {\n auto [it, succ] = map.emplace(key, Queue{});\n it->second.push({tag, baton});\n return std::make_tuple(it, succ, it->second.front().tag);\n },\n pos);\n if (succ) {\n baton.post();\n }\n return Guard{*this, baton, pos, it, std::move(currentTag)};\n }\n\n auto tryLock(folly::coro::Baton &baton, const std::string &key, const std::string &tag = \"\") {\n auto pos = shards_.position(key);\n auto [it, succ, currentTag] = shards_.withLockAt(\n [&](Map &map) {\n auto [it, succ] = map.emplace(key, Queue{});\n if (succ) {\n it->second.push({tag, baton});\n }\n return std::make_tuple(it, succ, succ ? std::string{} : it->second.front().tag);\n },\n pos);\n if (succ) {\n baton.post();\n }\n return Guard{*this, baton, succ ? pos : Guard::kInvalidPos, it, std::move(currentTag)};\n }\n\n protected:\n void unlock(folly::coro::Baton &baton, size_t pos, It it) {\n shards_.withLockAt(\n [&](Map &map) {\n auto &queue = it->second;\n if (UNLIKELY(queue.empty() || &queue.front().baton != &baton)) {\n assert(false);\n }\n queue.pop();\n if (!queue.empty()) {\n queue.front().baton.post();\n } else {\n map.erase(it);\n }\n },\n pos);\n }\n\n private:\n Shards shards_;\n};\n\n} // namespace hf3fs\n"], ["/3FS/src/storage/worker/DumpWorker.h", "#pragma once\n\n#include \n#include \n#include \n#include \n\n#include \"fbs/storage/Common.h\"\n#include \"storage/service/TargetMap.h\"\n\nnamespace hf3fs::storage {\n\nstruct Components;\n\nclass DumpWorker {\n public:\n struct Config : ConfigBase {\n CONFIG_HOT_UPDATED_ITEM(dump_root_path, Path{});\n CONFIG_HOT_UPDATED_ITEM(dump_interval, 1_d);\n CONFIG_HOT_UPDATED_ITEM(high_cpu_usage_threshold, 100); // num of cores.\n };\n\n DumpWorker(const Config &config, Components &components);\n\n // start dump worker.\n Result start(flat::NodeId nodeId);\n\n // stop dump worker. End all tasks immediately.\n Result stopAndJoin();\n\n protected:\n void loop();\n\n Result dump(const Path &rootPath);\n\n Result profilerStart(const Path &rootPath);\n\n private:\n ConstructLog<\"storage::DumpWorker\"> constructLog_;\n const Config &config_;\n Components &components_;\n folly::CPUThreadPoolExecutor executors_;\n\n std::mutex mutex_;\n std::condition_variable cond_;\n std::atomic stopping_ = false;\n std::atomic started_ = false;\n std::atomic stopped_ = false;\n flat::NodeId nodeId_{};\n};\n\n} // namespace hf3fs::storage\n"], ["/3FS/src/meta/store/ops/SetAttr.h", "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/kv/ITransaction.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/Result.h\"\n#include \"common/utils/UtcTime.h\"\n#include \"fbs/meta/Schema.h\"\n#include \"fbs/meta/Service.h\"\n#include \"meta/base/Config.h\"\n#include \"meta/service/MetaOperator.h\"\n#include \"meta/store/Inode.h\"\n#include \"meta/store/Utils.h\"\n\nnamespace hf3fs::meta::server {\n\nclass SetAttr {\n public:\n static Result check(const Inode &inode, const SetAttrReq &req, const Config &config) {\n RETURN_ON_ERROR(req.valid());\n\n // permission check for setPermission\n if (inode.id.isTreeRoot() && (req.perm || req.uid || req.gid)) {\n XLOGF(WARN, \"Don't allow change permission of tree root {}!\", inode.id);\n return makeError(MetaCode::kNoPermission, fmt::format(\"Don't allow change permission of {}\", inode.id));\n }\n if (req.iflags.has_value() && *req.iflags != inode.acl.iflags) {\n auto setChainAllocation = !(inode.acl.iflags & FS_CHAIN_ALLOCATION_FL) && (*req.iflags & FS_CHAIN_ALLOCATION_FL);\n if (setChainAllocation && !config.iflags_chain_allocation()) {\n return makeError(MetaCode::kNoPermission, \"FS_CHAIN_ALLOCATION_FL disabled\");\n }\n auto setNewChunkEngine = !(inode.acl.iflags & FS_NEW_CHUNK_ENGINE) && (*req.iflags & FS_NEW_CHUNK_ENGINE);\n if (setNewChunkEngine && !config.iflags_chunk_engine()) {\n return makeError(MetaCode::kNoPermission, \"FS_NEW_CHUNK_ENGINE disabled\");\n }\n auto changed = *req.iflags ^ inode.acl.iflags;\n auto ownerChangeable = config.allow_owner_change_immutable() ? (uint32_t)(FS_HUGE_FILE_FL | FS_IMMUTABLE_FL)\n : (uint32_t)(FS_HUGE_FILE_FL);\n auto permCheck = req.user.isRoot() || (req.user.uid == inode.acl.uid && changed == (changed & ownerChangeable));\n if (!permCheck) {\n // NOTE: only allow root user set inode flags, file owner can use chattr +/- i, or set FS_HUGE_FILE_FL\n return makeError(MetaCode::kNoPermission, \"only root can set iflags\");\n }\n }\n if (req.perm.has_value() && *req.perm != inode.acl.perm && !req.user.isRoot() && req.user.uid != inode.acl.uid) {\n // man 2 chmod: The effective UID of the calling process must match the owner of the file, or the process must be\n // privileged (Linux: it must have the CAP_FOWNER capability).\n return makeError(MetaCode::kNoPermission, \"no perm to set perm\");\n }\n if (req.uid.has_value() && *req.uid != inode.acl.uid && !req.user.isRoot()) {\n // Only a privileged process (Linux: one with the CAP_CHOWN capability) may change the owner of a file.\n return makeError(MetaCode::kNoPermission, \"no perm to set uid\");\n }\n if (req.gid.has_value() && *req.gid != inode.acl.gid && !req.user.isRoot() &&\n (req.user.uid != inode.acl.uid || !req.user.inGroup(req.gid.value()))) {\n // The owner of a file may change the group of the file to any group of which that owner is a member. A\n // privileged process (Linux: with CAP_CHOWN) may change the group arbitrarily.\n return makeError(MetaCode::kNoPermission, \"no perm to set gid\");\n }\n\n // permission check for utimes\n // To set both file timestamps to the current time (i.e., times is NULL, or both tv_nsec fields specify UTIME_NOW),\n // either:\n // 1. the caller must have write access to the file;\n // 2. the caller's effective user ID must match the owner of the file; or\n // 3. the caller must have appropriate privileges.\n // NOTE: we use UtcTime(0) as UTIME_NOW\n auto cond1 = inode.acl.checkPermission(req.user, AccessType::WRITE).hasValue();\n auto cond2 = req.user.uid == inode.acl.uid;\n auto cond3 = req.user.isRoot();\n if (req.atime || req.mtime) {\n if ((req.atime && req.atime != SETATTR_TIME_NOW) || (req.mtime && req.mtime != SETATTR_TIME_NOW)) {\n // To make any change other than setting both timestamps to the current time (i.e., times is not NULL, and\n // neither tv_nsec field is UTIME_NOW and neither tv_nsec field is UTIME_OMIT), either condition 2 or 3 above\n // must apply.\n if (!cond2 && !cond3) {\n return makeError(MetaCode::kNoPermission);\n }\n } else {\n if (!cond1 && !cond2 && !cond3) {\n return makeError(MetaCode::kNoPermission);\n }\n }\n }\n\n // permission check for setLayout\n if (req.layout) {\n if (!inode.isDirectory()) {\n return makeError(MetaCode::kNotDirectory, \"setLayout but not directory\");\n }\n RETURN_ON_ERROR(inode.acl.checkPermission(req.user, AccessType::WRITE));\n }\n\n if (!inode.isFile() && req.dynStripe) {\n return makeError(MetaCode::kNotFile, \"extend dynStripe but not file\");\n }\n\n return Void{};\n }\n\n static bool apply(Inode &inode, const SetAttrReq &req, Duration resolution, uint32_t stripeGrowth) {\n // now we can do update.\n bool dirty = false;\n\n // setPermission\n dirty |= update(inode.acl.iflags, req.iflags);\n dirty |= update(inode.acl.uid, req.uid);\n dirty |= update(inode.acl.gid, req.gid);\n dirty |= update(inode.acl.perm, req.perm);\n // setLayout\n if (req.layout.has_value()) {\n dirty |= update(inode.asDirectory().layout, req.layout);\n }\n if (dirty) {\n update(inode.ctime, SETATTR_TIME_NOW, resolution, true /* cmp */);\n }\n // utimes\n dirty |= update(inode.atime, req.atime, resolution, false /* cmp */);\n dirty |= update(inode.mtime, req.mtime, resolution, false /* cmp */);\n\n // extend\n if (req.dynStripe && inode.asFile().dynStripe && inode.asFile().dynStripe < req.dynStripe) {\n XLOGF_IF(FATAL, !inode.isFile(), \"inode {} is not file\", inode);\n\n auto growth = std::max(2u, stripeGrowth);\n auto dynStripe = inode.asFile().dynStripe;\n while (dynStripe < std::min(req.dynStripe, inode.asFile().layout.stripeSize)) {\n dynStripe = std::min(dynStripe * growth, inode.asFile().layout.stripeSize);\n }\n dirty |= update(inode.asFile().dynStripe, dynStripe);\n }\n\n return dirty;\n }\n\n static bool update(UtcTime &v, std::optional nv, Duration resolution, bool cmp) {\n if (!nv) {\n return false;\n }\n if (*nv == SETATTR_TIME_NOW) {\n nv = UtcClock::now();\n }\n nv = nv->castGranularity(resolution);\n if (*nv != v && (!cmp || (*nv > v))) {\n v = *nv;\n return true;\n } else {\n return false;\n }\n }\n\n template \n static bool update(T &v, std::optional nv) {\n static_assert(!std::is_same_v);\n if (nv.has_value() && nv != v) {\n v = *nv;\n return true;\n } else {\n return false;\n }\n }\n\n template \n static bool update(T &v, T nv) {\n if (nv != v) {\n v = nv;\n return true;\n } else {\n return false;\n }\n }\n};\n\n} // namespace hf3fs::meta::server"], ["/3FS/src/client/cli/admin/AdminEnv.h", "#pragma once\n\n#include \"client/cli/common/IEnv.h\"\n#include \"client/core/CoreClient.h\"\n#include \"client/meta/MetaClient.h\"\n#include \"client/mgmtd/IMgmtdClientForAdmin.h\"\n#include \"client/storage/StorageClient.h\"\n#include \"common/kv/IKVEngine.h\"\n#include \"fbs/core/user/User.h\"\n\nnamespace hf3fs::client::cli {\nstruct AdminEnv : IEnv {\n flat::UserInfo userInfo{flat::Uid{0}, flat::Gid{0}, \"\"};\n meta::InodeId currentDirId = meta::InodeId::root();\n String currentDir = \"/\";\n\n std::function()> clientGetter;\n std::function()> metaClientGetter;\n std::function()> kvEngineGetter;\n std::function()> mgmtdClientGetter;\n std::function()> unsafeMgmtdClientGetter;\n std::function()> storageClientGetter;\n std::function()> coreClientGetter;\n};\n} // namespace hf3fs::client::cli\n"], ["/3FS/src/client/mgmtd/MgmtdClientForClient.h", "#pragma once\n\n#include \"CommonMgmtdClient.h\"\n#include \"IMgmtdClientForClient.h\"\n\nnamespace hf3fs::client {\nclass MgmtdClientForClient : public CommonMgmtdClient {\n public:\n struct Config : MgmtdClient::Config {\n Config() {\n set_enable_auto_refresh(true);\n set_enable_auto_heartbeat(false);\n set_enable_auto_extend_client_session(true);\n }\n };\n\n explicit MgmtdClientForClient(std::shared_ptr client)\n : CommonMgmtdClient(std::move(client)) {}\n\n MgmtdClientForClient(String clusterId,\n std::unique_ptr stubFactory,\n const Config &config)\n : CommonMgmtdClient(std::make_shared(std::move(clusterId), std::move(stubFactory), config)) {}\n\n CoTryTask extendClientSession() final { return client_->extendClientSession(); }\n\n void setClientSessionPayload(ClientSessionPayload payload) { client_->setClientSessionPayload(std::move(payload)); }\n\n void setConfigListener(ConfigListener listener) final { client_->setClientConfigListener(std::move(listener)); }\n};\n} // namespace hf3fs::client\n"], ["/3FS/src/kv/RocksDBStore.h", "#pragma once\n\n#include \n#include \n#include \n\n#include \"kv/KVStore.h\"\n\nnamespace hf3fs::kv {\n\nclass RocksDBStore : public KVStore {\n public:\n RocksDBStore(const Config &config)\n : config_(config) {}\n\n // get value corresponding to key.\n Result get(std::string_view key) final;\n\n // get the first key which is greater than input key.\n Result iterateKeysWithPrefix(std::string_view prefix,\n uint32_t limit,\n IterateFunc func,\n std::optional *nextValidKey = nullptr) final;\n\n // put a key-value pair.\n Result put(std::string_view key, std::string_view value, bool sync = false) final;\n\n // remove a key-value pair.\n Result remove(std::string_view key) final;\n\n // batch operations.\n class RocksDBBatchOperations : public BatchOperations {\n public:\n RocksDBBatchOperations(RocksDBStore &db)\n : db_(db) {}\n // put a key-value pair.\n void put(std::string_view key, std::string_view value) override;\n // remove a key.\n void remove(std::string_view key) override;\n // clear a batch operations.\n void clear() override { writeBatch_.Clear(); }\n // commit a batch of operations.\n Result commit() override;\n // destroy self.\n void destroy() override;\n\n private:\n RocksDBStore &db_;\n rocksdb_internal::WriteBatch writeBatch_;\n };\n BatchOptionsPtr createBatchOps() override;\n\n // iterator.\n class RocksDBIterator : public Iterator {\n public:\n RocksDBIterator(std::unique_ptr it)\n : iterator_(std::move(it)) {}\n void seek(std::string_view key) override;\n void seekToFirst() override;\n void seekToLast() override;\n void next() override;\n Result status() const override;\n bool valid() const override;\n std::string_view key() const override;\n std::string_view value() const override;\n void destroy() override;\n\n private:\n std::unique_ptr iterator_;\n };\n IteratorPtr createIterator() override;\n\n // create a RocksDB instance.\n static std::unique_ptr create(const Config &config, const Options &options);\n\n protected:\n // initialize rocksdb.\n Result init(const Options &optionsIn);\n\n private:\n const Config &config_;\n std::unique_ptr db_;\n};\n\n} // namespace hf3fs::kv\n"], ["/3FS/src/common/net/Waiter.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/net/Network.h\"\n#include \"common/net/RDMAControl.h\"\n#include \"common/net/Transport.h\"\n#include \"common/serde/MessagePacket.h\"\n#include \"common/utils/Duration.h\"\n#include \"common/utils/RobinHood.h\"\n#include \"common/utils/Shards.h\"\n#include \"common/utils/Status.h\"\n\nnamespace hf3fs::net {\n\n// Wake up the waiting caller.\nclass Waiter {\n public:\n // is singleton.\n static Waiter &instance();\n ~Waiter();\n\n struct Item {\n folly::coro::Baton baton;\n IOBufPtr buf;\n serde::MessagePacket<> packet;\n Status status = Status::OK;\n TransportPtr transport;\n RDMATransmissionLimiterPtr limiter;\n RelativeTime timestamp = RelativeTime::now();\n };\n\n size_t bind(Item &item) {\n thread_local size_t start = 0, end = 0;\n if (UNLIKELY(start >= end)) {\n start = uuid_idx_.fetch_add(kShardsSize);\n end = start + kShardsSize;\n }\n\n auto uuid = start++;\n shards_.withLock([&](Map &map) { map.emplace(uuid, item); }, uuid);\n return uuid;\n }\n\n bool setTransport(size_t uuid, TransportPtr transport) {\n return shards_.withLock(\n [&](Map &map) {\n auto it = map.find(uuid);\n if (it == map.end()) {\n return false;\n }\n it->second.transport = std::move(transport);\n return true;\n },\n uuid);\n }\n\n std::optional setTransmissionLimiterPtr(size_t uuid,\n const RDMATransmissionLimiterPtr &limiter,\n RelativeTime startTime) {\n return shards_.withLock(\n [&](Map &map) -> std::optional {\n auto it = map.find(uuid);\n if (it == map.end() || it->second.limiter) {\n return std::nullopt;\n }\n it->second.limiter = limiter;\n return startTime - std::exchange(it->second.timestamp, RelativeTime::now());\n },\n uuid);\n }\n\n void post(const serde::MessagePacket<> &packet, IOBufPtr buff) {\n auto item = find(packet.uuid);\n if (item) {\n item->buf = std::move(buff);\n item->packet = packet;\n if (item->limiter) {\n item->limiter->signal(RelativeTime::now() - item->timestamp);\n }\n item->baton.post();\n }\n }\n\n static void error(Item *item, Status status) {\n if (item) {\n item->status = status;\n if (item->limiter) {\n item->limiter->signal(RelativeTime::now() - item->timestamp);\n }\n item->baton.post();\n }\n }\n\n bool contains(size_t uuid) {\n return shards_.withLock([&](Map &map) { return map.contains(uuid); }, uuid);\n }\n\n void timeout(size_t uuid) { error(find(uuid), Status(RPCCode::kTimeout)); }\n void sendFail(size_t uuid) { error(find(uuid), Status(RPCCode::kSendFailed)); }\n\n void clearPendingRequestsOnTransportFailure(Transport *tr) {\n shards_.iterate([tr](Map &map) {\n for (auto it = map.begin(); it != map.end();) {\n Item *item = &it->second;\n if (item->transport.get() == tr) {\n error(item, Status(RPCCode::kTimeout));\n it = map.erase(it);\n } else {\n ++it;\n }\n }\n });\n }\n\n void schedule(uint64_t uuid, std::chrono::milliseconds timeout);\n\n private:\n Waiter();\n\n Item *find(size_t uuid) {\n return shards_.withLock(\n [&](Map &map) -> Item * {\n auto it = map.find(uuid);\n if (it == map.end()) {\n return nullptr;\n }\n auto item = &it->second;\n map.erase(it);\n return item;\n },\n uuid);\n }\n\n void run();\n\n private:\n std::atomic uuid_idx_{0};\n\n constexpr static auto kShardsBit = 8u;\n constexpr static auto kShardsSize = (1u << kShardsBit);\n using Map = robin_hood::unordered_map;\n Shards shards_;\n\n // for timer.\n struct Task {\n uint64_t uuid;\n int64_t runTime;\n bool operator<(const Task &o) const { return runTime > o.runTime; }\n };\n\n class TaskShard {\n public:\n bool schedule(uint64_t uuid, int64_t runTime);\n void exchangeTasks(std::vector &out);\n\n private:\n std::mutex mutex_;\n int64_t nearestRunTime_ = std::numeric_limits::max();\n std::vector tasks_;\n };\n\n std::atomic stop_ = false;\n constexpr static auto kTaskShardNum = 13u;\n std::array taskShards_;\n\n std::mutex mutex_;\n std::condition_variable cond_;\n int64_t nearestRunTime_ = std::numeric_limits::max();\n std::vector reserved_;\n\n std::jthread thread_;\n};\n\n} // namespace hf3fs::net\n"], ["/3FS/src/fbs/mgmtd/ChainRef.h", "#pragma once\n\n#include \n#include \n\n#include \"MgmtdTypes.h\"\n#include \"common/utils/StrongType.h\"\n\nnamespace hf3fs::flat {\n\nclass ChainRef {\n public:\n ChainRef() {}\n ChainRef(ChainTableId tableId, ChainTableVersion tableVer, uint64_t index)\n : chainTableId(tableId),\n chainTableVersion(tableVer),\n chainIndex(index) {}\n\n std::tuple decode() const {\n return std::make_tuple(chainTableId, chainTableVersion, chainIndex);\n }\n\n ChainTableId tableId() const { return chainTableId; }\n\n ChainTableVersion tableVersion() const { return chainTableVersion; }\n\n uint64_t index() const { return chainIndex; }\n\n auto operator<=>(const ChainRef &) const = default;\n\n private:\n ChainTableId chainTableId{0};\n ChainTableVersion chainTableVersion{0};\n uint64_t chainIndex{0};\n};\n} // namespace hf3fs::flat\n\nFMT_BEGIN_NAMESPACE\n\ntemplate <>\nstruct formatter : formatter {\n template \n auto format(const hf3fs::flat::ChainRef &ref, FormatContext &ctx) const {\n auto [id, v, i] = ref.decode();\n return fmt::format_to(ctx.out(), \"ChainRef({}@{}-{})\", id.toUnderType(), v.toUnderType(), i);\n }\n};\n\nFMT_END_NAMESPACE\n"], ["/3FS/src/common/logging/LogConfig.h", "#pragma once\n\n#include \n#include \n#include \n\n#include \"common/utils/ConfigBase.h\"\n#include \"common/utils/Size.h\"\n#include \"common/utils/String.h\"\n\nnamespace hf3fs::logging {\nstruct LogLevel {\n LogLevel() = default;\n LogLevel(folly::LogLevel l)\n : level(l) {}\n LogLevel(std::string_view s) { level = folly::stringToLogLevel(folly::StringPiece(s)); }\n\n String toString() const { return folly::logLevelToString(level); }\n operator folly::LogLevel() const { return level; }\n\n folly::LogLevel level = folly::LogLevel::INFO;\n};\n\nstruct LogCategoryConfig : public ConfigBase {\n CONFIG_ITEM(categories, std::vector{\".\"});\n CONFIG_ITEM(level, LogLevel(folly::LogLevel::INFO));\n CONFIG_ITEM(inherit, true);\n CONFIG_ITEM(propagate, LogLevel(folly::LogLevel::MIN_LEVEL));\n CONFIG_ITEM(handlers, std::vector());\n\n public:\n bool operator==(const LogCategoryConfig &o) const {\n return categories() == o.categories() && level() == o.level() && inherit() == o.inherit() &&\n propagate() == o.propagate() && handlers() == o.handlers();\n }\n\n bool operator!=(const LogCategoryConfig &o) const { return !(*this == o); }\n};\n\nstruct LogHandlerConfig : public ConfigBase {\n enum class WriterType {\n FILE,\n STREAM,\n EVENT,\n };\n enum class StreamType {\n STDOUT,\n STDERR,\n };\n CONFIG_ITEM(name, \"\");\n CONFIG_ITEM(writer_type, WriterType::FILE);\n // FILE options\n CONFIG_ITEM(file_path, \"\"); // leave empty if you want `setupLogConfig` to auto generate path\n CONFIG_ITEM(async, true);\n // ROTATE FILE options\n CONFIG_ITEM(rotate, true);\n CONFIG_ITEM(max_files, 100);\n CONFIG_ITEM(max_file_size, 10_MB);\n CONFIG_ITEM(rotate_on_open, false);\n // STREAM options\n CONFIG_ITEM(stream_type, StreamType::STDERR);\n // SHARED options\n CONFIG_ITEM(start_level, LogLevel(folly::LogLevel::MIN_LEVEL));\n\n public:\n bool operator==(const LogHandlerConfig &o) const {\n return name() == o.name() && writer_type() == o.writer_type() && file_path() == o.file_path() &&\n async() == o.async() && rotate() == o.rotate() && max_files() == o.max_files() &&\n max_file_size() == o.max_file_size() && rotate_on_open() == o.rotate_on_open() &&\n stream_type() == o.stream_type() && start_level() == o.start_level();\n }\n\n bool operator!=(const LogHandlerConfig &o) const { return !(*this == o); }\n};\n\nstruct LogConfig : public ConfigBase {\n static LogCategoryConfig makeRootCategoryConfig() {\n LogCategoryConfig cfg;\n cfg.set_categories({\".\"});\n cfg.set_level(folly::LogLevel::INFO);\n cfg.set_handlers({\"normal\", \"err\", \"fatal\"});\n return cfg;\n }\n\n static LogCategoryConfig makeEventCategoryConfig() {\n LogCategoryConfig cfg;\n cfg.set_categories(std::vector{\"eventlog\"});\n cfg.set_level(folly::LogLevel::INFO);\n cfg.set_propagate(folly::LogLevel::ERR);\n cfg.set_inherit(false);\n cfg.set_handlers({\"event\"});\n return cfg;\n }\n\n static LogHandlerConfig makeNormalHandlerConfig() {\n LogHandlerConfig cfg;\n cfg.set_name(\"normal\");\n cfg.set_async(true);\n cfg.set_start_level(folly::LogLevel::MIN_LEVEL);\n return cfg;\n }\n\n static LogHandlerConfig makeErrHandlerConfig() {\n LogHandlerConfig cfg;\n cfg.set_name(\"err\");\n cfg.set_async(false);\n cfg.set_start_level(folly::LogLevel::ERR);\n return cfg;\n }\n\n static LogHandlerConfig makeFatalHandlerConfig() {\n LogHandlerConfig cfg;\n cfg.set_name(\"fatal\");\n cfg.set_async(false);\n cfg.set_start_level(folly::LogLevel::FATAL);\n cfg.set_writer_type(LogHandlerConfig::WriterType::STREAM);\n cfg.set_stream_type(LogHandlerConfig::StreamType::STDERR);\n return cfg;\n }\n\n static LogHandlerConfig makeEventHandlerConfig() {\n LogHandlerConfig cfg;\n cfg.set_name(\"event\");\n cfg.set_writer_type(LogHandlerConfig::WriterType::EVENT);\n cfg.set_async(true);\n cfg.set_start_level(folly::LogLevel::INFO);\n return cfg;\n }\n\n CONFIG_HOT_UPDATED_ITEM(categories, std::vector({makeRootCategoryConfig()}));\n CONFIG_HOT_UPDATED_ITEM(\n handlers,\n std::vector({makeNormalHandlerConfig(), makeErrHandlerConfig(), makeFatalHandlerConfig()}));\n};\n\nString generateLogConfig(const LogConfig &c, String serverName);\n} // namespace hf3fs::logging\n"], ["/3FS/src/common/net/TransportPool.h", "#pragma once\n\n#include \n#include \n\n#include \"common/net/Transport.h\"\n#include \"common/utils/RobinHood.h\"\n#include \"common/utils/Shards.h\"\n\nnamespace hf3fs::net {\n\nclass IOWorker;\n\n// A set of transports to same address for load balance.\nclass TransportSet {\n public:\n static constexpr uint32_t kDefaultMaxConnections = 1;\n\n // return a transport randomly.\n TransportPtr acquire(uint32_t idx);\n\n // add a new transport to this set.\n void add(TransportPtr tr, uint32_t idx);\n\n // remove a transport from this set.\n bool remove(TransportPtr tr);\n\n // get all transports.\n auto &transports() { return transports_; }\n\n // check all transports.\n uint32_t checkAll(Duration expiredTime);\n\n // drop all transports.\n uint32_t dropAll();\n\n protected:\n using TransportMap = std::map;\n\n void ensureSize(uint32_t idx);\n\n TransportMap::iterator erase(TransportMap::iterator it);\n\n private:\n TransportMap transports_{};\n std::vector idxToTransport_{kDefaultMaxConnections, transports_.end()};\n};\n\nstruct TransportCacheKey {\n Address addr;\n uint32_t idx;\n bool operator==(const TransportCacheKey &o) const { return addr == o.addr && idx == o.idx; }\n};\n\n} // namespace hf3fs::net\n\ntemplate <>\nstruct std::hash {\n auto operator()(const hf3fs::net::TransportCacheKey &key) const {\n return std::hash{}(key.addr) ^ key.idx;\n }\n};\n\nnamespace hf3fs::net {\n\n// Maintain a map of addresses and transport.\nclass TransportPool {\n public:\n class Config : public ConfigBase {\n CONFIG_HOT_UPDATED_ITEM(max_connections, TransportSet::kDefaultMaxConnections);\n };\n TransportPool(const Config &config)\n : config_(config) {}\n\n ~TransportPool();\n\n // add a transport into pool. [thread-safe]\n void add(TransportPtr tr);\n\n // remove a transport from pool. [thread-safe]\n void remove(TransportPtr tr);\n\n // get the transport corresponding to the specified address. [thread-safe]\n // the bool value in pair indicates whether connecting is required.\n std::pair get(Address addr, IOWorker &io_worker);\n\n // drop all connections.\n void dropConnections(bool dropAll = true, bool dropIncome = false);\n\n // drop all connections to this addr.\n void dropConnections(Address addr);\n\n // drop connetions to peer.\n void checkConnections(Address addr, Duration expiredTime);\n\n private:\n const Config &config_;\n\n // sharding by address for better performance.\n constexpr static auto kShardsSize = 32u;\n using Map = robin_hood::unordered_map;\n Shards shards_;\n\n // thread local cache for better performance.\n folly::ThreadLocal>> tlsCache_;\n};\n\n} // namespace hf3fs::net\n"], ["/3FS/src/common/utils/Status.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"folly/Portability.h\"\n\nnamespace hf3fs {\n\n#if !FOLLY_X64 && !FOLLY_AARCH64\n#error \"The platform must be 64bit!\"\n#endif\nstatic_assert(std::endian::native == std::endian::little);\n\n// `Status` imitates `abseil::Status` which contains:\n// - code\n// - (optional) message\n// - (optional) payload of any type\nclass [[nodiscard]] Status {\n struct status_ok_t {};\n\n public:\n Status() = delete;\n explicit Status(status_code_t code)\n : data_(construct(code, nullptr)) {}\n Status(const Status &other) { *this = other; }\n Status(Status &&other) = default;\n\n constexpr static status_ok_t OK{};\n /* implicit */ Status(status_ok_t)\n : Status(StatusCode::kOK) {}\n\n Status(status_code_t code, std::string_view msg) {\n auto rep = std::make_unique();\n rep->message = msg;\n data_ = construct(code, std::move(rep));\n }\n\n Status(status_code_t code, std::string &&msg) {\n auto rep = std::make_unique();\n rep->message = std::move(msg);\n data_ = construct(code, std::move(rep));\n }\n\n Status(status_code_t code, const char *msg)\n : Status(code, std::string_view(msg)) {}\n\n template \n Status(status_code_t code, std::string_view msg, T &&payload)\n : Status(code, msg) {\n setPayload(std::forward(payload));\n }\n\n Status &operator=(const Status &other) {\n if (std::addressof(other) != this) {\n data_ = construct(other.code(), other.rep() ? std::make_unique(*other.rep()) : nullptr);\n }\n return *this;\n }\n Status &operator=(Status &&other) = default;\n\n status_code_t code() const { return reinterpret_cast(data_.get()) >> kPtrBits; }\n std::string_view message() const { return rep() ? std::string_view(rep()->message) : std::string_view(); }\n\n Status convert(status_code_t code) const {\n Status status = Status::OK;\n status.data_ = construct(code, rep() ? std::make_unique(*rep()) : nullptr);\n return status;\n }\n\n String describe() const {\n return rep() ? fmt::format(\"{}({}) {}\", StatusCode::toString(code()), code(), rep()->message)\n : fmt::format(\"{}({})\", StatusCode::toString(code()), code());\n }\n std::ostream &operator<<(std::ostream &os) const { return os << describe(); }\n\n bool isOK() const { return code() == StatusCode::kOK; }\n explicit operator bool() const { return isOK(); }\n\n bool hasPayload() const { return rep() && rep()->payload.has_value(); }\n\n template \n T *payload() {\n return std::any_cast(&rep()->payload);\n }\n\n template \n const T *payload() const {\n return std::any_cast(&rep()->payload);\n }\n\n template \n void setPayload(T &&payload) {\n ensuredRep()->payload = std::forward(payload);\n }\n\n template \n void emplacePayload(Args &&...args) {\n ensuredRep()->payload.emplace(std::forward(args)...);\n }\n\n void resetPayload() { rep() ? rep()->payload.reset() : void(); }\n\n private:\n static_assert(StatusCode::kOK == 0, \"StatusCode::kOK must be 0!\");\n static_assert(sizeof(status_code_t) == 2, \"The width of status_code_t must be 16b\");\n\n static constexpr auto kPtrBits = 48u;\n static constexpr auto kPtrMask = ((1ul << kPtrBits) - 1);\n\n struct StatusRep {\n String message;\n std::any payload;\n };\n struct StatusRepDeleter {\n void operator()(StatusRep *rep) { delete extractPtr(rep); }\n };\n using StatusPtr = std::unique_ptr;\n\n static StatusPtr construct(status_code_t code, std::unique_ptr rep) {\n return StatusPtr(\n reinterpret_cast(reinterpret_cast(rep.release()) | (uintptr_t(code) << kPtrBits)));\n }\n static StatusRep *extractPtr(StatusRep *rep) {\n return reinterpret_cast(reinterpret_cast(rep) & kPtrMask);\n }\n\n StatusRep *rep() { return extractPtr(data_.get()); }\n const StatusRep *rep() const { return extractPtr(data_.get()); }\n\n StatusRep *ensuredRep() {\n if (rep() == nullptr) {\n data_ = construct(code(), std::make_unique());\n }\n return rep();\n }\n\n private:\n StatusPtr data_; // |<-- low 48 bits: rep ptr -->|<-- high 16 bits: status code -->|\n};\n\nclass StatusException : public std::runtime_error {\n public:\n using std::runtime_error::runtime_error;\n explicit StatusException(Status status)\n : std::runtime_error(status.describe()),\n status_(std::move(status)) {}\n\n const Status &get() const { return status_; }\n Status &get() { return status_; }\n\n private:\n Status status_;\n};\n} // namespace hf3fs\n\nFMT_BEGIN_NAMESPACE\n\ntemplate <>\nstruct formatter : formatter {\n template \n auto format(const hf3fs::Status &status, FormatContext &ctx) const {\n auto msg = status.message();\n if (msg.empty()) {\n return fmt::format_to(ctx.out(), \"{}({})\", hf3fs::StatusCode::toString(status.code()), status.code());\n }\n return fmt::format_to(ctx.out(), \"{}({}) {}\", hf3fs::StatusCode::toString(status.code()), status.code(), msg);\n }\n};\n\nFMT_END_NAMESPACE\n"], ["/3FS/src/common/utils/RobinHood.h", "// ______ _____ ______ _________\n// ______________ ___ /_ ___(_)_______ ___ /_ ______ ______ ______ /\n// __ ___/_ __ \\__ __ \\__ / __ __ \\ __ __ \\_ __ \\_ __ \\_ __ /\n// _ / / /_/ /_ /_/ /_ / _ / / / _ / / // /_/ // /_/ // /_/ /\n// /_/ \\____/ /_.___/ /_/ /_/ /_/ ________/_/ /_/ \\____/ \\____/ \\__,_/\n// _/_____/\n//\n// Fast & memory efficient hashtable based on robin hood hashing for C++11/14/17/20\n// https://github.com/martinus/robin-hood-hashing\n//\n// Licensed under the MIT License .\n// SPDX-License-Identifier: MIT\n// Copyright (c) 2018-2021 Martin Ankerl \n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#ifndef ROBIN_HOOD_H_INCLUDED\n#define ROBIN_HOOD_H_INCLUDED\n\n// see https://semver.org/\n#define ROBIN_HOOD_VERSION_MAJOR 3 // for incompatible API changes\n#define ROBIN_HOOD_VERSION_MINOR 11 // for adding functionality in a backwards-compatible manner\n#define ROBIN_HOOD_VERSION_PATCH 5 // for backwards-compatible bug fixes\n\n#include \n#include \n#include \n#include \n#include \n#include // only to support hash of smart pointers\n#include \n#include \n#include \n#include \n\n#include \"memory/common/GlobalMemoryAllocator.h\"\n\n#if __cplusplus >= 201703L\n#include \n#endif\n\n// #define ROBIN_HOOD_LOG_ENABLED\n#ifdef ROBIN_HOOD_LOG_ENABLED\n#include \n#define ROBIN_HOOD_LOG(...) std::cout << __FUNCTION__ << \"@\" << __LINE__ << \": \" << __VA_ARGS__ << std::endl;\n#else\n#define ROBIN_HOOD_LOG(x)\n#endif\n\n// #define ROBIN_HOOD_TRACE_ENABLED\n#ifdef ROBIN_HOOD_TRACE_ENABLED\n#include \n#define ROBIN_HOOD_TRACE(...) std::cout << __FUNCTION__ << \"@\" << __LINE__ << \": \" << __VA_ARGS__ << std::endl;\n#else\n#define ROBIN_HOOD_TRACE(x)\n#endif\n\n// #define ROBIN_HOOD_COUNT_ENABLED\n#ifdef ROBIN_HOOD_COUNT_ENABLED\n#include \n#define ROBIN_HOOD_COUNT(x) ++counts().x;\nnamespace robin_hood {\nstruct Counts {\n uint64_t shiftUp{};\n uint64_t shiftDown{};\n};\ninline std::ostream &operator<<(std::ostream &os, Counts const &c) {\n return os << c.shiftUp << \" shiftUp\" << std::endl << c.shiftDown << \" shiftDown\" << std::endl;\n}\n\nstatic Counts &counts() {\n static Counts counts{};\n return counts;\n}\n} // namespace robin_hood\n#else\n#define ROBIN_HOOD_COUNT(x)\n#endif\n\n// all non-argument macros should use this facility. See\n// https://www.fluentcpp.com/2019/05/28/better-macros-better-flags/\n#define ROBIN_HOOD(x) ROBIN_HOOD_PRIVATE_DEFINITION_##x()\n\n// mark unused members with this macro\n#define ROBIN_HOOD_UNUSED(identifier)\n\n// bitness\n#if SIZE_MAX == UINT32_MAX\n#define ROBIN_HOOD_PRIVATE_DEFINITION_BITNESS() 32\n#elif SIZE_MAX == UINT64_MAX\n#define ROBIN_HOOD_PRIVATE_DEFINITION_BITNESS() 64\n#else\n#error Unsupported bitness\n#endif\n\n// endianess\n#ifdef _MSC_VER\n#define ROBIN_HOOD_PRIVATE_DEFINITION_LITTLE_ENDIAN() 1\n#define ROBIN_HOOD_PRIVATE_DEFINITION_BIG_ENDIAN() 0\n#else\n#define ROBIN_HOOD_PRIVATE_DEFINITION_LITTLE_ENDIAN() (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)\n#define ROBIN_HOOD_PRIVATE_DEFINITION_BIG_ENDIAN() (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)\n#endif\n\n// inline\n#ifdef _MSC_VER\n#define ROBIN_HOOD_PRIVATE_DEFINITION_NOINLINE() __declspec(noinline)\n#else\n#define ROBIN_HOOD_PRIVATE_DEFINITION_NOINLINE() __attribute__((noinline))\n#endif\n\n// exceptions\n#if !defined(__cpp_exceptions) && !defined(__EXCEPTIONS) && !defined(_CPPUNWIND)\n#define ROBIN_HOOD_PRIVATE_DEFINITION_HAS_EXCEPTIONS() 0\n#else\n#define ROBIN_HOOD_PRIVATE_DEFINITION_HAS_EXCEPTIONS() 1\n#endif\n\n// count leading/trailing bits\n#if !defined(ROBIN_HOOD_DISABLE_INTRINSICS)\n#ifdef _MSC_VER\n#if ROBIN_HOOD(BITNESS) == 32\n#define ROBIN_HOOD_PRIVATE_DEFINITION_BITSCANFORWARD() _BitScanForward\n#else\n#define ROBIN_HOOD_PRIVATE_DEFINITION_BITSCANFORWARD() _BitScanForward64\n#endif\n#include \n#pragma intrinsic(ROBIN_HOOD(BITSCANFORWARD))\n#define ROBIN_HOOD_COUNT_TRAILING_ZEROES(x) \\\n [](size_t mask) noexcept -> int { \\\n unsigned long index; \\\n return ROBIN_HOOD(BITSCANFORWARD)(&index, mask) ? static_cast(index) : ROBIN_HOOD(BITNESS); \\\n }(x)\n#else\n#if ROBIN_HOOD(BITNESS) == 32\n#define ROBIN_HOOD_PRIVATE_DEFINITION_CTZ() __builtin_ctzl\n#define ROBIN_HOOD_PRIVATE_DEFINITION_CLZ() __builtin_clzl\n#else\n#define ROBIN_HOOD_PRIVATE_DEFINITION_CTZ() __builtin_ctzll\n#define ROBIN_HOOD_PRIVATE_DEFINITION_CLZ() __builtin_clzll\n#endif\n#define ROBIN_HOOD_COUNT_LEADING_ZEROES(x) ((x) ? ROBIN_HOOD(CLZ)(x) : ROBIN_HOOD(BITNESS))\n#define ROBIN_HOOD_COUNT_TRAILING_ZEROES(x) ((x) ? ROBIN_HOOD(CTZ)(x) : ROBIN_HOOD(BITNESS))\n#endif\n#endif\n\n// fallthrough\n#ifndef __has_cpp_attribute // For backwards compatibility\n#define __has_cpp_attribute(x) 0\n#endif\n#if __has_cpp_attribute(clang::fallthrough)\n#define ROBIN_HOOD_PRIVATE_DEFINITION_FALLTHROUGH() [[clang::fallthrough]]\n#elif __has_cpp_attribute(gnu::fallthrough)\n#define ROBIN_HOOD_PRIVATE_DEFINITION_FALLTHROUGH() [[gnu::fallthrough]]\n#else\n#define ROBIN_HOOD_PRIVATE_DEFINITION_FALLTHROUGH()\n#endif\n\n// likely/unlikely\n#ifdef _MSC_VER\n#define ROBIN_HOOD_LIKELY(condition) condition\n#define ROBIN_HOOD_UNLIKELY(condition) condition\n#else\n#define ROBIN_HOOD_LIKELY(condition) __builtin_expect(condition, 1)\n#define ROBIN_HOOD_UNLIKELY(condition) __builtin_expect(condition, 0)\n#endif\n\n// detect if native wchar_t type is availiable in MSVC\n#ifdef _MSC_VER\n#ifdef _NATIVE_WCHAR_T_DEFINED\n#define ROBIN_HOOD_PRIVATE_DEFINITION_HAS_NATIVE_WCHART() 1\n#else\n#define ROBIN_HOOD_PRIVATE_DEFINITION_HAS_NATIVE_WCHART() 0\n#endif\n#else\n#define ROBIN_HOOD_PRIVATE_DEFINITION_HAS_NATIVE_WCHART() 1\n#endif\n\n// detect if MSVC supports the pair(std::piecewise_construct_t,...) consructor being constexpr\n#ifdef _MSC_VER\n#if _MSC_VER <= 1900\n#define ROBIN_HOOD_PRIVATE_DEFINITION_BROKEN_CONSTEXPR() 1\n#else\n#define ROBIN_HOOD_PRIVATE_DEFINITION_BROKEN_CONSTEXPR() 0\n#endif\n#else\n#define ROBIN_HOOD_PRIVATE_DEFINITION_BROKEN_CONSTEXPR() 0\n#endif\n\n// helpers for C++ versions, see https://gcc.gnu.org/onlinedocs/cpp/Standard-Predefined-Macros.html\n#define ROBIN_HOOD_PRIVATE_DEFINITION_CXX() __cplusplus\n#define ROBIN_HOOD_PRIVATE_DEFINITION_CXX98() 199711L\n#define ROBIN_HOOD_PRIVATE_DEFINITION_CXX11() 201103L\n#define ROBIN_HOOD_PRIVATE_DEFINITION_CXX14() 201402L\n#define ROBIN_HOOD_PRIVATE_DEFINITION_CXX17() 201703L\n\n#if ROBIN_HOOD(CXX) >= ROBIN_HOOD(CXX17)\n#define ROBIN_HOOD_PRIVATE_DEFINITION_NODISCARD() [[nodiscard]]\n#else\n#define ROBIN_HOOD_PRIVATE_DEFINITION_NODISCARD()\n#endif\n\nnamespace robin_hood {\n\n#if ROBIN_HOOD(CXX) >= ROBIN_HOOD(CXX14)\n#define ROBIN_HOOD_STD std\n#else\n\n// c++11 compatibility layer\nnamespace ROBIN_HOOD_STD {\ntemplate \nstruct alignment_of : std::integral_constant::type)> {};\n\ntemplate \nclass integer_sequence {\n public:\n using value_type = T;\n static_assert(std::is_integral::value, \"not integral type\");\n static constexpr std::size_t size() noexcept { return sizeof...(Ints); }\n};\ntemplate \nusing index_sequence = integer_sequence;\n\nnamespace detail_ {\ntemplate \nstruct IntSeqImpl {\n using TValue = T;\n static_assert(std::is_integral::value, \"not integral type\");\n static_assert(Begin >= 0 && Begin < End, \"unexpected argument (Begin<0 || Begin<=End)\");\n\n template \n struct IntSeqCombiner;\n\n template \n struct IntSeqCombiner, integer_sequence> {\n using TResult = integer_sequence;\n };\n\n using TResult = typename IntSeqCombiner<\n typename IntSeqImpl::TResult,\n typename IntSeqImpl::TResult>::TResult;\n};\n\ntemplate \nstruct IntSeqImpl {\n using TValue = T;\n static_assert(std::is_integral::value, \"not integral type\");\n static_assert(Begin >= 0, \"unexpected argument (Begin<0)\");\n using TResult = integer_sequence;\n};\n\ntemplate \nstruct IntSeqImpl {\n using TValue = T;\n static_assert(std::is_integral::value, \"not integral type\");\n static_assert(Begin >= 0, \"unexpected argument (Begin<0)\");\n using TResult = integer_sequence;\n};\n} // namespace detail_\n\ntemplate \nusing make_integer_sequence = typename detail_::IntSeqImpl::TResult;\n\ntemplate \nusing make_index_sequence = make_integer_sequence;\n\ntemplate \nusing index_sequence_for = make_index_sequence;\n\n} // namespace ROBIN_HOOD_STD\n\n#endif\n\nnamespace detail {\n\n// make sure we static_cast to the correct type for hash_int\n#if ROBIN_HOOD(BITNESS) == 64\nusing SizeT = uint64_t;\n#else\nusing SizeT = uint32_t;\n#endif\n\ntemplate \nT rotr(T x, unsigned k) {\n return (x >> k) | (x << (8U * sizeof(T) - k));\n}\n\n// This cast gets rid of warnings like \"cast from 'uint8_t*' {aka 'unsigned char*'} to\n// 'uint64_t*' {aka 'long unsigned int*'} increases required alignment of target type\". Use with\n// care!\ntemplate \ninline T reinterpret_cast_no_cast_align_warning(void *ptr) noexcept {\n return reinterpret_cast(ptr);\n}\n\ntemplate \ninline T reinterpret_cast_no_cast_align_warning(void const *ptr) noexcept {\n return reinterpret_cast(ptr);\n}\n\n// make sure this is not inlined as it is slow and dramatically enlarges code, thus making other\n// inlinings more difficult. Throws are also generally the slow path.\ntemplate \n[[noreturn]] ROBIN_HOOD(NOINLINE)\n#if ROBIN_HOOD(HAS_EXCEPTIONS)\n void doThrow(Args &&...args) {\n // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay)\n throw E(std::forward(args)...);\n}\n#else\n void doThrow(Args &&...ROBIN_HOOD_UNUSED(args) /*unused*/) {\n abort();\n}\n#endif\n\ntemplate \nT *assertNotNull(T *t, Args &&...args) {\n if (ROBIN_HOOD_UNLIKELY(nullptr == t)) {\n doThrow(std::forward(args)...);\n }\n return t;\n}\n\ntemplate \ninline T unaligned_load(void const *ptr) noexcept {\n // using memcpy so we don't get into unaligned load problems.\n // compiler should optimize this very well anyways.\n T t;\n std::memcpy(&t, ptr, sizeof(T));\n return t;\n}\n\n// Allocates bulks of memory for objects of type T. This deallocates the memory in the destructor,\n// and keeps a linked list of the allocated memory around. Overhead per allocation is the size of a\n// pointer.\ntemplate \nclass BulkPoolAllocator {\n public:\n BulkPoolAllocator() noexcept = default;\n\n // does not copy anything, just creates a new allocator.\n BulkPoolAllocator(const BulkPoolAllocator &ROBIN_HOOD_UNUSED(o) /*unused*/) noexcept\n : mHead(nullptr),\n mListForFree(nullptr) {}\n\n BulkPoolAllocator(BulkPoolAllocator &&o) noexcept\n : mHead(o.mHead),\n mListForFree(o.mListForFree) {\n o.mListForFree = nullptr;\n o.mHead = nullptr;\n }\n\n BulkPoolAllocator &operator=(BulkPoolAllocator &&o) noexcept {\n reset();\n mHead = o.mHead;\n mListForFree = o.mListForFree;\n o.mListForFree = nullptr;\n o.mHead = nullptr;\n return *this;\n }\n\n BulkPoolAllocator &\n // NOLINTNEXTLINE(bugprone-unhandled-self-assignment,cert-oop54-cpp)\n operator=(const BulkPoolAllocator &ROBIN_HOOD_UNUSED(o) /*unused*/) noexcept {\n // does not do anything\n return *this;\n }\n\n ~BulkPoolAllocator() noexcept { reset(); }\n\n // Deallocates all allocated memory.\n void reset() noexcept {\n while (mListForFree) {\n T *tmp = *mListForFree;\n ROBIN_HOOD_LOG(\"hf3fs::memory::deallocate\")\n hf3fs::memory::deallocate(mListForFree);\n mListForFree = reinterpret_cast_no_cast_align_warning(tmp);\n }\n mHead = nullptr;\n }\n\n // allocates, but does NOT initialize. Use in-place new constructor, e.g.\n // T* obj = pool.allocate();\n // ::new (static_cast(obj)) T();\n T *allocate() {\n T *tmp = mHead;\n if (!tmp) {\n tmp = performAllocation();\n }\n\n mHead = *reinterpret_cast_no_cast_align_warning(tmp);\n return tmp;\n }\n\n // does not actually deallocate but puts it in store.\n // make sure you have already called the destructor! e.g. with\n // obj->~T();\n // pool.deallocate(obj);\n void deallocate(T *obj) noexcept {\n *reinterpret_cast_no_cast_align_warning(obj) = mHead;\n mHead = obj;\n }\n\n // Adds an already allocated block of memory to the allocator. This allocator is from now on\n // responsible for freeing the data (with free()). If the provided data is not large enough to\n // make use of, it is immediately freed. Otherwise it is reused and freed in the destructor.\n void addOrFree(void *ptr, const size_t numBytes) noexcept {\n // calculate number of available elements in ptr\n if (numBytes < ALIGNMENT + ALIGNED_SIZE) {\n // not enough data for at least one element. Free and return.\n ROBIN_HOOD_LOG(\"hf3fs::memory::deallocate\")\n hf3fs::memory::deallocate(ptr);\n } else {\n ROBIN_HOOD_LOG(\"add to buffer\")\n add(ptr, numBytes);\n }\n }\n\n void swap(BulkPoolAllocator &other) noexcept {\n using std::swap;\n swap(mHead, other.mHead);\n swap(mListForFree, other.mListForFree);\n }\n\n private:\n // iterates the list of allocated memory to calculate how many to alloc next.\n // Recalculating this each time saves us a size_t member.\n // This ignores the fact that memory blocks might have been added manually with addOrFree. In\n // practice, this should not matter much.\n ROBIN_HOOD(NODISCARD) size_t calcNumElementsToAlloc() const noexcept {\n auto tmp = mListForFree;\n size_t numAllocs = MinNumAllocs;\n\n while (numAllocs * 2 <= MaxNumAllocs && tmp) {\n auto x = reinterpret_cast(tmp);\n tmp = *x;\n numAllocs *= 2;\n }\n\n return numAllocs;\n }\n\n // WARNING: Underflow if numBytes < ALIGNMENT! This is guarded in addOrFree().\n void add(void *ptr, const size_t numBytes) noexcept {\n const size_t numElements = (numBytes - ALIGNMENT) / ALIGNED_SIZE;\n\n auto data = reinterpret_cast(ptr);\n\n // link free list\n auto x = reinterpret_cast(data);\n *x = mListForFree;\n mListForFree = data;\n\n // create linked list for newly allocated data\n auto *const headT = reinterpret_cast_no_cast_align_warning(reinterpret_cast(ptr) + ALIGNMENT);\n\n auto *const head = reinterpret_cast(headT);\n\n // Visual Studio compiler automatically unrolls this loop, which is pretty cool\n for (size_t i = 0; i < numElements; ++i) {\n *reinterpret_cast_no_cast_align_warning(head + i * ALIGNED_SIZE) = head + (i + 1) * ALIGNED_SIZE;\n }\n\n // last one points to 0\n *reinterpret_cast_no_cast_align_warning(head + (numElements - 1) * ALIGNED_SIZE) = mHead;\n mHead = headT;\n }\n\n // Called when no memory is available (mHead == 0).\n // Don't inline this slow path.\n ROBIN_HOOD(NOINLINE) T *performAllocation() {\n size_t const numElementsToAlloc = calcNumElementsToAlloc();\n\n // alloc new memory: [prev |T, T, ... T]\n size_t const bytes = ALIGNMENT + ALIGNED_SIZE * numElementsToAlloc;\n ROBIN_HOOD_LOG(\"hf3fs::memory::allocate \" << bytes << \" = \" << ALIGNMENT << \" + \" << ALIGNED_SIZE << \" * \"\n << numElementsToAlloc)\n add(assertNotNull(hf3fs::memory::allocate(bytes)), bytes);\n return mHead;\n }\n\n // enforce byte alignment of the T's\n#if ROBIN_HOOD(CXX) >= ROBIN_HOOD(CXX14)\n static constexpr size_t ALIGNMENT = (std::max)(std::alignment_of::value, std::alignment_of::value);\n#else\n static const size_t ALIGNMENT = (ROBIN_HOOD_STD::alignment_of::value > ROBIN_HOOD_STD::alignment_of::value)\n ? ROBIN_HOOD_STD::alignment_of::value\n : +ROBIN_HOOD_STD::alignment_of::value; // the + is for walkarround\n#endif\n\n static constexpr size_t ALIGNED_SIZE = ((sizeof(T) - 1) / ALIGNMENT + 1) * ALIGNMENT;\n\n static_assert(MinNumAllocs >= 1, \"MinNumAllocs\");\n static_assert(MaxNumAllocs >= MinNumAllocs, \"MaxNumAllocs\");\n static_assert(ALIGNED_SIZE >= sizeof(T *), \"ALIGNED_SIZE\");\n static_assert(0 == (ALIGNED_SIZE % sizeof(T *)), \"ALIGNED_SIZE mod\");\n static_assert(ALIGNMENT >= sizeof(T *), \"ALIGNMENT\");\n\n T *mHead{nullptr};\n T **mListForFree{nullptr};\n};\n\ntemplate \nstruct NodeAllocator;\n\n// dummy allocator that does nothing\ntemplate \nstruct NodeAllocator {\n // we are not using the data, so just free it.\n void addOrFree(void *ptr, size_t ROBIN_HOOD_UNUSED(numBytes) /*unused*/) noexcept {\n ROBIN_HOOD_LOG(\"hf3fs::memory::deallocate\")\n hf3fs::memory::deallocate(ptr);\n }\n};\n\ntemplate \nstruct NodeAllocator : public BulkPoolAllocator {};\n\n// c++14 doesn't have is_nothrow_swappable, and clang++ 6.0.1 doesn't like it either, so I'm making\n// my own here.\nnamespace swappable {\n#if ROBIN_HOOD(CXX) < ROBIN_HOOD(CXX17)\nusing std::swap;\ntemplate \nstruct nothrow {\n static const bool value = noexcept(swap(std::declval(), std::declval()));\n};\n#else\ntemplate \nstruct nothrow {\n static const bool value = std::is_nothrow_swappable::value;\n};\n#endif\n} // namespace swappable\n\n} // namespace detail\n\nstruct is_transparent_tag {};\n\n// A custom pair implementation is used in the map because std::pair is not is_trivially_copyable,\n// which means it would not be allowed to be used in std::memcpy. This struct is copyable, which is\n// also tested.\ntemplate \nstruct pair {\n using first_type = T1;\n using second_type = T2;\n\n template ::value &&\n std::is_default_constructible::value>::type>\n constexpr pair() noexcept(noexcept(U1()) &&noexcept(U2()))\n : first(),\n second() {}\n\n // pair constructors are explicit so we don't accidentally call this ctor when we don't have to.\n explicit constexpr pair(std::pair const &o) noexcept(\n noexcept(T1(std::declval())) &&noexcept(T2(std::declval())))\n : first(o.first),\n second(o.second) {}\n\n // pair constructors are explicit so we don't accidentally call this ctor when we don't have to.\n explicit constexpr pair(std::pair &&o) noexcept(\n noexcept(T1(std::move(std::declval()))) &&noexcept(T2(std::move(std::declval()))))\n : first(std::move(o.first)),\n second(std::move(o.second)) {}\n\n constexpr pair(T1 &&a, T2 &&b) noexcept(\n noexcept(T1(std::move(std::declval()))) &&noexcept(T2(std::move(std::declval()))))\n : first(std::move(a)),\n second(std::move(b)) {}\n\n template \n constexpr pair(U1 &&a, U2 &&b) noexcept(\n noexcept(T1(std::forward(std::declval()))) &&noexcept(T2(std::forward(std::declval()))))\n : first(std::forward(a)),\n second(std::forward(b)) {}\n\n template \n // MSVC 2015 produces error \"C2476: ‘constexpr’ constructor does not initialize all members\"\n // if this constructor is constexpr\n#if !ROBIN_HOOD(BROKEN_CONSTEXPR)\n constexpr\n#endif\n pair(std::piecewise_construct_t /*unused*/,\n std::tuple a,\n std::tuple b) noexcept(noexcept(pair(std::declval &>(),\n std::declval &>(),\n ROBIN_HOOD_STD::index_sequence_for(),\n ROBIN_HOOD_STD::index_sequence_for())))\n : pair(a, b, ROBIN_HOOD_STD::index_sequence_for(), ROBIN_HOOD_STD::index_sequence_for()) {\n }\n\n // constructor called from the std::piecewise_construct_t ctor\n template \n pair(std::tuple &a,\n std::tuple &b,\n ROBIN_HOOD_STD::index_sequence /*unused*/,\n ROBIN_HOOD_STD::index_sequence<\n I2...> /*unused*/) noexcept(noexcept(T1(std::forward(std::get(std::declval\n &>()))...))\n &&noexcept(T2(\n std::forward(std::get(std::declval &>()))...)))\n : first(std::forward(std::get(a))...),\n second(std::forward(std::get(b))...) {\n // make visual studio compiler happy about warning about unused a & b.\n // Visual studio's pair implementation disables warning 4100.\n (void)a;\n (void)b;\n }\n\n void swap(pair &o) noexcept((detail::swappable::nothrow::value) &&\n (detail::swappable::nothrow::value)) {\n using std::swap;\n swap(first, o.first);\n swap(second, o.second);\n }\n\n T1 first; // NOLINT(misc-non-private-member-variables-in-classes)\n T2 second; // NOLINT(misc-non-private-member-variables-in-classes)\n};\n\ntemplate \ninline void swap(pair &a,\n pair &b) noexcept(noexcept(std::declval &>().swap(std::declval &>()))) {\n a.swap(b);\n}\n\ntemplate \ninline constexpr bool operator==(pair const &x, pair const &y) {\n return (x.first == y.first) && (x.second == y.second);\n}\ntemplate \ninline constexpr bool operator!=(pair const &x, pair const &y) {\n return !(x == y);\n}\ntemplate \ninline constexpr bool operator<(pair const &x, pair const &y) noexcept(\n noexcept(std::declval() < std::declval()) &&noexcept(std::declval() <\n std::declval())) {\n return x.first < y.first || (!(y.first < x.first) && x.second < y.second);\n}\ntemplate \ninline constexpr bool operator>(pair const &x, pair const &y) {\n return y < x;\n}\ntemplate \ninline constexpr bool operator<=(pair const &x, pair const &y) {\n return !(x > y);\n}\ntemplate \ninline constexpr bool operator>=(pair const &x, pair const &y) {\n return !(x < y);\n}\n\ninline size_t hash_bytes(void const *ptr, size_t len) noexcept {\n static constexpr uint64_t m = UINT64_C(0xc6a4a7935bd1e995);\n static constexpr uint64_t seed = UINT64_C(0xe17a1465);\n static constexpr unsigned int r = 47;\n\n auto const *const data64 = static_cast(ptr);\n uint64_t h = seed ^ (len * m);\n\n size_t const n_blocks = len / 8;\n for (size_t i = 0; i < n_blocks; ++i) {\n auto k = detail::unaligned_load(data64 + i);\n\n k *= m;\n k ^= k >> r;\n k *= m;\n\n h ^= k;\n h *= m;\n }\n\n auto const *const data8 = reinterpret_cast(data64 + n_blocks);\n switch (len & 7U) {\n case 7:\n h ^= static_cast(data8[6]) << 48U;\n ROBIN_HOOD(FALLTHROUGH); // FALLTHROUGH\n case 6:\n h ^= static_cast(data8[5]) << 40U;\n ROBIN_HOOD(FALLTHROUGH); // FALLTHROUGH\n case 5:\n h ^= static_cast(data8[4]) << 32U;\n ROBIN_HOOD(FALLTHROUGH); // FALLTHROUGH\n case 4:\n h ^= static_cast(data8[3]) << 24U;\n ROBIN_HOOD(FALLTHROUGH); // FALLTHROUGH\n case 3:\n h ^= static_cast(data8[2]) << 16U;\n ROBIN_HOOD(FALLTHROUGH); // FALLTHROUGH\n case 2:\n h ^= static_cast(data8[1]) << 8U;\n ROBIN_HOOD(FALLTHROUGH); // FALLTHROUGH\n case 1:\n h ^= static_cast(data8[0]);\n h *= m;\n ROBIN_HOOD(FALLTHROUGH); // FALLTHROUGH\n default:\n break;\n }\n\n h ^= h >> r;\n\n // not doing the final step here, because this will be done by keyToIdx anyways\n // h *= m;\n // h ^= h >> r;\n return static_cast(h);\n}\n\ninline size_t hash_int(uint64_t x) noexcept {\n // tried lots of different hashes, let's stick with murmurhash3. It's simple, fast, well tested,\n // and doesn't need any special 128bit operations.\n x ^= x >> 33U;\n x *= UINT64_C(0xff51afd7ed558ccd);\n x ^= x >> 33U;\n\n // not doing the final step here, because this will be done by keyToIdx anyways\n // x *= UINT64_C(0xc4ceb9fe1a85ec53);\n // x ^= x >> 33U;\n return static_cast(x);\n}\n\n// A thin wrapper around std::hash, performing an additional simple mixing step of the result.\ntemplate \nstruct hash : public std::hash {\n size_t operator()(T const &obj) const\n noexcept(noexcept(std::declval>().operator()(std::declval()))) {\n // call base hash\n auto result = std::hash::operator()(obj);\n // return mixed of that, to be save against identity has\n return hash_int(static_cast(result));\n }\n};\n\ntemplate \nstruct hash> {\n size_t operator()(std::basic_string const &str) const noexcept {\n return hash_bytes(str.data(), sizeof(CharT) * str.size());\n }\n};\n\n#if ROBIN_HOOD(CXX) >= ROBIN_HOOD(CXX17)\ntemplate \nstruct hash> {\n size_t operator()(std::basic_string_view const &sv) const noexcept {\n return hash_bytes(sv.data(), sizeof(CharT) * sv.size());\n }\n};\n#endif\n\ntemplate \nstruct hash {\n size_t operator()(T *ptr) const noexcept { return hash_int(reinterpret_cast(ptr)); }\n};\n\ntemplate \nstruct hash> {\n size_t operator()(std::unique_ptr const &ptr) const noexcept {\n return hash_int(reinterpret_cast(ptr.get()));\n }\n};\n\ntemplate \nstruct hash> {\n size_t operator()(std::shared_ptr const &ptr) const noexcept {\n return hash_int(reinterpret_cast(ptr.get()));\n }\n};\n\ntemplate \nstruct hash::value>::type> {\n size_t operator()(Enum e) const noexcept {\n using Underlying = typename std::underlying_type::type;\n return hash{}(static_cast(e));\n }\n};\n\n#define ROBIN_HOOD_HASH_INT(T) \\\n template <> \\\n struct hash { \\\n size_t operator()(T const &obj) const noexcept { return hash_int(static_cast(obj)); } \\\n }\n\n#if defined(__GNUC__) && !defined(__clang__)\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wuseless-cast\"\n#endif\n// see https://en.cppreference.com/w/cpp/utility/hash\nROBIN_HOOD_HASH_INT(bool);\nROBIN_HOOD_HASH_INT(char);\nROBIN_HOOD_HASH_INT(signed char);\nROBIN_HOOD_HASH_INT(unsigned char);\nROBIN_HOOD_HASH_INT(char16_t);\nROBIN_HOOD_HASH_INT(char32_t);\n#if ROBIN_HOOD(HAS_NATIVE_WCHART)\nROBIN_HOOD_HASH_INT(wchar_t);\n#endif\nROBIN_HOOD_HASH_INT(short);\nROBIN_HOOD_HASH_INT(unsigned short);\nROBIN_HOOD_HASH_INT(int);\nROBIN_HOOD_HASH_INT(unsigned int);\nROBIN_HOOD_HASH_INT(long);\nROBIN_HOOD_HASH_INT(long long);\nROBIN_HOOD_HASH_INT(unsigned long);\nROBIN_HOOD_HASH_INT(unsigned long long);\n#if defined(__GNUC__) && !defined(__clang__)\n#pragma GCC diagnostic pop\n#endif\nnamespace detail {\n\ntemplate \nstruct void_type {\n using type = void;\n};\n\ntemplate \nstruct has_is_transparent : public std::false_type {};\n\ntemplate \nstruct has_is_transparent::type> : public std::true_type {};\n\n// using wrapper classes for hash and key_equal prevents the diamond problem when the same type\n// is used. see https://stackoverflow.com/a/28771920/48181\ntemplate \nstruct WrapHash : public T {\n WrapHash() = default;\n explicit WrapHash(T const &o) noexcept(noexcept(T(std::declval())))\n : T(o) {}\n};\n\ntemplate \nstruct WrapKeyEqual : public T {\n WrapKeyEqual() = default;\n explicit WrapKeyEqual(T const &o) noexcept(noexcept(T(std::declval())))\n : T(o) {}\n};\n\n// A highly optimized hashmap implementation, using the Robin Hood algorithm.\n//\n// In most cases, this map should be usable as a drop-in replacement for std::unordered_map, but\n// be about 2x faster in most cases and require much less allocations.\n//\n// This implementation uses the following memory layout:\n//\n// [Node, Node, ... Node | info, info, ... infoSentinel ]\n//\n// * Node: either a DataNode that directly has the std::pair as member,\n// or a DataNode with a pointer to std::pair. Which DataNode representation to use\n// depends on how fast the swap() operation is. Heuristically, this is automatically choosen\n// based on sizeof(). there are always 2^n Nodes.\n//\n// * info: Each Node in the map has a corresponding info byte, so there are 2^n info bytes.\n// Each byte is initialized to 0, meaning the corresponding Node is empty. Set to 1 means the\n// corresponding node contains data. Set to 2 means the corresponding Node is filled, but it\n// actually belongs to the previous position and was pushed out because that place is already\n// taken.\n//\n// * infoSentinel: Sentinel byte set to 1, so that iterator's ++ can stop at end() without the\n// need for a idx variable.\n//\n// According to STL, order of templates has effect on throughput. That's why I've moved the\n// boolean to the front.\n// https://www.reddit.com/r/cpp/comments/ahp6iu/compile_time_binary_size_reductions_and_cs_future/eeguck4/\ntemplate \nclass Table\n : public WrapHash,\n public WrapKeyEqual,\n detail::NodeAllocator<\n typename std::conditional::value,\n Key,\n robin_hood::pair::type, T>>::type,\n 4,\n 16384,\n IsFlat> {\n public:\n static constexpr bool is_flat = IsFlat;\n static constexpr bool is_map = !std::is_void::value;\n static constexpr bool is_set = !is_map;\n static constexpr bool is_transparent = has_is_transparent::value && has_is_transparent::value;\n\n using key_type = Key;\n using mapped_type = T;\n using value_type = typename std::\n conditional::type, T>>::type;\n using size_type = size_t;\n using hasher = Hash;\n using key_equal = KeyEqual;\n using Self = Table;\n\n private:\n static_assert(MaxLoadFactor100 > 10 && MaxLoadFactor100 < 100, \"MaxLoadFactor100 needs to be >10 && < 100\");\n\n using WHash = WrapHash;\n using WKeyEqual = WrapKeyEqual;\n\n // configuration defaults\n\n // make sure we have 8 elements, needed to quickly rehash mInfo\n static constexpr size_t InitialNumElements = sizeof(uint64_t);\n static constexpr uint32_t InitialInfoNumBits = 5;\n static constexpr uint8_t InitialInfoInc = 1U << InitialInfoNumBits;\n static constexpr size_t InfoMask = InitialInfoInc - 1U;\n static constexpr uint8_t InitialInfoHashShift = 0;\n using DataPool = detail::NodeAllocator;\n\n // type needs to be wider than uint8_t.\n using InfoType = uint32_t;\n\n // DataNode ////////////////////////////////////////////////////////\n\n // Primary template for the data node. We have special implementations for small and big\n // objects. For large objects it is assumed that swap() is fairly slow, so we allocate these\n // on the heap so swap merely swaps a pointer.\n template \n class DataNode {};\n\n // Small: just allocate on the stack.\n template \n class DataNode final {\n public:\n template \n explicit DataNode(M &ROBIN_HOOD_UNUSED(map) /*unused*/,\n Args &&...args) noexcept(noexcept(value_type(std::forward(args)...)))\n : mData(std::forward(args)...) {}\n\n DataNode(M &ROBIN_HOOD_UNUSED(map) /*unused*/,\n DataNode &&n) noexcept(std::is_nothrow_move_constructible::value)\n : mData(std::move(n.mData)) {}\n\n // doesn't do anything\n void destroy(M &ROBIN_HOOD_UNUSED(map) /*unused*/) noexcept {}\n void destroyDoNotDeallocate() noexcept {}\n\n value_type const *operator->() const noexcept { return &mData; }\n value_type *operator->() noexcept { return &mData; }\n\n const value_type &operator*() const noexcept { return mData; }\n\n value_type &operator*() noexcept { return mData; }\n\n template \n ROBIN_HOOD(NODISCARD)\n typename std::enable_if::type getFirst() noexcept {\n return mData.first;\n }\n template \n ROBIN_HOOD(NODISCARD)\n typename std::enable_if::type getFirst() noexcept {\n return mData;\n }\n\n template \n ROBIN_HOOD(NODISCARD)\n typename std::enable_if::type getFirst() const noexcept {\n return mData.first;\n }\n template \n ROBIN_HOOD(NODISCARD)\n typename std::enable_if::type getFirst() const noexcept {\n return mData;\n }\n\n template \n ROBIN_HOOD(NODISCARD)\n typename std::enable_if::type getSecond() noexcept {\n return mData.second;\n }\n\n template \n ROBIN_HOOD(NODISCARD)\n typename std::enable_if::type getSecond() const noexcept {\n return mData.second;\n }\n\n void swap(DataNode &o) noexcept(noexcept(std::declval().swap(std::declval()))) {\n mData.swap(o.mData);\n }\n\n private:\n value_type mData;\n };\n\n // big object: allocate on heap.\n template \n class DataNode {\n public:\n template \n explicit DataNode(M &map, Args &&...args)\n : mData(map.allocate()) {\n ::new (static_cast(mData)) value_type(std::forward(args)...);\n }\n\n DataNode(M &ROBIN_HOOD_UNUSED(map) /*unused*/, DataNode &&n) noexcept\n : mData(std::move(n.mData)) {}\n\n void destroy(M &map) noexcept {\n // don't deallocate, just put it into list of datapool.\n mData->~value_type();\n map.deallocate(mData);\n }\n\n void destroyDoNotDeallocate() noexcept { mData->~value_type(); }\n\n value_type const *operator->() const noexcept { return mData; }\n\n value_type *operator->() noexcept { return mData; }\n\n const value_type &operator*() const { return *mData; }\n\n value_type &operator*() { return *mData; }\n\n template \n ROBIN_HOOD(NODISCARD)\n typename std::enable_if::type getFirst() noexcept {\n return mData->first;\n }\n template \n ROBIN_HOOD(NODISCARD)\n typename std::enable_if::type getFirst() noexcept {\n return *mData;\n }\n\n template \n ROBIN_HOOD(NODISCARD)\n typename std::enable_if::type getFirst() const noexcept {\n return mData->first;\n }\n template \n ROBIN_HOOD(NODISCARD)\n typename std::enable_if::type getFirst() const noexcept {\n return *mData;\n }\n\n template \n ROBIN_HOOD(NODISCARD)\n typename std::enable_if::type getSecond() noexcept {\n return mData->second;\n }\n\n template \n ROBIN_HOOD(NODISCARD)\n typename std::enable_if::type getSecond() const noexcept {\n return mData->second;\n }\n\n void swap(DataNode &o) noexcept {\n using std::swap;\n swap(mData, o.mData);\n }\n\n private:\n value_type *mData;\n };\n\n using Node = DataNode;\n\n // helpers for insertKeyPrepareEmptySpot: extract first entry (only const required)\n ROBIN_HOOD(NODISCARD) key_type const &getFirstConst(Node const &n) const noexcept { return n.getFirst(); }\n\n // in case we have void mapped_type, we are not using a pair, thus we just route k through.\n // No need to disable this because it's just not used if not applicable.\n ROBIN_HOOD(NODISCARD) key_type const &getFirstConst(key_type const &k) const noexcept { return k; }\n\n // in case we have non-void mapped_type, we have a standard robin_hood::pair\n template \n ROBIN_HOOD(NODISCARD)\n typename std::enable_if::value, key_type const &>::type\n getFirstConst(value_type const &vt) const noexcept {\n return vt.first;\n }\n\n // Cloner //////////////////////////////////////////////////////////\n\n template \n struct Cloner;\n\n // fast path: Just copy data, without allocating anything.\n template \n struct Cloner {\n void operator()(M const &source, M &target) const {\n auto const *const src = reinterpret_cast(source.mKeyVals);\n auto *tgt = reinterpret_cast(target.mKeyVals);\n auto const numElementsWithBuffer = target.calcNumElementsWithBuffer(target.mMask + 1);\n std::copy(src, src + target.calcNumBytesTotal(numElementsWithBuffer), tgt);\n }\n };\n\n template \n struct Cloner {\n void operator()(M const &s, M &t) const {\n auto const numElementsWithBuffer = t.calcNumElementsWithBuffer(t.mMask + 1);\n std::copy(s.mInfo, s.mInfo + t.calcNumBytesInfo(numElementsWithBuffer), t.mInfo);\n\n for (size_t i = 0; i < numElementsWithBuffer; ++i) {\n if (t.mInfo[i]) {\n ::new (static_cast(t.mKeyVals + i)) Node(t, *s.mKeyVals[i]);\n }\n }\n }\n };\n\n // Destroyer ///////////////////////////////////////////////////////\n\n template \n struct Destroyer {};\n\n template \n struct Destroyer {\n void nodes(M &m) const noexcept { m.mNumElements = 0; }\n\n void nodesDoNotDeallocate(M &m) const noexcept { m.mNumElements = 0; }\n };\n\n template \n struct Destroyer {\n void nodes(M &m) const noexcept {\n m.mNumElements = 0;\n // clear also resets mInfo to 0, that's sometimes not necessary.\n auto const numElementsWithBuffer = m.calcNumElementsWithBuffer(m.mMask + 1);\n\n for (size_t idx = 0; idx < numElementsWithBuffer; ++idx) {\n if (0 != m.mInfo[idx]) {\n Node &n = m.mKeyVals[idx];\n n.destroy(m);\n n.~Node();\n }\n }\n }\n\n void nodesDoNotDeallocate(M &m) const noexcept {\n m.mNumElements = 0;\n // clear also resets mInfo to 0, that's sometimes not necessary.\n auto const numElementsWithBuffer = m.calcNumElementsWithBuffer(m.mMask + 1);\n for (size_t idx = 0; idx < numElementsWithBuffer; ++idx) {\n if (0 != m.mInfo[idx]) {\n Node &n = m.mKeyVals[idx];\n n.destroyDoNotDeallocate();\n n.~Node();\n }\n }\n }\n };\n\n // Iter ////////////////////////////////////////////////////////////\n\n struct fast_forward_tag {};\n\n // generic iterator for both const_iterator and iterator.\n template \n // NOLINTNEXTLINE(hicpp-special-member-functions,cppcoreguidelines-special-member-functions)\n class Iter {\n private:\n using NodePtr = typename std::conditional::type;\n\n public:\n using difference_type = std::ptrdiff_t;\n using value_type = typename Self::value_type;\n using reference = typename std::conditional::type;\n using pointer = typename std::conditional::type;\n using iterator_category = std::forward_iterator_tag;\n\n // default constructed iterator can be compared to itself, but WON'T return true when\n // compared to end().\n Iter() = default;\n\n // Rule of zero: nothing specified. The conversion constructor is only enabled for\n // iterator to const_iterator, so it doesn't accidentally work as a copy ctor.\n\n // Conversion constructor from iterator to const_iterator.\n template ::type>\n // NOLINTNEXTLINE(hicpp-explicit-conversions)\n Iter(Iter const &other) noexcept\n : mKeyVals(other.mKeyVals),\n mInfo(other.mInfo) {}\n\n Iter(NodePtr valPtr, uint8_t const *infoPtr) noexcept\n : mKeyVals(valPtr),\n mInfo(infoPtr) {}\n\n Iter(NodePtr valPtr, uint8_t const *infoPtr, fast_forward_tag ROBIN_HOOD_UNUSED(tag) /*unused*/) noexcept\n : mKeyVals(valPtr),\n mInfo(infoPtr) {\n fastForward();\n }\n\n template ::type>\n Iter &operator=(Iter const &other) noexcept {\n mKeyVals = other.mKeyVals;\n mInfo = other.mInfo;\n return *this;\n }\n\n // prefix increment. Undefined behavior if we are at end()!\n Iter &operator++() noexcept {\n mInfo++;\n mKeyVals++;\n fastForward();\n return *this;\n }\n\n Iter operator++(int) noexcept {\n Iter tmp = *this;\n ++(*this);\n return tmp;\n }\n\n reference operator*() const { return **mKeyVals; }\n\n pointer operator->() const { return &**mKeyVals; }\n\n template \n bool operator==(Iter const &o) const noexcept {\n return mKeyVals == o.mKeyVals;\n }\n\n template \n bool operator!=(Iter const &o) const noexcept {\n return mKeyVals != o.mKeyVals;\n }\n\n private:\n // fast forward to the next non-free info byte\n // I've tried a few variants that don't depend on intrinsics, but unfortunately they are\n // quite a bit slower than this one. So I've reverted that change again. See map_benchmark.\n void fastForward() noexcept {\n size_t n = 0;\n while (0U == (n = detail::unaligned_load(mInfo))) {\n mInfo += sizeof(size_t);\n mKeyVals += sizeof(size_t);\n }\n#if defined(ROBIN_HOOD_DISABLE_INTRINSICS)\n // we know for certain that within the next 8 bytes we'll find a non-zero one.\n if (ROBIN_HOOD_UNLIKELY(0U == detail::unaligned_load(mInfo))) {\n mInfo += 4;\n mKeyVals += 4;\n }\n if (ROBIN_HOOD_UNLIKELY(0U == detail::unaligned_load(mInfo))) {\n mInfo += 2;\n mKeyVals += 2;\n }\n if (ROBIN_HOOD_UNLIKELY(0U == *mInfo)) {\n mInfo += 1;\n mKeyVals += 1;\n }\n#else\n#if ROBIN_HOOD(LITTLE_ENDIAN)\n auto inc = ROBIN_HOOD_COUNT_TRAILING_ZEROES(n) / 8;\n#else\n auto inc = ROBIN_HOOD_COUNT_LEADING_ZEROES(n) / 8;\n#endif\n mInfo += inc;\n mKeyVals += inc;\n#endif\n }\n\n friend class Table;\n NodePtr mKeyVals{nullptr};\n uint8_t const *mInfo{nullptr};\n };\n\n ////////////////////////////////////////////////////////////////////\n\n // highly performance relevant code.\n // Lower bits are used for indexing into the array (2^n size)\n // The upper 1-5 bits need to be a reasonable good hash, to save comparisons.\n template \n void keyToIdx(HashKey &&key, size_t *idx, InfoType *info) const {\n // In addition to whatever hash is used, add another mul & shift so we get better hashing.\n // This serves as a bad hash prevention, if the given data is\n // badly mixed.\n auto h = static_cast(WHash::operator()(key));\n\n h *= mHashMultiplier;\n h ^= h >> 33U;\n\n // the lower InitialInfoNumBits are reserved for info.\n *info = mInfoInc + static_cast((h & InfoMask) >> mInfoHashShift);\n *idx = (static_cast(h) >> InitialInfoNumBits) & mMask;\n }\n\n // forwards the index by one, wrapping around at the end\n void next(InfoType *info, size_t *idx) const noexcept {\n *idx = *idx + 1;\n *info += mInfoInc;\n }\n\n void nextWhileLess(InfoType *info, size_t *idx) const noexcept {\n // unrolling this by hand did not bring any speedups.\n while (*info < mInfo[*idx]) {\n next(info, idx);\n }\n }\n\n // Shift everything up by one element. Tries to move stuff around.\n void shiftUp(size_t startIdx, size_t const insertion_idx) noexcept(std::is_nothrow_move_assignable::value) {\n auto idx = startIdx;\n ::new (static_cast(mKeyVals + idx)) Node(std::move(mKeyVals[idx - 1]));\n while (--idx != insertion_idx) {\n mKeyVals[idx] = std::move(mKeyVals[idx - 1]);\n }\n\n idx = startIdx;\n while (idx != insertion_idx) {\n ROBIN_HOOD_COUNT(shiftUp)\n mInfo[idx] = static_cast(mInfo[idx - 1] + mInfoInc);\n if (ROBIN_HOOD_UNLIKELY(mInfo[idx] + mInfoInc > 0xFF)) {\n mMaxNumElementsAllowed = 0;\n }\n --idx;\n }\n }\n\n void shiftDown(size_t idx) noexcept(std::is_nothrow_move_assignable::value) {\n // until we find one that is either empty or has zero offset.\n // TODO(martinus) we don't need to move everything, just the last one for the same\n // bucket.\n mKeyVals[idx].destroy(*this);\n\n // until we find one that is either empty or has zero offset.\n while (mInfo[idx + 1] >= 2 * mInfoInc) {\n ROBIN_HOOD_COUNT(shiftDown)\n mInfo[idx] = static_cast(mInfo[idx + 1] - mInfoInc);\n mKeyVals[idx] = std::move(mKeyVals[idx + 1]);\n ++idx;\n }\n\n mInfo[idx] = 0;\n // don't destroy, we've moved it\n // mKeyVals[idx].destroy(*this);\n mKeyVals[idx].~Node();\n }\n\n // copy of find(), except that it returns iterator instead of const_iterator.\n template \n ROBIN_HOOD(NODISCARD)\n size_t findIdx(Other const &key) const {\n size_t idx{};\n InfoType info{};\n keyToIdx(key, &idx, &info);\n\n do {\n // unrolling this twice gives a bit of a speedup. More unrolling did not help.\n if (info == mInfo[idx] && ROBIN_HOOD_LIKELY(WKeyEqual::operator()(key, mKeyVals[idx].getFirst()))) {\n return idx;\n }\n next(&info, &idx);\n if (info == mInfo[idx] && ROBIN_HOOD_LIKELY(WKeyEqual::operator()(key, mKeyVals[idx].getFirst()))) {\n return idx;\n }\n next(&info, &idx);\n } while (info <= mInfo[idx]);\n\n // nothing found!\n return mMask == 0\n ? 0\n : static_cast(std::distance(mKeyVals, reinterpret_cast_no_cast_align_warning(mInfo)));\n }\n\n void cloneData(const Table &o) { Cloner::value>()(o, *this); }\n\n // inserts a keyval that is guaranteed to be new, e.g. when the hashmap is resized.\n // @return True on success, false if something went wrong\n void insert_move(Node &&keyval) {\n // we don't retry, fail if overflowing\n // don't need to check max num elements\n if (0 == mMaxNumElementsAllowed && !try_increase_info()) {\n throwOverflowError();\n }\n\n size_t idx{};\n InfoType info{};\n keyToIdx(keyval.getFirst(), &idx, &info);\n\n // skip forward. Use <= because we are certain that the element is not there.\n while (info <= mInfo[idx]) {\n idx = idx + 1;\n info += mInfoInc;\n }\n\n // key not found, so we are now exactly where we want to insert it.\n auto const insertion_idx = idx;\n auto const insertion_info = static_cast(info);\n if (ROBIN_HOOD_UNLIKELY(insertion_info + mInfoInc > 0xFF)) {\n mMaxNumElementsAllowed = 0;\n }\n\n // find an empty spot\n while (0 != mInfo[idx]) {\n next(&info, &idx);\n }\n\n auto &l = mKeyVals[insertion_idx];\n if (idx == insertion_idx) {\n ::new (static_cast(&l)) Node(std::move(keyval));\n } else {\n shiftUp(idx, insertion_idx);\n l = std::move(keyval);\n }\n\n // put at empty spot\n mInfo[insertion_idx] = insertion_info;\n\n ++mNumElements;\n }\n\n public:\n using iterator = Iter;\n using const_iterator = Iter;\n\n Table() noexcept(noexcept(Hash()) &&noexcept(KeyEqual()))\n : WHash(),\n WKeyEqual() {\n ROBIN_HOOD_TRACE(this)\n }\n\n // Creates an empty hash map. Nothing is allocated yet, this happens at the first insert.\n // This tremendously speeds up ctor & dtor of a map that never receives an element. The\n // penalty is payed at the first insert, and not before. Lookup of this empty map works\n // because everybody points to DummyInfoByte::b. parameter bucket_count is dictated by the\n // standard, but we can ignore it.\n explicit Table(size_t ROBIN_HOOD_UNUSED(bucket_count) /*unused*/,\n const Hash &h = Hash{},\n const KeyEqual &equal = KeyEqual{}) noexcept(noexcept(Hash(h)) &&noexcept(KeyEqual(equal)))\n : WHash(h),\n WKeyEqual(equal) {\n ROBIN_HOOD_TRACE(this)\n }\n\n template \n Table(Iter first,\n Iter last,\n size_t ROBIN_HOOD_UNUSED(bucket_count) /*unused*/ = 0,\n const Hash &h = Hash{},\n const KeyEqual &equal = KeyEqual{})\n : WHash(h),\n WKeyEqual(equal) {\n ROBIN_HOOD_TRACE(this)\n insert(first, last);\n }\n\n Table(std::initializer_list initlist,\n size_t ROBIN_HOOD_UNUSED(bucket_count) /*unused*/ = 0,\n const Hash &h = Hash{},\n const KeyEqual &equal = KeyEqual{})\n : WHash(h),\n WKeyEqual(equal) {\n ROBIN_HOOD_TRACE(this)\n insert(initlist.begin(), initlist.end());\n }\n\n Table(Table &&o) noexcept\n : WHash(std::move(static_cast(o))),\n WKeyEqual(std::move(static_cast(o))),\n DataPool(std::move(static_cast(o))) {\n ROBIN_HOOD_TRACE(this)\n if (o.mMask) {\n mHashMultiplier = std::move(o.mHashMultiplier);\n mKeyVals = std::move(o.mKeyVals);\n mInfo = std::move(o.mInfo);\n mNumElements = std::move(o.mNumElements);\n mMask = std::move(o.mMask);\n mMaxNumElementsAllowed = std::move(o.mMaxNumElementsAllowed);\n mInfoInc = std::move(o.mInfoInc);\n mInfoHashShift = std::move(o.mInfoHashShift);\n // set other's mask to 0 so its destructor won't do anything\n o.init();\n }\n }\n\n Table &operator=(Table &&o) noexcept {\n ROBIN_HOOD_TRACE(this)\n if (&o != this) {\n if (o.mMask) {\n // only move stuff if the other map actually has some data\n destroy();\n mHashMultiplier = std::move(o.mHashMultiplier);\n mKeyVals = std::move(o.mKeyVals);\n mInfo = std::move(o.mInfo);\n mNumElements = std::move(o.mNumElements);\n mMask = std::move(o.mMask);\n mMaxNumElementsAllowed = std::move(o.mMaxNumElementsAllowed);\n mInfoInc = std::move(o.mInfoInc);\n mInfoHashShift = std::move(o.mInfoHashShift);\n WHash::operator=(std::move(static_cast(o)));\n WKeyEqual::operator=(std::move(static_cast(o)));\n DataPool::operator=(std::move(static_cast(o)));\n\n o.init();\n\n } else {\n // nothing in the other map => just clear us.\n clear();\n }\n }\n return *this;\n }\n\n Table(const Table &o)\n : WHash(static_cast(o)),\n WKeyEqual(static_cast(o)),\n DataPool(static_cast(o)) {\n ROBIN_HOOD_TRACE(this)\n if (!o.empty()) {\n // not empty: create an exact copy. it is also possible to just iterate through all\n // elements and insert them, but copying is probably faster.\n\n auto const numElementsWithBuffer = calcNumElementsWithBuffer(o.mMask + 1);\n auto const numBytesTotal = calcNumBytesTotal(numElementsWithBuffer);\n\n ROBIN_HOOD_LOG(\"hf3fs::memory::allocate \" << numBytesTotal << \" = calcNumBytesTotal(\" << numElementsWithBuffer\n << \")\")\n mHashMultiplier = o.mHashMultiplier;\n mKeyVals = static_cast(detail::assertNotNull(hf3fs::memory::allocate(numBytesTotal)));\n // no need for calloc because clonData does memcpy\n mInfo = reinterpret_cast(mKeyVals + numElementsWithBuffer);\n mNumElements = o.mNumElements;\n mMask = o.mMask;\n mMaxNumElementsAllowed = o.mMaxNumElementsAllowed;\n mInfoInc = o.mInfoInc;\n mInfoHashShift = o.mInfoHashShift;\n cloneData(o);\n }\n }\n\n // Creates a copy of the given map. Copy constructor of each entry is used.\n // Not sure why clang-tidy thinks this doesn't handle self assignment, it does\n // NOLINTNEXTLINE(bugprone-unhandled-self-assignment,cert-oop54-cpp)\n Table &operator=(Table const &o) {\n ROBIN_HOOD_TRACE(this)\n if (&o == this) {\n // prevent assigning of itself\n return *this;\n }\n\n // we keep using the old allocator and not assign the new one, because we want to keep\n // the memory available. when it is the same size.\n if (o.empty()) {\n if (0 == mMask) {\n // nothing to do, we are empty too\n return *this;\n }\n\n // not empty: destroy what we have there\n // clear also resets mInfo to 0, that's sometimes not necessary.\n destroy();\n init();\n WHash::operator=(static_cast(o));\n WKeyEqual::operator=(static_cast(o));\n DataPool::operator=(static_cast(o));\n\n return *this;\n }\n\n // clean up old stuff\n Destroyer::value>{}.nodes(*this);\n\n if (mMask != o.mMask) {\n // no luck: we don't have the same array size allocated, so we need to realloc.\n if (0 != mMask) {\n // only deallocate if we actually have data!\n ROBIN_HOOD_LOG(\"hf3fs::memory::deallocate\")\n hf3fs::memory::deallocate(mKeyVals);\n }\n\n auto const numElementsWithBuffer = calcNumElementsWithBuffer(o.mMask + 1);\n auto const numBytesTotal = calcNumBytesTotal(numElementsWithBuffer);\n ROBIN_HOOD_LOG(\"hf3fs::memory::allocate \" << numBytesTotal << \" = calcNumBytesTotal(\" << numElementsWithBuffer\n << \")\")\n mKeyVals = static_cast(detail::assertNotNull(hf3fs::memory::allocate(numBytesTotal)));\n\n // no need for calloc here because cloneData performs a memcpy.\n mInfo = reinterpret_cast(mKeyVals + numElementsWithBuffer);\n // sentinel is set in cloneData\n }\n WHash::operator=(static_cast(o));\n WKeyEqual::operator=(static_cast(o));\n DataPool::operator=(static_cast(o));\n mHashMultiplier = o.mHashMultiplier;\n mNumElements = o.mNumElements;\n mMask = o.mMask;\n mMaxNumElementsAllowed = o.mMaxNumElementsAllowed;\n mInfoInc = o.mInfoInc;\n mInfoHashShift = o.mInfoHashShift;\n cloneData(o);\n\n return *this;\n }\n\n // Swaps everything between the two maps.\n void swap(Table &o) {\n ROBIN_HOOD_TRACE(this)\n using std::swap;\n swap(o, *this);\n }\n\n // Clears all data, without resizing.\n void clear() {\n ROBIN_HOOD_TRACE(this)\n if (empty()) {\n // don't do anything! also important because we don't want to write to\n // DummyInfoByte::b, even though we would just write 0 to it.\n return;\n }\n\n Destroyer::value>{}.nodes(*this);\n\n auto const numElementsWithBuffer = calcNumElementsWithBuffer(mMask + 1);\n // clear everything, then set the sentinel again\n uint8_t const z = 0;\n std::fill(mInfo, mInfo + calcNumBytesInfo(numElementsWithBuffer), z);\n mInfo[numElementsWithBuffer] = 1;\n\n mInfoInc = InitialInfoInc;\n mInfoHashShift = InitialInfoHashShift;\n }\n\n // Destroys the map and all it's contents.\n ~Table() {\n ROBIN_HOOD_TRACE(this)\n destroy();\n }\n\n // Checks if both tables contain the same entries. Order is irrelevant.\n bool operator==(const Table &other) const {\n ROBIN_HOOD_TRACE(this)\n if (other.size() != size()) {\n return false;\n }\n for (auto const &otherEntry : other) {\n if (!has(otherEntry)) {\n return false;\n }\n }\n\n return true;\n }\n\n bool operator!=(const Table &other) const {\n ROBIN_HOOD_TRACE(this)\n return !operator==(other);\n }\n\n template \n typename std::enable_if::value, Q &>::type operator[](const key_type &key) {\n ROBIN_HOOD_TRACE(this)\n auto idxAndState = insertKeyPrepareEmptySpot(key);\n switch (idxAndState.second) {\n case InsertionState::key_found:\n break;\n\n case InsertionState::new_node:\n ::new (static_cast(&mKeyVals[idxAndState.first]))\n Node(*this, std::piecewise_construct, std::forward_as_tuple(key), std::forward_as_tuple());\n break;\n\n case InsertionState::overwrite_node:\n mKeyVals[idxAndState.first] =\n Node(*this, std::piecewise_construct, std::forward_as_tuple(key), std::forward_as_tuple());\n break;\n\n case InsertionState::overflow_error:\n throwOverflowError();\n }\n\n return mKeyVals[idxAndState.first].getSecond();\n }\n\n template \n typename std::enable_if::value, Q &>::type operator[](key_type &&key) {\n ROBIN_HOOD_TRACE(this)\n auto idxAndState = insertKeyPrepareEmptySpot(key);\n switch (idxAndState.second) {\n case InsertionState::key_found:\n break;\n\n case InsertionState::new_node:\n ::new (static_cast(&mKeyVals[idxAndState.first]))\n Node(*this, std::piecewise_construct, std::forward_as_tuple(std::move(key)), std::forward_as_tuple());\n break;\n\n case InsertionState::overwrite_node:\n mKeyVals[idxAndState.first] =\n Node(*this, std::piecewise_construct, std::forward_as_tuple(std::move(key)), std::forward_as_tuple());\n break;\n\n case InsertionState::overflow_error:\n throwOverflowError();\n }\n\n return mKeyVals[idxAndState.first].getSecond();\n }\n\n template \n void insert(Iter first, Iter last) {\n for (; first != last; ++first) {\n // value_type ctor needed because this might be called with std::pair's\n insert(value_type(*first));\n }\n }\n\n void insert(std::initializer_list ilist) {\n for (auto &&vt : ilist) {\n insert(std::move(vt));\n }\n }\n\n template \n std::pair emplace(Args &&...args) {\n ROBIN_HOOD_TRACE(this)\n Node n{*this, std::forward(args)...};\n auto idxAndState = insertKeyPrepareEmptySpot(getFirstConst(n));\n switch (idxAndState.second) {\n case InsertionState::key_found:\n n.destroy(*this);\n break;\n\n case InsertionState::new_node:\n ::new (static_cast(&mKeyVals[idxAndState.first])) Node(*this, std::move(n));\n break;\n\n case InsertionState::overwrite_node:\n mKeyVals[idxAndState.first] = std::move(n);\n break;\n\n case InsertionState::overflow_error:\n n.destroy(*this);\n throwOverflowError();\n break;\n }\n\n return std::make_pair(iterator(mKeyVals + idxAndState.first, mInfo + idxAndState.first),\n InsertionState::key_found != idxAndState.second);\n }\n\n template \n iterator emplace_hint(const_iterator position, Args &&...args) {\n (void)position;\n return emplace(std::forward(args)...).first;\n }\n\n template \n std::pair try_emplace(const key_type &key, Args &&...args) {\n return try_emplace_impl(key, std::forward(args)...);\n }\n\n template \n std::pair try_emplace(key_type &&key, Args &&...args) {\n return try_emplace_impl(std::move(key), std::forward(args)...);\n }\n\n template \n iterator try_emplace(const_iterator hint, const key_type &key, Args &&...args) {\n (void)hint;\n return try_emplace_impl(key, std::forward(args)...).first;\n }\n\n template \n iterator try_emplace(const_iterator hint, key_type &&key, Args &&...args) {\n (void)hint;\n return try_emplace_impl(std::move(key), std::forward(args)...).first;\n }\n\n template \n std::pair insert_or_assign(const key_type &key, Mapped &&obj) {\n return insertOrAssignImpl(key, std::forward(obj));\n }\n\n template \n std::pair insert_or_assign(key_type &&key, Mapped &&obj) {\n return insertOrAssignImpl(std::move(key), std::forward(obj));\n }\n\n template \n iterator insert_or_assign(const_iterator hint, const key_type &key, Mapped &&obj) {\n (void)hint;\n return insertOrAssignImpl(key, std::forward(obj)).first;\n }\n\n template \n iterator insert_or_assign(const_iterator hint, key_type &&key, Mapped &&obj) {\n (void)hint;\n return insertOrAssignImpl(std::move(key), std::forward(obj)).first;\n }\n\n std::pair insert(const value_type &keyval) {\n ROBIN_HOOD_TRACE(this)\n return emplace(keyval);\n }\n\n iterator insert(const_iterator hint, const value_type &keyval) {\n (void)hint;\n return emplace(keyval).first;\n }\n\n std::pair insert(value_type &&keyval) { return emplace(std::move(keyval)); }\n\n iterator insert(const_iterator hint, value_type &&keyval) {\n (void)hint;\n return emplace(std::move(keyval)).first;\n }\n\n // Returns 1 if key is found, 0 otherwise.\n size_t count(const key_type &key) const { // NOLINT(modernize-use-nodiscard)\n ROBIN_HOOD_TRACE(this)\n auto kv = mKeyVals + findIdx(key);\n if (kv != reinterpret_cast_no_cast_align_warning(mInfo)) {\n return 1;\n }\n return 0;\n }\n\n template \n // NOLINTNEXTLINE(modernize-use-nodiscard)\n typename std::enable_if::type count(const OtherKey &key) const {\n ROBIN_HOOD_TRACE(this)\n auto kv = mKeyVals + findIdx(key);\n if (kv != reinterpret_cast_no_cast_align_warning(mInfo)) {\n return 1;\n }\n return 0;\n }\n\n bool contains(const key_type &key) const { // NOLINT(modernize-use-nodiscard)\n return 1U == count(key);\n }\n\n template \n // NOLINTNEXTLINE(modernize-use-nodiscard)\n typename std::enable_if::type contains(const OtherKey &key) const {\n return 1U == count(key);\n }\n\n // Returns a reference to the value found for key.\n // Throws std::out_of_range if element cannot be found\n template \n // NOLINTNEXTLINE(modernize-use-nodiscard)\n typename std::enable_if::value, Q &>::type at(key_type const &key) {\n ROBIN_HOOD_TRACE(this)\n auto kv = mKeyVals + findIdx(key);\n if (kv == reinterpret_cast_no_cast_align_warning(mInfo)) {\n doThrow(\"key not found\");\n }\n return kv->getSecond();\n }\n\n // Returns a reference to the value found for key.\n // Throws std::out_of_range if element cannot be found\n template \n // NOLINTNEXTLINE(modernize-use-nodiscard)\n typename std::enable_if::value, Q const &>::type at(key_type const &key) const {\n ROBIN_HOOD_TRACE(this)\n auto kv = mKeyVals + findIdx(key);\n if (kv == reinterpret_cast_no_cast_align_warning(mInfo)) {\n doThrow(\"key not found\");\n }\n return kv->getSecond();\n }\n\n const_iterator find(const key_type &key) const { // NOLINT(modernize-use-nodiscard)\n ROBIN_HOOD_TRACE(this)\n const size_t idx = findIdx(key);\n return const_iterator{mKeyVals + idx, mInfo + idx};\n }\n\n template \n const_iterator find(const OtherKey &key, is_transparent_tag /*unused*/) const {\n ROBIN_HOOD_TRACE(this)\n const size_t idx = findIdx(key);\n return const_iterator{mKeyVals + idx, mInfo + idx};\n }\n\n template \n typename std::enable_if::type // NOLINT(modernize-use-nodiscard)\n find(const OtherKey &key) const { // NOLINT(modernize-use-nodiscard)\n ROBIN_HOOD_TRACE(this)\n const size_t idx = findIdx(key);\n return const_iterator{mKeyVals + idx, mInfo + idx};\n }\n\n iterator find(const key_type &key) {\n ROBIN_HOOD_TRACE(this)\n const size_t idx = findIdx(key);\n return iterator{mKeyVals + idx, mInfo + idx};\n }\n\n template \n iterator find(const OtherKey &key, is_transparent_tag /*unused*/) {\n ROBIN_HOOD_TRACE(this)\n const size_t idx = findIdx(key);\n return iterator{mKeyVals + idx, mInfo + idx};\n }\n\n template \n typename std::enable_if::type find(const OtherKey &key) {\n ROBIN_HOOD_TRACE(this)\n const size_t idx = findIdx(key);\n return iterator{mKeyVals + idx, mInfo + idx};\n }\n\n iterator begin() {\n ROBIN_HOOD_TRACE(this)\n if (empty()) {\n return end();\n }\n return iterator(mKeyVals, mInfo, fast_forward_tag{});\n }\n const_iterator begin() const { // NOLINT(modernize-use-nodiscard)\n ROBIN_HOOD_TRACE(this)\n return cbegin();\n }\n const_iterator cbegin() const { // NOLINT(modernize-use-nodiscard)\n ROBIN_HOOD_TRACE(this)\n if (empty()) {\n return cend();\n }\n return const_iterator(mKeyVals, mInfo, fast_forward_tag{});\n }\n\n iterator end() {\n ROBIN_HOOD_TRACE(this)\n // no need to supply valid info pointer: end() must not be dereferenced, and only node\n // pointer is compared.\n return iterator{reinterpret_cast_no_cast_align_warning(mInfo), nullptr};\n }\n const_iterator end() const { // NOLINT(modernize-use-nodiscard)\n ROBIN_HOOD_TRACE(this)\n return cend();\n }\n const_iterator cend() const { // NOLINT(modernize-use-nodiscard)\n ROBIN_HOOD_TRACE(this)\n return const_iterator{reinterpret_cast_no_cast_align_warning(mInfo), nullptr};\n }\n\n iterator erase(const_iterator pos) {\n ROBIN_HOOD_TRACE(this)\n // its safe to perform const cast here\n // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast)\n return erase(iterator{const_cast(pos.mKeyVals), const_cast(pos.mInfo)});\n }\n\n // Erases element at pos, returns iterator to the next element.\n iterator erase(iterator pos) {\n ROBIN_HOOD_TRACE(this)\n // we assume that pos always points to a valid entry, and not end().\n auto const idx = static_cast(pos.mKeyVals - mKeyVals);\n\n shiftDown(idx);\n --mNumElements;\n\n if (*pos.mInfo) {\n // we've backward shifted, return this again\n return pos;\n }\n\n // no backward shift, return next element\n return ++pos;\n }\n\n size_t erase(const key_type &key) {\n ROBIN_HOOD_TRACE(this)\n size_t idx{};\n InfoType info{};\n keyToIdx(key, &idx, &info);\n\n // check while info matches with the source idx\n do {\n if (info == mInfo[idx] && WKeyEqual::operator()(key, mKeyVals[idx].getFirst())) {\n shiftDown(idx);\n --mNumElements;\n return 1;\n }\n next(&info, &idx);\n } while (info <= mInfo[idx]);\n\n // nothing found to delete\n return 0;\n }\n\n // reserves space for the specified number of elements. Makes sure the old data fits.\n // exactly the same as reserve(c).\n void rehash(size_t c) {\n // forces a reserve\n reserve(c, true);\n }\n\n // reserves space for the specified number of elements. Makes sure the old data fits.\n // Exactly the same as rehash(c). Use rehash(0) to shrink to fit.\n void reserve(size_t c) {\n // reserve, but don't force rehash\n reserve(c, false);\n }\n\n // If possible reallocates the map to a smaller one. This frees the underlying table.\n // Does not do anything if load_factor is too large for decreasing the table's size.\n void compact() {\n ROBIN_HOOD_TRACE(this)\n auto newSize = InitialNumElements;\n while (calcMaxNumElementsAllowed(newSize) < mNumElements && newSize != 0) {\n newSize *= 2;\n }\n if (ROBIN_HOOD_UNLIKELY(newSize == 0)) {\n throwOverflowError();\n }\n\n ROBIN_HOOD_LOG(\"newSize > mMask + 1: \" << newSize << \" > \" << mMask << \" + 1\")\n\n // only actually do anything when the new size is bigger than the old one. This prevents to\n // continuously allocate for each reserve() call.\n if (newSize < mMask + 1) {\n rehashPowerOfTwo(newSize, true);\n }\n }\n\n size_type size() const noexcept { // NOLINT(modernize-use-nodiscard)\n ROBIN_HOOD_TRACE(this)\n return mNumElements;\n }\n\n size_type max_size() const noexcept { // NOLINT(modernize-use-nodiscard)\n ROBIN_HOOD_TRACE(this)\n return static_cast(-1);\n }\n\n ROBIN_HOOD(NODISCARD) bool empty() const noexcept {\n ROBIN_HOOD_TRACE(this)\n return 0 == mNumElements;\n }\n\n float max_load_factor() const noexcept { // NOLINT(modernize-use-nodiscard)\n ROBIN_HOOD_TRACE(this)\n return MaxLoadFactor100 / 100.0F;\n }\n\n // Average number of elements per bucket. Since we allow only 1 per bucket\n float load_factor() const noexcept { // NOLINT(modernize-use-nodiscard)\n ROBIN_HOOD_TRACE(this)\n return static_cast(size()) / static_cast(mMask + 1);\n }\n\n ROBIN_HOOD(NODISCARD) size_t mask() const noexcept {\n ROBIN_HOOD_TRACE(this)\n return mMask;\n }\n\n ROBIN_HOOD(NODISCARD) size_t calcMaxNumElementsAllowed(size_t maxElements) const noexcept {\n if (ROBIN_HOOD_LIKELY(maxElements <= (std::numeric_limits::max)() / 100)) {\n return maxElements * MaxLoadFactor100 / 100;\n }\n\n // we might be a bit inprecise, but since maxElements is quite large that doesn't matter\n return (maxElements / 100) * MaxLoadFactor100;\n }\n\n ROBIN_HOOD(NODISCARD) size_t calcNumBytesInfo(size_t numElements) const noexcept {\n // we add a uint64_t, which houses the sentinel (first byte) and padding so we can load\n // 64bit types.\n return numElements + sizeof(uint64_t);\n }\n\n ROBIN_HOOD(NODISCARD)\n size_t calcNumElementsWithBuffer(size_t numElements) const noexcept {\n auto maxNumElementsAllowed = calcMaxNumElementsAllowed(numElements);\n return numElements + (std::min)(maxNumElementsAllowed, (static_cast(0xFF)));\n }\n\n // calculation only allowed for 2^n values\n ROBIN_HOOD(NODISCARD) size_t calcNumBytesTotal(size_t numElements) const {\n#if ROBIN_HOOD(BITNESS) == 64\n return numElements * sizeof(Node) + calcNumBytesInfo(numElements);\n#else\n // make sure we're doing 64bit operations, so we are at least safe against 32bit overflows.\n auto const ne = static_cast(numElements);\n auto const s = static_cast(sizeof(Node));\n auto const infos = static_cast(calcNumBytesInfo(numElements));\n\n auto const total64 = ne * s + infos;\n auto const total = static_cast(total64);\n\n if (ROBIN_HOOD_UNLIKELY(static_cast(total) != total64)) {\n throwOverflowError();\n }\n return total;\n#endif\n }\n\n private:\n template \n ROBIN_HOOD(NODISCARD)\n typename std::enable_if::value, bool>::type has(const value_type &e) const {\n ROBIN_HOOD_TRACE(this)\n auto it = find(e.first);\n return it != end() && it->second == e.second;\n }\n\n template \n ROBIN_HOOD(NODISCARD)\n typename std::enable_if::value, bool>::type has(const value_type &e) const {\n ROBIN_HOOD_TRACE(this)\n return find(e) != end();\n }\n\n void reserve(size_t c, bool forceRehash) {\n ROBIN_HOOD_TRACE(this)\n auto const minElementsAllowed = (std::max)(c, mNumElements);\n auto newSize = InitialNumElements;\n while (calcMaxNumElementsAllowed(newSize) < minElementsAllowed && newSize != 0) {\n newSize *= 2;\n }\n if (ROBIN_HOOD_UNLIKELY(newSize == 0)) {\n throwOverflowError();\n }\n\n ROBIN_HOOD_LOG(\"newSize > mMask + 1: \" << newSize << \" > \" << mMask << \" + 1\")\n\n // only actually do anything when the new size is bigger than the old one. This prevents to\n // continuously allocate for each reserve() call.\n if (forceRehash || newSize > mMask + 1) {\n rehashPowerOfTwo(newSize, false);\n }\n }\n\n // reserves space for at least the specified number of elements.\n // only works if numBuckets if power of two\n // True on success, false otherwise\n void rehashPowerOfTwo(size_t numBuckets, bool forceFree) {\n ROBIN_HOOD_TRACE(this)\n\n Node *const oldKeyVals = mKeyVals;\n uint8_t const *const oldInfo = mInfo;\n\n const size_t oldMaxElementsWithBuffer = calcNumElementsWithBuffer(mMask + 1);\n\n // resize operation: move stuff\n initData(numBuckets);\n if (oldMaxElementsWithBuffer > 1) {\n for (size_t i = 0; i < oldMaxElementsWithBuffer; ++i) {\n if (oldInfo[i] != 0) {\n // might throw an exception, which is really bad since we are in the middle of\n // moving stuff.\n insert_move(std::move(oldKeyVals[i]));\n // destroy the node but DON'T destroy the data.\n oldKeyVals[i].~Node();\n }\n }\n\n // this check is not necessary as it's guarded by the previous if, but it helps\n // silence g++'s overeager \"attempt to free a non-heap object 'map'\n // [-Werror=free-nonheap-object]\" warning.\n if (oldKeyVals != reinterpret_cast_no_cast_align_warning(&mMask)) {\n // don't destroy old data: put it into the pool instead\n if (forceFree) {\n hf3fs::memory::deallocate(oldKeyVals);\n } else {\n DataPool::addOrFree(oldKeyVals, calcNumBytesTotal(oldMaxElementsWithBuffer));\n }\n }\n }\n }\n\n ROBIN_HOOD(NOINLINE) void throwOverflowError() const {\n#if ROBIN_HOOD(HAS_EXCEPTIONS)\n throw std::overflow_error(\"robin_hood::map overflow\");\n#else\n abort();\n#endif\n }\n\n template \n std::pair try_emplace_impl(OtherKey &&key, Args &&...args) {\n ROBIN_HOOD_TRACE(this)\n auto idxAndState = insertKeyPrepareEmptySpot(key);\n switch (idxAndState.second) {\n case InsertionState::key_found:\n break;\n\n case InsertionState::new_node:\n ::new (static_cast(&mKeyVals[idxAndState.first]))\n Node(*this,\n std::piecewise_construct,\n std::forward_as_tuple(std::forward(key)),\n std::forward_as_tuple(std::forward(args)...));\n break;\n\n case InsertionState::overwrite_node:\n mKeyVals[idxAndState.first] = Node(*this,\n std::piecewise_construct,\n std::forward_as_tuple(std::forward(key)),\n std::forward_as_tuple(std::forward(args)...));\n break;\n\n case InsertionState::overflow_error:\n throwOverflowError();\n break;\n }\n\n return std::make_pair(iterator(mKeyVals + idxAndState.first, mInfo + idxAndState.first),\n InsertionState::key_found != idxAndState.second);\n }\n\n template \n std::pair insertOrAssignImpl(OtherKey &&key, Mapped &&obj) {\n ROBIN_HOOD_TRACE(this)\n auto idxAndState = insertKeyPrepareEmptySpot(key);\n switch (idxAndState.second) {\n case InsertionState::key_found:\n mKeyVals[idxAndState.first].getSecond() = std::forward(obj);\n break;\n\n case InsertionState::new_node:\n ::new (static_cast(&mKeyVals[idxAndState.first]))\n Node(*this,\n std::piecewise_construct,\n std::forward_as_tuple(std::forward(key)),\n std::forward_as_tuple(std::forward(obj)));\n break;\n\n case InsertionState::overwrite_node:\n mKeyVals[idxAndState.first] = Node(*this,\n std::piecewise_construct,\n std::forward_as_tuple(std::forward(key)),\n std::forward_as_tuple(std::forward(obj)));\n break;\n\n case InsertionState::overflow_error:\n throwOverflowError();\n break;\n }\n\n return std::make_pair(iterator(mKeyVals + idxAndState.first, mInfo + idxAndState.first),\n InsertionState::key_found != idxAndState.second);\n }\n\n void initData(size_t max_elements) {\n mNumElements = 0;\n mMask = max_elements - 1;\n mMaxNumElementsAllowed = calcMaxNumElementsAllowed(max_elements);\n\n auto const numElementsWithBuffer = calcNumElementsWithBuffer(max_elements);\n\n // malloc & zero mInfo. Faster than calloc everything.\n auto const numBytesTotal = calcNumBytesTotal(numElementsWithBuffer);\n ROBIN_HOOD_LOG(\"std::calloc \" << numBytesTotal << \" = calcNumBytesTotal(\" << numElementsWithBuffer << \")\")\n mKeyVals = reinterpret_cast(detail::assertNotNull(hf3fs::memory::allocate(numBytesTotal)));\n mInfo = reinterpret_cast(mKeyVals + numElementsWithBuffer);\n std::memset(mInfo, 0, numBytesTotal - numElementsWithBuffer * sizeof(Node));\n\n // set sentinel\n mInfo[numElementsWithBuffer] = 1;\n\n mInfoInc = InitialInfoInc;\n mInfoHashShift = InitialInfoHashShift;\n }\n\n enum class InsertionState { overflow_error, key_found, new_node, overwrite_node };\n\n // Finds key, and if not already present prepares a spot where to pot the key & value.\n // This potentially shifts nodes out of the way, updates mInfo and number of inserted\n // elements, so the only operation left to do is create/assign a new node at that spot.\n template \n std::pair insertKeyPrepareEmptySpot(OtherKey &&key) {\n for (int i = 0; i < 256; ++i) {\n size_t idx{};\n InfoType info{};\n keyToIdx(key, &idx, &info);\n nextWhileLess(&info, &idx);\n\n // while we potentially have a match\n while (info == mInfo[idx]) {\n if (WKeyEqual::operator()(key, mKeyVals[idx].getFirst())) {\n // key already exists, do NOT insert.\n // see http://en.cppreference.com/w/cpp/container/unordered_map/insert\n return std::make_pair(idx, InsertionState::key_found);\n }\n next(&info, &idx);\n }\n\n // unlikely that this evaluates to true\n if (ROBIN_HOOD_UNLIKELY(mNumElements >= mMaxNumElementsAllowed)) {\n if (!increase_size()) {\n return std::make_pair(size_t(0), InsertionState::overflow_error);\n }\n continue;\n }\n\n // key not found, so we are now exactly where we want to insert it.\n auto const insertion_idx = idx;\n auto const insertion_info = info;\n if (ROBIN_HOOD_UNLIKELY(insertion_info + mInfoInc > 0xFF)) {\n mMaxNumElementsAllowed = 0;\n }\n\n // find an empty spot\n while (0 != mInfo[idx]) {\n next(&info, &idx);\n }\n\n if (idx != insertion_idx) {\n shiftUp(idx, insertion_idx);\n }\n // put at empty spot\n mInfo[insertion_idx] = static_cast(insertion_info);\n ++mNumElements;\n return std::make_pair(insertion_idx,\n idx == insertion_idx ? InsertionState::new_node : InsertionState::overwrite_node);\n }\n\n // enough attempts failed, so finally give up.\n return std::make_pair(size_t(0), InsertionState::overflow_error);\n }\n\n bool try_increase_info() {\n ROBIN_HOOD_LOG(\"mInfoInc=\" << mInfoInc << \", numElements=\" << mNumElements\n << \", maxNumElementsAllowed=\" << calcMaxNumElementsAllowed(mMask + 1))\n if (mInfoInc <= 2) {\n // need to be > 2 so that shift works (otherwise undefined behavior!)\n return false;\n }\n // we got space left, try to make info smaller\n mInfoInc = static_cast(mInfoInc >> 1U);\n\n // remove one bit of the hash, leaving more space for the distance info.\n // This is extremely fast because we can operate on 8 bytes at once.\n ++mInfoHashShift;\n auto const numElementsWithBuffer = calcNumElementsWithBuffer(mMask + 1);\n\n for (size_t i = 0; i < numElementsWithBuffer; i += 8) {\n auto val = unaligned_load(mInfo + i);\n val = (val >> 1U) & UINT64_C(0x7f7f7f7f7f7f7f7f);\n std::memcpy(mInfo + i, &val, sizeof(val));\n }\n // update sentinel, which might have been cleared out!\n mInfo[numElementsWithBuffer] = 1;\n\n mMaxNumElementsAllowed = calcMaxNumElementsAllowed(mMask + 1);\n return true;\n }\n\n // True if resize was possible, false otherwise\n bool increase_size() {\n // nothing allocated yet? just allocate InitialNumElements\n if (0 == mMask) {\n initData(InitialNumElements);\n return true;\n }\n\n auto const maxNumElementsAllowed = calcMaxNumElementsAllowed(mMask + 1);\n if (mNumElements < maxNumElementsAllowed && try_increase_info()) {\n return true;\n }\n\n ROBIN_HOOD_LOG(\"mNumElements=\" << mNumElements << \", maxNumElementsAllowed=\" << maxNumElementsAllowed << \", load=\"\n << (static_cast(mNumElements) * 100.0 / (static_cast(mMask) + 1)))\n\n if (mNumElements * 2 < calcMaxNumElementsAllowed(mMask + 1)) {\n // we have to resize, even though there would still be plenty of space left!\n // Try to rehash instead. Delete freed memory so we don't steadyily increase mem in case\n // we have to rehash a few times\n nextHashMultiplier();\n rehashPowerOfTwo(mMask + 1, true);\n } else {\n // we've reached the capacity of the map, so the hash seems to work nice. Keep using it.\n rehashPowerOfTwo((mMask + 1) * 2, false);\n }\n return true;\n }\n\n void nextHashMultiplier() {\n // adding an *even* number, so that the multiplier will always stay odd. This is necessary\n // so that the hash stays a mixing function (and thus doesn't have any information loss).\n mHashMultiplier += UINT64_C(0xc4ceb9fe1a85ec54);\n }\n\n void destroy() {\n if (0 == mMask) {\n // don't deallocate!\n return;\n }\n\n Destroyer::value>{}.nodesDoNotDeallocate(*this);\n\n // This protection against not deleting mMask shouldn't be needed as it's sufficiently\n // protected with the 0==mMask check, but I have this anyways because g++ 7 otherwise\n // reports a compile error: attempt to free a non-heap object 'fm'\n // [-Werror=free-nonheap-object]\n if (mKeyVals != reinterpret_cast_no_cast_align_warning(&mMask)) {\n ROBIN_HOOD_LOG(\"hf3fs::memory::deallocate\")\n hf3fs::memory::deallocate(mKeyVals);\n }\n }\n\n void init() noexcept {\n mKeyVals = reinterpret_cast_no_cast_align_warning(&mMask);\n mInfo = reinterpret_cast(&mMask);\n mNumElements = 0;\n mMask = 0;\n mMaxNumElementsAllowed = 0;\n mInfoInc = InitialInfoInc;\n mInfoHashShift = InitialInfoHashShift;\n }\n\n // members are sorted so no padding occurs\n uint64_t mHashMultiplier = UINT64_C(0xc4ceb9fe1a85ec53); // 8 byte 8\n Node *mKeyVals = reinterpret_cast_no_cast_align_warning(&mMask); // 8 byte 16\n uint8_t *mInfo = reinterpret_cast(&mMask); // 8 byte 24\n size_t mNumElements = 0; // 8 byte 32\n size_t mMask = 0; // 8 byte 40\n size_t mMaxNumElementsAllowed = 0; // 8 byte 48\n InfoType mInfoInc = InitialInfoInc; // 4 byte 52\n InfoType mInfoHashShift = InitialInfoHashShift; // 4 byte 56\n // 16 byte 56 if NodeAllocator\n};\n\n} // namespace detail\n\n// map\n\ntemplate ,\n typename KeyEqual = std::equal_to,\n size_t MaxLoadFactor100 = 80>\nusing unordered_flat_map = detail::Table;\n\ntemplate ,\n typename KeyEqual = std::equal_to,\n size_t MaxLoadFactor100 = 80>\nusing unordered_node_map = detail::Table;\n\ntemplate ,\n typename KeyEqual = std::equal_to,\n size_t MaxLoadFactor100 = 80>\nusing unordered_map = detail::Table) <= sizeof(size_t) * 6 &&\n std::is_nothrow_move_constructible>::value &&\n std::is_nothrow_move_assignable>::value,\n MaxLoadFactor100,\n Key,\n T,\n Hash,\n KeyEqual>;\n\n// set\n\ntemplate , typename KeyEqual = std::equal_to, size_t MaxLoadFactor100 = 80>\nusing unordered_flat_set = detail::Table;\n\ntemplate , typename KeyEqual = std::equal_to, size_t MaxLoadFactor100 = 80>\nusing unordered_node_set = detail::Table;\n\ntemplate , typename KeyEqual = std::equal_to, size_t MaxLoadFactor100 = 80>\nusing unordered_set =\n detail::Table::value &&\n std::is_nothrow_move_assignable::value,\n MaxLoadFactor100,\n Key,\n void,\n Hash,\n KeyEqual>;\n\n} // namespace robin_hood\n\n#endif\n"], ["/3FS/src/fuse/PioV.h", "#pragma once\n\n#include \n\n#include \"client/meta/MetaClient.h\"\n#include \"client/storage/StorageClient.h\"\n#include \"common/utils/Result.h\"\n\nnamespace hf3fs::lib::agent {\nusing flat::UserInfo;\nclass PioV {\n public:\n PioV(storage::client::StorageClient &storageClient, int chunkSizeLim, std::vector &res);\n hf3fs::Result addRead(size_t idx,\n const meta::Inode &inode,\n uint16_t track,\n off_t off,\n size_t len,\n void *buf,\n storage::client::IOBuffer &memh);\n // if metaClient and userInfo are not nullptr,\n // meta server will be contacted for latest file length if known length is shorter than off\n CoTryTask checkWriteOff(size_t idx,\n meta::client::MetaClient *metaClient,\n const UserInfo *userInfo,\n const meta::Inode &inode,\n size_t off);\n hf3fs::Result addWrite(size_t idx,\n const meta::Inode &inode,\n uint16_t track,\n off_t off,\n size_t len,\n const void *buf,\n storage::client::IOBuffer &memh);\n CoTryTask executeRead(const UserInfo &userInfo,\n const storage::client::ReadOptions &options = storage::client::ReadOptions());\n CoTryTask executeWrite(const UserInfo &userInfo,\n const storage::client::WriteOptions &options = storage::client::WriteOptions());\n void finishIo(bool allowHoles);\n\n private:\n Result chunkIo(\n const meta::Inode &inode,\n uint16_t track,\n off_t off,\n size_t len,\n std::function &&consumeChunk);\n\n private:\n storage::client::StorageClient &storageClient_;\n int chunkSizeLim_;\n std::shared_ptr routingInfo_;\n std::vector &res_;\n std::vector rios_;\n std::vector wios_;\n std::vector trops_;\n std::map potentialLens_;\n};\n} // namespace hf3fs::lib::agent\n"], ["/3FS/src/common/monitor/MonitorCollectorClient.h", "#pragma once\n\n#include \"common/monitor/LogReporter.h\"\n#include \"common/monitor/Reporter.h\"\n#include \"common/monitor/Sample.h\"\n#include \"common/net/Client.h\"\n#include \"common/utils/Address.h\"\n#include \"common/utils/ConfigBase.h\"\n\nnamespace hf3fs::monitor {\n\nclass MonitorCollectorClient : public Reporter {\n public:\n struct Config : ConfigBase {\n CONFIG_ITEM(remote_ip, \"\"); // format: 127.0.0.1:10000\n CONFIG_OBJ(client, net::Client::Config);\n };\n\n MonitorCollectorClient(const Config &config)\n : config_(config) {}\n ~MonitorCollectorClient() override { stop(); }\n\n Result init() final;\n void stop();\n\n Result commit(const std::vector &samples) final;\n\n private:\n const Config &config_;\n std::unique_ptr client_;\n std::unique_ptr ctx_;\n};\n\n} // namespace hf3fs::monitor\n"], ["/3FS/src/fdb/FDBKVEngine.h", "#pragma once\n\n#include \n#include \n\n#include \"FDB.h\"\n#include \"FDBTransaction.h\"\n#include \"common/kv/IKVEngine.h\"\n\nnamespace hf3fs {\n\nnamespace meta {\ntemplate \nclass MetaTestBase;\n}\n\nnamespace kv {\nclass FDBKVEngine : public IKVEngine {\n public:\n FDBKVEngine(fdb::DB db)\n : db_(std::move(db)) {}\n\n std::unique_ptr createReadonlyTransaction() override { return createReadWriteTransaction(); }\n\n std::unique_ptr createReadWriteTransaction() override {\n fdb::Transaction tr(db_);\n if (UNLIKELY(tr.error())) {\n return nullptr;\n }\n return std::make_unique(std::move(tr));\n }\n\n private:\n template \n friend class hf3fs::meta::MetaTestBase;\n\n FRIEND_TEST(TestFDBTransaction, Readonly);\n\n void setReadonly(bool rdonly) { db_.readonly_ = rdonly; }\n\n fdb::DB db_;\n};\n} // namespace kv\n\n} // namespace hf3fs\n"], ["/3FS/src/client/storage/TargetSelection.h", "#pragma once\n\n#include \n#include \n#include \n\n#include \"common/utils/StatusCodeDetails.h\"\n#include \"fbs/storage/Common.h\"\n\nnamespace hf3fs::storage::client {\n\n/* Slim routing info */\n\nstruct SlimTargetInfo {\n TargetId targetId;\n NodeId nodeId;\n\n bool operator==(const SlimTargetInfo &other) const = default;\n};\n\nstruct SlimChainInfo {\n ChainId chainId;\n ChainVer version;\n flat::RoutingInfoVersion routingInfoVer;\n size_t totalNumTargets; // total number of targets including non-serving targets\n std::vector servingTargets;\n};\n\nenum TargetSelectionMode {\n Default = 0,\n LoadBalance,\n RoundRobin,\n RandomTarget,\n TailTarget,\n HeadTarget,\n ManualMode,\n EndOfMode\n};\n\nclass TargetSelectionOptions : public hf3fs::ConfigBase {\n // if mode = Tail/Head, but tail/head is not in the specified traffic zone, the read could fail\n // if mode = LB/RR/Random, only storage targets hosted in the specified traffic zone are selected\n CONFIG_HOT_UPDATED_ITEM(mode, TargetSelectionMode::Default);\n CONFIG_HOT_UPDATED_ITEM(targetIndex, 0U); // the target chosen by user in ManualMode\n CONFIG_HOT_UPDATED_ITEM(trafficZone, \"\");\n};\n\n// An instance of each TargetSelectionStrategy implementation is created for each batch read.\nclass TargetSelectionStrategy {\n public:\n TargetSelectionStrategy(const TargetSelectionOptions &options)\n : options_(options) {}\n\n virtual ~TargetSelectionStrategy() = default;\n\n // selectTarget() is called for each read IO in the batch.\n virtual Result selectTarget(const SlimChainInfo &chain) = 0;\n\n virtual bool selectAnyTarget() { return false; }\n\n // reset the internal states\n virtual void reset() {}\n\n static std::unique_ptr create(const TargetSelectionOptions &options);\n\n protected:\n static constexpr size_t kNodeIdKeyedMapExpectedNumElements = 1000;\n TargetSelectionOptions options_;\n};\n\n} // namespace hf3fs::storage::client\n"], ["/3FS/src/storage/aio/BatchReadJob.h", "#pragma once\n\n#include \n#include \n\n#include \"chunk_engine/src/cxx.rs.h\"\n#include \"common/net/ib/IBSocket.h\"\n#include \"common/serde/CallContext.h\"\n#include \"common/utils/Duration.h\"\n#include \"fbs/storage/Common.h\"\n#include \"storage/store/ChunkMetadata.h\"\n\nnamespace hf3fs::storage {\n\nclass BatchReadJob;\nclass StorageTarget;\n\nclass ChunkEngineReadJob {\n public:\n ChunkEngineReadJob() = default;\n ChunkEngineReadJob(const ChunkEngineReadJob &) = delete;\n ChunkEngineReadJob(ChunkEngineReadJob &&other)\n : engine_(std::exchange(other.engine_, nullptr)),\n chunk_(std::exchange(other.chunk_, nullptr)) {}\n\n void set(chunk_engine::Engine *engine, const chunk_engine::Chunk *chunk) {\n reset();\n engine_ = engine;\n chunk_ = chunk;\n }\n\n void reset() {\n if (engine_ && chunk_) {\n std::exchange(engine_, nullptr)->release_raw_chunk(chunk_);\n }\n }\n\n auto chunk() const { return chunk_; }\n\n bool has_chunk() const { return chunk_ != nullptr; }\n\n ~ChunkEngineReadJob() { reset(); }\n\n private:\n chunk_engine::Engine *engine_{};\n const chunk_engine::Chunk *chunk_{};\n};\n\nclass AioReadJob {\n public:\n AioReadJob(const ReadIO &readIO, IOResult &result, BatchReadJob &batch);\n\n auto &readIO() { return readIO_; }\n auto &result() { return result_; }\n auto &batch() { return batch_; }\n auto &state() { return state_; }\n\n void setResult(Result lengthInfo);\n\n uint32_t alignedOffset() const { return readIO_.offset - state_.headLength; }\n uint32_t alignedLength() const { return readIO_.length + state_.headLength + state_.tailLength; }\n\n auto startTime() const { return startTime_; }\n void resetStartTime() { startTime_ = RelativeTime::now(); }\n\n private:\n const ReadIO &readIO_;\n IOResult &result_;\n BatchReadJob &batch_;\n struct State {\n net::RDMABuf localbuf{};\n StorageTarget *storageTarget = nullptr;\n ChunkEngineReadJob chunkEngineJob{};\n SERDE_STRUCT_FIELD(headLength, uint32_t{});\n SERDE_STRUCT_FIELD(tailLength, uint32_t{});\n SERDE_STRUCT_FIELD(readLength, uint32_t{}); // after cropping.\n SERDE_STRUCT_FIELD(readFd, int32_t{});\n SERDE_STRUCT_FIELD(readOffset, uint64_t{});\n SERDE_STRUCT_FIELD(chunkLen, uint32_t{});\n SERDE_STRUCT_FIELD(bufferIndex, uint32_t{});\n SERDE_STRUCT_FIELD(fdIndex, std::optional{});\n SERDE_STRUCT_FIELD(chunkChecksum, ChecksumInfo{});\n SERDE_STRUCT_FIELD(readUncommitted, false);\n } state_;\n static_assert(serde::Serializable);\n RelativeTime startTime_{};\n};\n\nclass BatchReadJob {\n public:\n BatchReadJob(std::span readIOs, std::span results, ChecksumType checksumType);\n BatchReadJob(const ReadIO &readIO, StorageTarget *target, IOResult &result, ChecksumType checksumType)\n : BatchReadJob(std::span(&readIO, 1), std::span(&result, 1), checksumType) {\n jobs_.back().state().storageTarget = target;\n }\n CoTask complete() { co_await baton_; }\n size_t addBufferToBatch(serde::CallContext::RDMATransmission &batch);\n size_t copyToRespBuffer(std::vector &buffer);\n void finish(AioReadJob *job);\n auto checksumType() const { return checksumType_; }\n bool recalculateChecksum() const { return recalculateChecksum_; }\n void setRecalculateChecksum(bool value = true) { recalculateChecksum_ = value; }\n auto &front() { return jobs_.front(); }\n auto &front() const { return jobs_.front(); }\n auto startTime() const { return startTime_.load(); }\n void resetStartTime() { startTime_ = RelativeTime::now(); }\n\n private:\n friend class AioReadJobIterator;\n std::vector jobs_;\n folly::coro::Baton baton_;\n std::atomic finishedCount_{};\n std::atomic startTime_ = RelativeTime::now();\n const ChecksumType checksumType_;\n bool recalculateChecksum_ = false;\n};\n\nclass AioReadJobIterator {\n public:\n AioReadJobIterator() = default;\n AioReadJobIterator(BatchReadJob *batch)\n : batch_(batch),\n end_(batch->jobs_.size()) {}\n AioReadJobIterator(BatchReadJob *batch, uint32_t start, uint32_t size)\n : batch_(batch),\n begin_(start),\n end_(std::min((uint32_t)batch->jobs_.size(), start + size)) {}\n\n operator bool() const { return begin_ < end_; }\n bool isNull() const { return batch_ == nullptr; }\n AioReadJob &operator*() { return batch_->jobs_[begin_]; }\n AioReadJob *operator->() { return &batch_->jobs_[begin_]; }\n AioReadJob *operator++(int) { return &batch_->jobs_[begin_++]; }\n\n auto startTime() const { return startTime_; }\n auto resetStartTime() { startTime_ = RelativeTime::now(); }\n\n private:\n BatchReadJob *batch_ = nullptr;\n uint32_t begin_ = 0;\n uint32_t end_ = 0;\n RelativeTime startTime_ = RelativeTime::now();\n};\n\n} // namespace hf3fs::storage\n"], ["/3FS/src/common/serde/Service.h", "#pragma once\n\n#include \"common/serde/MessagePacket.h\"\n#include \"common/serde/Serde.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/Reflection.h\"\n\nnamespace hf3fs::net {\nstruct UserRequestOptions;\n}\n\nnamespace hf3fs::serde {\n\ntemplate \nstruct ServiceBase {\n static constexpr auto kServiceNameWrapper = NAME;\n static constexpr std::string_view kServiceName = NAME;\n static constexpr uint16_t kServiceID = ID;\n};\n\ntemplate \nstruct MethodInfo {\n static constexpr auto nameWrapper = NAME;\n static constexpr std::string_view name = NAME;\n using Object = T;\n using ReqType = REQ;\n using RspType = RSP;\n static constexpr auto id = ID;\n static constexpr auto method = METHOD;\n};\n\ntemplate \nconstexpr inline uint16_t MaxMethodId = 0;\ntemplate \nconstexpr inline uint16_t MaxMethodId> = std::max({T::id...});\n\ntemplate class Service>\nstruct ServiceWrapper {\n static constexpr std::string_view kServiceName = Service::kServiceName;\n static constexpr uint16_t kServiceID = Service::kServiceID;\n\n protected:\n friend struct ::hf3fs::refl::Helper;\n template \n static auto CollectField(::hf3fs::refl::Rank<> rank) -> refl::Helper::FieldInfoList>;\n};\n\ntemplate \nclass MethodExtractor {\n public:\n static auto get(uint16_t id) {\n constexpr MethodExtractor ins;\n return id <= ins.kMaxThreadId ? ins.table[id] : DEFAULT;\n }\n\n protected:\n consteval MethodExtractor() {\n for (uint16_t i = 0; i <= kMaxThreadId; ++i) {\n table[i] = calc(i);\n }\n }\n\n template \n consteval auto calc(uint16_t id) {\n if constexpr (I == std::tuple_size_v) {\n return DEFAULT;\n } else {\n using FieldInfo = std::tuple_element_t;\n return FieldInfo::id == id ? &C::template call : calc(id);\n }\n }\n\n private:\n using FieldInfoList = refl::Helper::FieldInfoList;\n using Method = decltype(&C::template call>);\n static constexpr auto kMaxThreadId = MaxMethodId;\n std::array table;\n};\n\n#define SERDE_SERVICE(NAME, ID) SERDE_SERVICE_2(NAME, NAME, ID)\n\n#define SERDE_SERVICE_2(STRUCT_NAME, SERVICE_NAME, ID) \\\n template \\\n struct STRUCT_NAME : public ::hf3fs::serde::ServiceBase<#SERVICE_NAME, ID>\n\n#define SERDE_SERVICE_METHOD(NAME, ID, REQ, RSP) \\\n SERDE_SERVICE_METHOD_SENDER(NAME, ID, REQ, RSP) \\\n SERDE_SERVICE_METHOD_REFL(NAME, ID, REQ, RSP)\n\n#define SERDE_SERVICE_METHOD_SENDER(NAME, ID, REQ, RSP) \\\n public: \\\n static constexpr auto NAME##MethodId = ID; \\\n \\\n template \\\n static CoTryTask NAME(Context &ctx, \\\n const REQ &req, \\\n const ::hf3fs::net::UserRequestOptions *options = nullptr, \\\n ::hf3fs::serde::Timestamp * timestamp = nullptr) { \\\n co_return co_await ctx.template call(req, \\\n options, \\\n timestamp); \\\n } \\\n \\\n template \\\n static Result NAME##Sync(Context &ctx, \\\n const REQ &req, \\\n const ::hf3fs::net::UserRequestOptions *options = nullptr, \\\n ::hf3fs::serde::Timestamp * timestamp = nullptr) { \\\n return ctx.template callSync(req, \\\n options, \\\n timestamp); \\\n }\n\n#define SERDE_SERVICE_METHOD_REFL(NAME, ID, REQ, RSP) \\\n private: \\\n struct MethodId##ID : std::type_identity {}; \\\n static auto CollectField(::hf3fs::refl::Rank + 1>) { \\\n if constexpr (std::is_void_v) { \\\n return ::hf3fs::refl::Append_t>{}; \\\n } else { \\\n return ::hf3fs::refl::Append_t>{}; \\\n } \\\n } \\\n friend struct ::hf3fs::refl::Helper\n\n#define SERDE_SERVICE_CLIENT(CLIENT_NAME, BASE_NAME) \\\n template \\\n struct CLIENT_NAME { \\\n static constexpr auto kServiceName = BASE_NAME::kServiceName; \\\n static constexpr auto kServiceID = BASE_NAME::kServiceID; \\\n \\\n template \\\n static auto send(Context &ctx, \\\n const Req &req, \\\n const ::hf3fs::net::UserRequestOptions *options = nullptr, \\\n ::hf3fs::serde::Timestamp *timestamp = nullptr) { \\\n auto handler = [&](auto type) requires(decltype(type)::name == name && \\\n std::is_same_v) { \\\n using M = std::decay_t; \\\n return ctx.template call::kServiceNameWrapper, \\\n name, \\\n typename M::ReqType, \\\n typename M::RspType, \\\n BASE_NAME::kServiceID, \\\n M::id>(req, options, timestamp); \\\n }; \\\n return ::hf3fs::refl::Helper::visit>(std::move(handler)); \\\n } \\\n }\n\n} // namespace hf3fs::serde\n"], ["/3FS/src/common/utils/ArgParse.h", "/*\n __ _ _ __ __ _ _ __ __ _ _ __ ___ ___\n / _` | '__/ _` | '_ \\ / _` | '__/ __|/ _ \\ Argument Parser for Modern C++\n| (_| | | | (_| | |_) | (_| | | \\__ \\ __/ http://github.com/p-ranav/argparse\n \\__,_|_| \\__, | .__/ \\__,_|_| |___/\\___|\n |___/|_|\n\nLicensed under the MIT License .\nSPDX-License-Identifier: MIT\nCopyright (c) 2019-2022 Pranav Srinivas Kumar \nand other contributors.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n#pragma once\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace argparse {\n\nnamespace details { // namespace for helper methods\n\ntemplate \nstruct HasContainerTraits : std::false_type {};\n\ntemplate <>\nstruct HasContainerTraits : std::false_type {};\n\ntemplate <>\nstruct HasContainerTraits : std::false_type {};\n\ntemplate \nstruct HasContainerTraits().begin()),\n decltype(std::declval().end()),\n decltype(std::declval().size())>> : std::true_type {};\n\ntemplate \nstatic constexpr bool IsContainer = HasContainerTraits::value;\n\ntemplate \nstruct HasStreamableTraits : std::false_type {};\n\ntemplate \nstruct HasStreamableTraits() << std::declval())>>\n : std::true_type {};\n\ntemplate \nstatic constexpr bool IsStreamable = HasStreamableTraits::value;\n\nconstexpr std::size_t repr_max_container_size = 5;\n\ntemplate \nstd::string repr(T const &val) {\n if constexpr (std::is_same_v) {\n return val ? \"true\" : \"false\";\n } else if constexpr (std::is_convertible_v) {\n return '\"' + std::string{std::string_view{val}} + '\"';\n } else if constexpr (IsContainer) {\n std::stringstream out;\n out << \"{\";\n const auto size = val.size();\n if (size > 1) {\n out << repr(*val.begin());\n std::for_each(std::next(val.begin()),\n std::next(val.begin(),\n static_cast(\n std::min(size, repr_max_container_size) - 1)),\n [&out](const auto &v) { out << \" \" << repr(v); });\n if (size <= repr_max_container_size) {\n out << \" \";\n } else {\n out << \"...\";\n }\n }\n if (size > 0) {\n out << repr(*std::prev(val.end()));\n }\n out << \"}\";\n return out.str();\n } else if constexpr (IsStreamable) {\n std::stringstream out;\n out << val;\n return out.str();\n } else {\n return \"\";\n }\n}\n\nnamespace {\n\ntemplate \nconstexpr bool standard_signed_integer = false;\ntemplate <>\nconstexpr bool standard_signed_integer = true;\ntemplate <>\nconstexpr bool standard_signed_integer = true;\ntemplate <>\nconstexpr bool standard_signed_integer = true;\ntemplate <>\nconstexpr bool standard_signed_integer = true;\ntemplate <>\nconstexpr bool standard_signed_integer = true;\n\ntemplate \nconstexpr bool standard_unsigned_integer = false;\ntemplate <>\nconstexpr bool standard_unsigned_integer = true;\ntemplate <>\nconstexpr bool standard_unsigned_integer = true;\ntemplate <>\nconstexpr bool standard_unsigned_integer = true;\ntemplate <>\nconstexpr bool standard_unsigned_integer = true;\ntemplate <>\nconstexpr bool standard_unsigned_integer = true;\n\n} // namespace\n\nconstexpr int radix_8 = 8;\nconstexpr int radix_10 = 10;\nconstexpr int radix_16 = 16;\n\ntemplate \nconstexpr bool standard_integer = standard_signed_integer || standard_unsigned_integer;\n\ntemplate \nconstexpr decltype(auto) apply_plus_one_impl(F &&f, Tuple &&t, Extra &&x, std::index_sequence /*unused*/) {\n return std::invoke(std::forward(f), std::get(std::forward(t))..., std::forward(x));\n}\n\ntemplate \nconstexpr decltype(auto) apply_plus_one(F &&f, Tuple &&t, Extra &&x) {\n return details::apply_plus_one_impl(std::forward(f),\n std::forward(t),\n std::forward(x),\n std::make_index_sequence>>{});\n}\n\nconstexpr auto pointer_range(std::string_view s) noexcept { return std::tuple(s.data(), s.data() + s.size()); }\n\ntemplate \nconstexpr bool starts_with(std::basic_string_view prefix,\n std::basic_string_view s) noexcept {\n return s.substr(0, prefix.size()) == prefix;\n}\n\nenum class chars_format { scientific = 0x1, fixed = 0x2, hex = 0x4, general = fixed | scientific };\n\nstruct ConsumeHexPrefixResult {\n bool is_hexadecimal;\n std::string_view rest;\n};\n\nusing namespace std::literals;\n\nconstexpr auto consume_hex_prefix(std::string_view s) -> ConsumeHexPrefixResult {\n if (starts_with(\"0x\"sv, s) || starts_with(\"0X\"sv, s)) {\n s.remove_prefix(2);\n return {true, s};\n }\n return {false, s};\n}\n\ntemplate \ninline auto do_from_chars(std::string_view s) -> T {\n T x;\n auto [first, last] = pointer_range(s);\n auto [ptr, ec] = std::from_chars(first, last, x, Param);\n if (ec == std::errc()) {\n if (ptr == last) {\n return x;\n }\n throw std::invalid_argument{\"pattern does not match to the end\"};\n }\n if (ec == std::errc::invalid_argument) {\n throw std::invalid_argument{\"pattern not found\"};\n }\n if (ec == std::errc::result_out_of_range) {\n throw std::range_error{\"not representable\"};\n }\n return x; // unreachable\n}\n\ntemplate \nstruct parse_number {\n auto operator()(std::string_view s) -> T { return do_from_chars(s); }\n};\n\ntemplate \nstruct parse_number {\n auto operator()(std::string_view s) -> T {\n if (auto [ok, rest] = consume_hex_prefix(s); ok) {\n return do_from_chars(rest);\n }\n throw std::invalid_argument{\"pattern not found\"};\n }\n};\n\ntemplate \nstruct parse_number {\n auto operator()(std::string_view s) -> T {\n auto [ok, rest] = consume_hex_prefix(s);\n if (ok) {\n return do_from_chars(rest);\n }\n if (starts_with(\"0\"sv, s)) {\n return do_from_chars(rest);\n }\n return do_from_chars(rest);\n }\n};\n\nnamespace {\n\ntemplate \ninline const auto generic_strtod = nullptr;\ntemplate <>\ninline const auto generic_strtod = strtof;\ntemplate <>\ninline const auto generic_strtod = strtod;\ntemplate <>\ninline const auto generic_strtod = strtold;\n\n} // namespace\n\ntemplate \ninline auto do_strtod(std::string const &s) -> T {\n if (isspace(static_cast(s[0])) || s[0] == '+') {\n throw std::invalid_argument{\"pattern not found\"};\n }\n\n auto [first, last] = pointer_range(s);\n char *ptr;\n\n errno = 0;\n auto x = generic_strtod(first, &ptr);\n if (errno == 0) {\n if (ptr == last) {\n return x;\n }\n throw std::invalid_argument{\"pattern does not match to the end\"};\n }\n if (errno == ERANGE) {\n throw std::range_error{\"not representable\"};\n }\n return x; // unreachable\n}\n\ntemplate \nstruct parse_number {\n auto operator()(std::string const &s) -> T {\n if (auto r = consume_hex_prefix(s); r.is_hexadecimal) {\n throw std::invalid_argument{\"chars_format::general does not parse hexfloat\"};\n }\n\n return do_strtod(s);\n }\n};\n\ntemplate \nstruct parse_number {\n auto operator()(std::string const &s) -> T {\n if (auto r = consume_hex_prefix(s); !r.is_hexadecimal) {\n throw std::invalid_argument{\"chars_format::hex parses hexfloat\"};\n }\n\n return do_strtod(s);\n }\n};\n\ntemplate \nstruct parse_number {\n auto operator()(std::string const &s) -> T {\n if (auto r = consume_hex_prefix(s); r.is_hexadecimal) {\n throw std::invalid_argument{\"chars_format::scientific does not parse hexfloat\"};\n }\n if (s.find_first_of(\"eE\") == std::string::npos) {\n throw std::invalid_argument{\"chars_format::scientific requires exponent part\"};\n }\n\n return do_strtod(s);\n }\n};\n\ntemplate \nstruct parse_number {\n auto operator()(std::string const &s) -> T {\n if (auto r = consume_hex_prefix(s); r.is_hexadecimal) {\n throw std::invalid_argument{\"chars_format::fixed does not parse hexfloat\"};\n }\n if (s.find_first_of(\"eE\") != std::string::npos) {\n throw std::invalid_argument{\"chars_format::fixed does not parse exponent part\"};\n }\n\n return do_strtod(s);\n }\n};\n\ntemplate \nstd::string join(StrIt first, StrIt last, const std::string &separator) {\n if (first == last) {\n return \"\";\n }\n std::stringstream value;\n value << *first;\n ++first;\n while (first != last) {\n value << separator << *first;\n ++first;\n }\n return value.str();\n}\n\n} // namespace details\n\nenum class nargs_pattern { optional, any, at_least_one };\n\nenum class default_arguments : unsigned int {\n none = 0,\n help = 1,\n version = 2,\n all = help | version,\n};\n\ninline default_arguments operator&(const default_arguments &a, const default_arguments &b) {\n return static_cast(static_cast::type>(a) &\n static_cast::type>(b));\n}\n\nclass ArgumentParser;\n\nclass Argument {\n friend class ArgumentParser;\n friend auto operator<<(std::ostream &stream, const ArgumentParser &parser) -> std::ostream &;\n\n template \n explicit Argument(std::string_view prefix_chars,\n std::array &&a,\n std::index_sequence /*unused*/)\n : m_is_optional((is_optional(a[I], prefix_chars) || ...)),\n m_is_required(false),\n m_is_repeatable(false),\n m_is_used(false),\n m_prefix_chars(prefix_chars) {\n ((void)m_names.emplace_back(a[I]), ...);\n std::sort(m_names.begin(), m_names.end(), [](const auto &lhs, const auto &rhs) {\n return lhs.size() == rhs.size() ? lhs < rhs : lhs.size() < rhs.size();\n });\n }\n\n public:\n template \n explicit Argument(std::string_view prefix_chars, std::array &&a)\n : Argument(prefix_chars, std::move(a), std::make_index_sequence{}) {}\n\n Argument &help(std::string help_text) {\n m_help = std::move(help_text);\n return *this;\n }\n\n Argument &metavar(std::string metavar) {\n m_metavar = std::move(metavar);\n return *this;\n }\n\n template \n Argument &default_value(T &&value) {\n m_default_value_repr = details::repr(value);\n m_default_value = std::forward(value);\n return *this;\n }\n\n Argument &required() {\n m_is_required = true;\n return *this;\n }\n\n Argument &implicit_value(std::any value) {\n m_implicit_value = std::move(value);\n m_num_args_range = NArgsRange{0, 0};\n return *this;\n }\n\n template \n auto action(F &&callable, Args &&...bound_args)\n -> std::enable_if_t, Argument &> {\n using action_type = std::\n conditional_t>, void_action, valued_action>;\n if constexpr (sizeof...(Args) == 0) {\n m_action.emplace(std::forward(callable));\n } else {\n m_action.emplace(\n [f = std::forward(callable), tup = std::make_tuple(std::forward(bound_args)...)](\n std::string const &opt) mutable { return details::apply_plus_one(f, tup, opt); });\n }\n return *this;\n }\n\n auto &append() {\n m_is_repeatable = true;\n return *this;\n }\n\n template \n auto scan() -> std::enable_if_t, Argument &> {\n static_assert(!(std::is_const_v || std::is_volatile_v), \"T should not be cv-qualified\");\n auto is_one_of = [](char c, auto... x) constexpr { return ((c == x) || ...); };\n\n if constexpr (is_one_of(Shape, 'd') && details::standard_integer) {\n action(details::parse_number());\n } else if constexpr (is_one_of(Shape, 'i') && details::standard_integer) {\n action(details::parse_number());\n } else if constexpr (is_one_of(Shape, 'u') && details::standard_unsigned_integer) {\n action(details::parse_number());\n } else if constexpr (is_one_of(Shape, 'o') && details::standard_unsigned_integer) {\n action(details::parse_number());\n } else if constexpr (is_one_of(Shape, 'x', 'X') && details::standard_unsigned_integer) {\n action(details::parse_number());\n } else if constexpr (is_one_of(Shape, 'a', 'A') && std::is_floating_point_v) {\n action(details::parse_number());\n } else if constexpr (is_one_of(Shape, 'e', 'E') && std::is_floating_point_v) {\n action(details::parse_number());\n } else if constexpr (is_one_of(Shape, 'f', 'F') && std::is_floating_point_v) {\n action(details::parse_number());\n } else if constexpr (is_one_of(Shape, 'g', 'G') && std::is_floating_point_v) {\n action(details::parse_number());\n } else {\n static_assert(alignof(T) == 0, \"No scan specification for T\");\n }\n\n return *this;\n }\n\n Argument &nargs(std::size_t num_args) {\n m_num_args_range = NArgsRange{num_args, num_args};\n return *this;\n }\n\n Argument &nargs(std::size_t num_args_min, std::size_t num_args_max) {\n m_num_args_range = NArgsRange{num_args_min, num_args_max};\n return *this;\n }\n\n Argument &nargs(nargs_pattern pattern) {\n switch (pattern) {\n case nargs_pattern::optional:\n m_num_args_range = NArgsRange{0, 1};\n break;\n case nargs_pattern::any:\n m_num_args_range = NArgsRange{0, std::numeric_limits::max()};\n break;\n case nargs_pattern::at_least_one:\n m_num_args_range = NArgsRange{1, std::numeric_limits::max()};\n break;\n }\n return *this;\n }\n\n Argument &remaining() {\n m_accepts_optional_like_value = true;\n return nargs(nargs_pattern::any);\n }\n\n template \n Iterator consume(Iterator start, Iterator end, std::string_view used_name = {}) {\n if (!m_is_repeatable && m_is_used) {\n throw std::runtime_error(\"Duplicate argument\");\n }\n m_is_used = true;\n m_used_name = used_name;\n\n const auto num_args_max = m_num_args_range.get_max();\n const auto num_args_min = m_num_args_range.get_min();\n std::size_t dist = 0;\n if (num_args_max == 0) {\n m_values.emplace_back(m_implicit_value);\n std::visit([](const auto &f) { f({}); }, m_action);\n return start;\n }\n if ((dist = static_cast(std::distance(start, end))) >= num_args_min) {\n if (num_args_max < dist) {\n end = std::next(start, static_cast(num_args_max));\n }\n if (!m_accepts_optional_like_value) {\n end = std::find_if(start, end, std::bind(is_optional, std::placeholders::_1, m_prefix_chars));\n dist = static_cast(std::distance(start, end));\n if (dist < num_args_min) {\n throw std::runtime_error(\"Too few arguments\");\n }\n }\n\n struct ActionApply {\n void operator()(valued_action &f) { std::transform(first, last, std::back_inserter(self.m_values), f); }\n\n void operator()(void_action &f) {\n std::for_each(first, last, f);\n if (!self.m_default_value.has_value()) {\n if (!self.m_accepts_optional_like_value) {\n self.m_values.resize(static_cast(std::distance(first, last)));\n }\n }\n }\n\n Iterator first, last;\n Argument &self;\n };\n std::visit(ActionApply{start, end, *this}, m_action);\n return end;\n }\n if (m_default_value.has_value()) {\n return start;\n }\n throw std::runtime_error(\"Too few arguments for '\" + std::string(m_used_name) + \"'.\");\n }\n\n /*\n * @throws std::runtime_error if argument values are not valid\n */\n void validate() const {\n if (m_is_optional) {\n // TODO: check if an implicit value was programmed for this argument\n if (!m_is_used && !m_default_value.has_value() && m_is_required) {\n throw_required_arg_not_used_error();\n }\n if (m_is_used && m_is_required && m_values.empty()) {\n throw_required_arg_no_value_provided_error();\n }\n } else {\n if (!m_num_args_range.contains(m_values.size()) && !m_default_value.has_value()) {\n throw_nargs_range_validation_error();\n }\n }\n }\n\n std::string get_inline_usage() const {\n std::stringstream usage;\n // Find the longest variant to show in the usage string\n std::string longest_name = m_names.front();\n for (const auto &s : m_names) {\n if (s.size() > longest_name.size()) {\n longest_name = s;\n }\n }\n if (!m_is_required) {\n usage << \"[\";\n }\n usage << longest_name;\n const std::string metavar = !m_metavar.empty() ? m_metavar : \"VAR\";\n if (m_num_args_range.get_max() > 0) {\n usage << \" \" << metavar;\n if (m_num_args_range.get_max() > 1) {\n usage << \"...\";\n }\n }\n if (!m_is_required) {\n usage << \"]\";\n }\n return usage.str();\n }\n\n std::size_t get_arguments_length() const {\n std::size_t names_size =\n std::accumulate(std::begin(m_names), std::end(m_names), std::size_t(0), [](const auto &sum, const auto &s) {\n return sum + s.size();\n });\n\n if (is_positional(m_names.front(), m_prefix_chars)) {\n // A set metavar means this replaces the names\n if (!m_metavar.empty()) {\n // Indent and metavar\n return 2 + m_metavar.size();\n }\n\n // Indent and space-separated\n return 2 + names_size + (m_names.size() - 1);\n }\n // Is an option - include both names _and_ metavar\n // size = text + (\", \" between names)\n std::size_t size = names_size + 2 * (m_names.size() - 1);\n if (!m_metavar.empty() && m_num_args_range == NArgsRange{1, 1}) {\n size += m_metavar.size() + 1;\n }\n return size + 2; // indent\n }\n\n friend std::ostream &operator<<(std::ostream &stream, const Argument &argument) {\n std::stringstream name_stream;\n name_stream << \" \"; // indent\n if (argument.is_positional(argument.m_names.front(), argument.m_prefix_chars)) {\n if (!argument.m_metavar.empty()) {\n name_stream << argument.m_metavar;\n } else {\n name_stream << details::join(argument.m_names.begin(), argument.m_names.end(), \" \");\n }\n } else {\n name_stream << details::join(argument.m_names.begin(), argument.m_names.end(), \", \");\n // If we have a metavar, and one narg - print the metavar\n if (!argument.m_metavar.empty() && argument.m_num_args_range == NArgsRange{1, 1}) {\n name_stream << \" \" << argument.m_metavar;\n }\n }\n stream << name_stream.str() << \"\\t\" << argument.m_help;\n\n // print nargs spec\n if (!argument.m_help.empty()) {\n stream << \" \";\n }\n stream << argument.m_num_args_range;\n\n if (argument.m_default_value.has_value() && argument.m_num_args_range != NArgsRange{0, 0}) {\n stream << \"[default: \" << argument.m_default_value_repr << \"]\";\n } else if (argument.m_is_required) {\n stream << \"[required]\";\n }\n stream << \"\\n\";\n return stream;\n }\n\n template \n bool operator!=(const T &rhs) const {\n return !(*this == rhs);\n }\n\n /*\n * Compare to an argument value of known type\n * @throws std::logic_error in case of incompatible types\n */\n template \n bool operator==(const T &rhs) const {\n if constexpr (!details::IsContainer) {\n return get() == rhs;\n } else {\n auto lhs = get();\n return std::equal(std::begin(lhs),\n std::end(lhs),\n std::begin(rhs),\n std::end(rhs),\n [](const auto &a, const auto &b) { return a == b; });\n }\n }\n\n private:\n class NArgsRange {\n std::size_t m_min;\n std::size_t m_max;\n\n public:\n NArgsRange(std::size_t minimum, std::size_t maximum)\n : m_min(minimum),\n m_max(maximum) {\n if (minimum > maximum) {\n throw std::logic_error(\"Range of number of arguments is invalid\");\n }\n }\n\n bool contains(std::size_t value) const { return value >= m_min && value <= m_max; }\n\n bool is_exact() const { return m_min == m_max; }\n\n bool is_right_bounded() const { return m_max < std::numeric_limits::max(); }\n\n std::size_t get_min() const { return m_min; }\n\n std::size_t get_max() const { return m_max; }\n\n // Print help message\n friend auto operator<<(std::ostream &stream, const NArgsRange &range) -> std::ostream & {\n if (range.m_min == range.m_max) {\n if (range.m_min != 0 && range.m_min != 1) {\n stream << \"[nargs: \" << range.m_min << \"] \";\n }\n } else {\n if (range.m_max == std::numeric_limits::max()) {\n stream << \"[nargs: \" << range.m_min << \" or more] \";\n } else {\n stream << \"[nargs=\" << range.m_min << \"..\" << range.m_max << \"] \";\n }\n }\n return stream;\n }\n\n bool operator==(const NArgsRange &rhs) const { return rhs.m_min == m_min && rhs.m_max == m_max; }\n\n bool operator!=(const NArgsRange &rhs) const { return !(*this == rhs); }\n };\n\n void throw_nargs_range_validation_error() const {\n std::stringstream stream;\n if (!m_used_name.empty()) {\n stream << m_used_name << \": \";\n } else {\n stream << m_names.front() << \": \";\n }\n if (m_num_args_range.is_exact()) {\n stream << m_num_args_range.get_min();\n } else if (m_num_args_range.is_right_bounded()) {\n stream << m_num_args_range.get_min() << \" to \" << m_num_args_range.get_max();\n } else {\n stream << m_num_args_range.get_min() << \" or more\";\n }\n stream << \" argument(s) expected. \" << m_values.size() << \" provided.\";\n throw std::runtime_error(stream.str());\n }\n\n void throw_required_arg_not_used_error() const {\n std::stringstream stream;\n stream << m_names.front() << \": required.\";\n throw std::runtime_error(stream.str());\n }\n\n void throw_required_arg_no_value_provided_error() const {\n std::stringstream stream;\n stream << m_used_name << \": no value provided.\";\n throw std::runtime_error(stream.str());\n }\n\n static constexpr int eof = std::char_traits::eof();\n\n static auto lookahead(std::string_view s) -> int {\n if (s.empty()) {\n return eof;\n }\n return static_cast(static_cast(s[0]));\n }\n\n /*\n * decimal-literal:\n * '0'\n * nonzero-digit digit-sequence_opt\n * integer-part fractional-part\n * fractional-part\n * integer-part '.' exponent-part_opt\n * integer-part exponent-part\n *\n * integer-part:\n * digit-sequence\n *\n * fractional-part:\n * '.' post-decimal-point\n *\n * post-decimal-point:\n * digit-sequence exponent-part_opt\n *\n * exponent-part:\n * 'e' post-e\n * 'E' post-e\n *\n * post-e:\n * sign_opt digit-sequence\n *\n * sign: one of\n * '+' '-'\n */\n static bool is_decimal_literal(std::string_view s) {\n auto is_digit = [](auto c) constexpr {\n switch (c) {\n case '0':\n case '1':\n case '2':\n case '3':\n case '4':\n case '5':\n case '6':\n case '7':\n case '8':\n case '9':\n return true;\n default:\n return false;\n }\n };\n\n // precondition: we have consumed or will consume at least one digit\n auto consume_digits = [=](std::string_view sd) {\n // NOLINTNEXTLINE(readability-qualified-auto)\n auto it = std::find_if_not(std::begin(sd), std::end(sd), is_digit);\n return sd.substr(static_cast(it - std::begin(sd)));\n };\n\n switch (lookahead(s)) {\n case '0': {\n s.remove_prefix(1);\n if (s.empty()) {\n return true;\n }\n goto integer_part;\n }\n case '1':\n case '2':\n case '3':\n case '4':\n case '5':\n case '6':\n case '7':\n case '8':\n case '9': {\n s = consume_digits(s);\n if (s.empty()) {\n return true;\n }\n goto integer_part_consumed;\n }\n case '.': {\n s.remove_prefix(1);\n goto post_decimal_point;\n }\n default:\n return false;\n }\n\n integer_part:\n s = consume_digits(s);\n integer_part_consumed:\n switch (lookahead(s)) {\n case '.': {\n s.remove_prefix(1);\n if (is_digit(lookahead(s))) {\n goto post_decimal_point;\n } else {\n goto exponent_part_opt;\n }\n }\n case 'e':\n case 'E': {\n s.remove_prefix(1);\n goto post_e;\n }\n default:\n return false;\n }\n\n post_decimal_point:\n if (is_digit(lookahead(s))) {\n s = consume_digits(s);\n goto exponent_part_opt;\n }\n return false;\n\n exponent_part_opt:\n switch (lookahead(s)) {\n case eof:\n return true;\n case 'e':\n case 'E': {\n s.remove_prefix(1);\n goto post_e;\n }\n default:\n return false;\n }\n\n post_e:\n switch (lookahead(s)) {\n case '-':\n case '+':\n s.remove_prefix(1);\n }\n if (is_digit(lookahead(s))) {\n s = consume_digits(s);\n return s.empty();\n }\n return false;\n }\n\n static bool is_optional(std::string_view name, std::string_view prefix_chars) {\n return !is_positional(name, prefix_chars);\n }\n\n /*\n * positional:\n * _empty_\n * '-'\n * '-' decimal-literal\n * !'-' anything\n */\n static bool is_positional(std::string_view name, std::string_view prefix_chars) {\n auto first = lookahead(name);\n\n if (first == eof) {\n return true;\n } else if (prefix_chars.find(static_cast(first)) != std::string_view::npos) {\n name.remove_prefix(1);\n if (name.empty()) {\n return true;\n }\n return is_decimal_literal(name);\n }\n return true;\n }\n\n /*\n * Get argument value given a type\n * @throws std::logic_error in case of incompatible types\n */\n template \n auto get() const -> std::conditional_t, T, const T &> {\n if (!m_values.empty()) {\n if constexpr (details::IsContainer) {\n return any_cast_container(m_values);\n } else {\n return *std::any_cast(&m_values.front());\n }\n }\n if (m_default_value.has_value()) {\n return *std::any_cast(&m_default_value);\n }\n if constexpr (details::IsContainer) {\n if (!m_accepts_optional_like_value) {\n return any_cast_container(m_values);\n }\n }\n\n throw std::logic_error(\"No value provided for '\" + m_names.back() + \"'.\");\n }\n\n /*\n * Get argument value given a type.\n * @pre The object has no default value.\n * @returns The stored value if any, std::nullopt otherwise.\n */\n template \n auto present() const -> std::optional {\n if (m_default_value.has_value()) {\n throw std::logic_error(\"Argument with default value always presents\");\n }\n if (m_values.empty()) {\n return std::nullopt;\n }\n if constexpr (details::IsContainer) {\n return any_cast_container(m_values);\n }\n return std::any_cast(m_values.front());\n }\n\n template \n static auto any_cast_container(const std::vector &operand) -> T {\n using ValueType = typename T::value_type;\n\n T result;\n std::transform(std::begin(operand), std::end(operand), std::back_inserter(result), [](const auto &value) {\n return *std::any_cast(&value);\n });\n return result;\n }\n\n std::vector m_names;\n std::string_view m_used_name;\n std::string m_help;\n std::string m_metavar;\n std::any m_default_value;\n std::string m_default_value_repr;\n std::any m_implicit_value;\n using valued_action = std::function;\n using void_action = std::function;\n std::variant m_action{std::in_place_type,\n [](const std::string &value) { return value; }};\n std::vector m_values;\n NArgsRange m_num_args_range{1, 1};\n bool m_accepts_optional_like_value = false;\n bool m_is_optional : true;\n bool m_is_required : true;\n bool m_is_repeatable : true;\n bool m_is_used : true; // True if the optional argument is used by user\n std::string_view m_prefix_chars; // ArgumentParser has the prefix_chars\n};\n\nclass ArgumentParser {\n public:\n explicit ArgumentParser(std::string program_name = {},\n std::string version = \"1.0\",\n default_arguments add_args = default_arguments::none)\n : m_program_name(std::move(program_name)),\n m_version(std::move(version)),\n m_parser_path(m_program_name) {\n if ((add_args & default_arguments::help) == default_arguments::help) {\n add_argument(\"-h\", \"--help\")\n .action([&](const auto & /*unused*/) {\n std::cout << help().str();\n std::exit(0);\n })\n .default_value(false)\n .help(\"shows help message and exits\")\n .implicit_value(true)\n .nargs(0);\n }\n if ((add_args & default_arguments::version) == default_arguments::version) {\n add_argument(\"-v\", \"--version\")\n .action([&](const auto & /*unused*/) {\n std::cout << m_version << std::endl;\n std::exit(0);\n })\n .default_value(false)\n .help(\"prints version information and exits\")\n .implicit_value(true)\n .nargs(0);\n }\n }\n\n ArgumentParser(ArgumentParser &&) noexcept = default;\n ArgumentParser &operator=(ArgumentParser &&) = default;\n\n ArgumentParser(const ArgumentParser &other)\n : m_program_name(other.m_program_name),\n m_version(other.m_version),\n m_description(other.m_description),\n m_epilog(other.m_epilog),\n m_prefix_chars(other.m_prefix_chars),\n m_assign_chars(other.m_assign_chars),\n m_is_parsed(other.m_is_parsed),\n m_positional_arguments(other.m_positional_arguments),\n m_optional_arguments(other.m_optional_arguments),\n m_parser_path(other.m_parser_path),\n m_subparsers(other.m_subparsers) {\n for (auto it = std::begin(m_positional_arguments); it != std::end(m_positional_arguments); ++it) {\n index_argument(it);\n }\n for (auto it = std::begin(m_optional_arguments); it != std::end(m_optional_arguments); ++it) {\n index_argument(it);\n }\n for (auto it = std::begin(m_subparsers); it != std::end(m_subparsers); ++it) {\n m_subparser_map.insert_or_assign(it->get().m_program_name, it);\n m_subparser_used.insert_or_assign(it->get().m_program_name, false);\n }\n }\n\n ~ArgumentParser() = default;\n\n ArgumentParser &operator=(const ArgumentParser &other) {\n auto tmp = other;\n std::swap(*this, tmp);\n return *this;\n }\n\n explicit operator bool() const {\n auto arg_used =\n std::any_of(m_argument_map.cbegin(), m_argument_map.cend(), [](auto &it) { return it.second->m_is_used; });\n auto subparser_used =\n std::any_of(m_subparser_used.cbegin(), m_subparser_used.cend(), [](auto &it) { return it.second; });\n\n return m_is_parsed && (arg_used || subparser_used);\n }\n\n // Parameter packing\n // Call add_argument with variadic number of string arguments\n template \n Argument &add_argument(Targs... f_args) {\n using array_of_sv = std::array;\n auto argument =\n m_optional_arguments.emplace(std::cend(m_optional_arguments), m_prefix_chars, array_of_sv{f_args...});\n\n if (!argument->m_is_optional) {\n m_positional_arguments.splice(std::cend(m_positional_arguments), m_optional_arguments, argument);\n }\n\n index_argument(argument);\n return *argument;\n }\n\n // Parameter packed add_parents method\n // Accepts a variadic number of ArgumentParser objects\n template \n ArgumentParser &add_parents(const Targs &...f_args) {\n for (const ArgumentParser &parent_parser : {std::ref(f_args)...}) {\n for (const auto &argument : parent_parser.m_positional_arguments) {\n auto it = m_positional_arguments.insert(std::cend(m_positional_arguments), argument);\n index_argument(it);\n }\n for (const auto &argument : parent_parser.m_optional_arguments) {\n auto it = m_optional_arguments.insert(std::cend(m_optional_arguments), argument);\n index_argument(it);\n }\n }\n return *this;\n }\n\n ArgumentParser &add_description(std::string description) {\n m_description = std::move(description);\n return *this;\n }\n\n ArgumentParser &add_epilog(std::string epilog) {\n m_epilog = std::move(epilog);\n return *this;\n }\n\n /* Getter for arguments and subparsers.\n * @throws std::logic_error in case of an invalid argument or subparser name\n */\n template \n T &at(std::string_view name) {\n if constexpr (std::is_same_v) {\n return (*this)[name];\n } else {\n auto subparser_it = m_subparser_map.find(name);\n if (subparser_it != m_subparser_map.end()) {\n return subparser_it->second->get();\n }\n throw std::logic_error(\"No such subparser: \" + std::string(name));\n }\n }\n\n ArgumentParser &set_prefix_chars(std::string prefix_chars) {\n m_prefix_chars = std::move(prefix_chars);\n return *this;\n }\n\n ArgumentParser &set_assign_chars(std::string assign_chars) {\n m_assign_chars = std::move(assign_chars);\n return *this;\n }\n\n /* Call parse_args_internal - which does all the work\n * Then, validate the parsed arguments\n * This variant is used mainly for testing\n * @throws std::runtime_error in case of any invalid argument\n */\n void parse_args(const std::vector &arguments) {\n parse_args_internal(arguments);\n // Check if all arguments are parsed\n for ([[maybe_unused]] const auto &[unused, argument] : m_argument_map) {\n argument->validate();\n }\n }\n\n /* Call parse_known_args_internal - which does all the work\n * Then, validate the parsed arguments\n * This variant is used mainly for testing\n * @throws std::runtime_error in case of any invalid argument\n */\n std::vector parse_known_args(const std::vector &arguments) {\n auto unknown_arguments = parse_known_args_internal(arguments);\n // Check if all arguments are parsed\n for ([[maybe_unused]] const auto &[unused, argument] : m_argument_map) {\n argument->validate();\n }\n return unknown_arguments;\n }\n\n /* Main entry point for parsing command-line arguments using this\n * ArgumentParser\n * @throws std::runtime_error in case of any invalid argument\n */\n // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays)\n void parse_args(int argc, const char *const argv[]) { parse_args({argv, argv + argc}); }\n\n /* Main entry point for parsing command-line arguments using this\n * ArgumentParser\n * @throws std::runtime_error in case of any invalid argument\n */\n // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays)\n auto parse_known_args(int argc, const char *const argv[]) { return parse_known_args({argv, argv + argc}); }\n\n /* Getter for options with default values.\n * @throws std::logic_error if parse_args() has not been previously called\n * @throws std::logic_error if there is no such option\n * @throws std::logic_error if the option has no value\n * @throws std::bad_any_cast if the option is not of type T\n */\n template \n auto get(std::string_view arg_name) const -> std::conditional_t, T, const T &> {\n if (!m_is_parsed) {\n throw std::logic_error(\"Nothing parsed, no arguments are available.\");\n }\n return (*this)[arg_name].get();\n }\n\n /* Getter for options without default values.\n * @pre The option has no default value.\n * @throws std::logic_error if there is no such option\n * @throws std::bad_any_cast if the option is not of type T\n */\n template \n auto present(std::string_view arg_name) const -> std::optional {\n return (*this)[arg_name].present();\n }\n\n /* Getter that returns true for user-supplied options. Returns false if not\n * user-supplied, even with a default value.\n */\n auto is_used(std::string_view arg_name) const { return (*this)[arg_name].m_is_used; }\n\n /* Getter that returns true if a subcommand is used.\n */\n auto is_subcommand_used(std::string_view subcommand_name) const { return m_subparser_used.at(subcommand_name); }\n\n /* Getter that returns true if a subcommand is used.\n */\n auto is_subcommand_used(const ArgumentParser &subparser) const {\n return is_subcommand_used(subparser.m_program_name);\n }\n\n /* Indexing operator. Return a reference to an Argument object\n * Used in conjunction with Argument.operator== e.g., parser[\"foo\"] == true\n * @throws std::logic_error in case of an invalid argument name\n */\n Argument &operator[](std::string_view arg_name) const {\n auto it = m_argument_map.find(arg_name);\n if (it != m_argument_map.end()) {\n return *(it->second);\n }\n if (!is_valid_prefix_char(arg_name.front())) {\n std::string name(arg_name);\n const auto legal_prefix_char = get_any_valid_prefix_char();\n const auto prefix = std::string(1, legal_prefix_char);\n\n // \"-\" + arg_name\n name = prefix + name;\n it = m_argument_map.find(name);\n if (it != m_argument_map.end()) {\n return *(it->second);\n }\n // \"--\" + arg_name\n name = prefix + name;\n it = m_argument_map.find(name);\n if (it != m_argument_map.end()) {\n return *(it->second);\n }\n }\n throw std::logic_error(\"No such argument: \" + std::string(arg_name));\n }\n\n // Print help message\n friend auto operator<<(std::ostream &stream, const ArgumentParser &parser) -> std::ostream & {\n stream.setf(std::ios_base::left);\n\n auto longest_arg_length = parser.get_length_of_longest_argument();\n\n stream << parser.usage() << \"\\n\\n\";\n\n if (!parser.m_description.empty()) {\n stream << parser.m_description << \"\\n\\n\";\n }\n\n if (!parser.m_positional_arguments.empty()) {\n stream << \"Positional arguments:\\n\";\n }\n\n for (const auto &argument : parser.m_positional_arguments) {\n stream.width(static_cast(longest_arg_length));\n stream << argument;\n }\n\n if (!parser.m_optional_arguments.empty()) {\n stream << (parser.m_positional_arguments.empty() ? \"\" : \"\\n\") << \"Optional arguments:\\n\";\n }\n\n for (const auto &argument : parser.m_optional_arguments) {\n stream.width(static_cast(longest_arg_length));\n stream << argument;\n }\n\n if (!parser.m_subparser_map.empty()) {\n stream << (parser.m_positional_arguments.empty() ? (parser.m_optional_arguments.empty() ? \"\" : \"\\n\") : \"\\n\")\n << \"Subcommands:\\n\";\n for (const auto &[command, subparser] : parser.m_subparser_map) {\n stream << std::setw(2) << \" \";\n stream << std::setw(static_cast(longest_arg_length - 2)) << command;\n stream << \" \" << subparser->get().m_description << \"\\n\";\n }\n }\n\n if (!parser.m_epilog.empty()) {\n stream << '\\n';\n stream << parser.m_epilog << \"\\n\\n\";\n }\n\n return stream;\n }\n\n const std::string &program_name() const { return m_program_name; }\n\n // Format help message\n auto help() const -> std::stringstream {\n std::stringstream out;\n out << *this;\n return out;\n }\n\n // Format usage part of help only\n auto usage() const -> std::string {\n std::stringstream stream;\n\n stream << \"Usage: \" << this->m_program_name;\n\n // Add any options inline here\n for (const auto &argument : this->m_optional_arguments) {\n stream << \" \" << argument.get_inline_usage();\n }\n // Put positional arguments after the optionals\n for (const auto &argument : this->m_positional_arguments) {\n if (!argument.m_metavar.empty()) {\n stream << \" \" << argument.m_metavar;\n } else {\n stream << \" \" << argument.m_names.front();\n }\n }\n // Put subcommands after positional arguments\n if (!m_subparser_map.empty()) {\n stream << \" {\";\n std::size_t i{0};\n for (const auto &[command, unused] : m_subparser_map) {\n if (i == 0) {\n stream << command;\n } else {\n stream << \",\" << command;\n }\n ++i;\n }\n stream << \"}\";\n }\n\n return stream.str();\n }\n\n // Printing the one and only help message\n // I've stuck with a simple message format, nothing fancy.\n [[deprecated(\"Use cout << program; instead. See also help().\")]] std::string print_help() const {\n auto out = help();\n std::cout << out.rdbuf();\n return out.str();\n }\n\n void add_subparser(ArgumentParser &parser) {\n parser.m_parser_path = m_program_name + \" \" + parser.m_program_name;\n auto it = m_subparsers.emplace(std::cend(m_subparsers), parser);\n m_subparser_map.insert_or_assign(parser.m_program_name, it);\n m_subparser_used.insert_or_assign(parser.m_program_name, false);\n }\n\n private:\n bool is_valid_prefix_char(char c) const { return m_prefix_chars.find(c) != std::string::npos; }\n\n char get_any_valid_prefix_char() const { return m_prefix_chars[0]; }\n\n /*\n * Pre-process this argument list. Anything starting with \"--\", that\n * contains an =, where the prefix before the = has an entry in the\n * options table, should be split.\n */\n std::vector preprocess_arguments(const std::vector &raw_arguments) const {\n std::vector arguments{};\n for (const auto &arg : raw_arguments) {\n const auto argument_starts_with_prefix_chars = [this](const std::string &a) -> bool {\n if (!a.empty()) {\n const auto legal_prefix = [this](char c) -> bool { return m_prefix_chars.find(c) != std::string::npos; };\n\n // Windows-style\n // if '/' is a legal prefix char\n // then allow single '/' followed by argument name, followed by an\n // assign char, e.g., ':' e.g., 'test.exe /A:Foo'\n const auto windows_style = legal_prefix('/');\n\n if (windows_style) {\n if (legal_prefix(a[0])) {\n return true;\n }\n } else {\n // Slash '/' is not a legal prefix char\n // For all other characters, only support long arguments\n // i.e., the argument must start with 2 prefix chars, e.g,\n // '--foo' e,g, './test --foo=Bar -DARG=yes'\n if (a.size() > 1) {\n return (legal_prefix(a[0]) && legal_prefix(a[1]));\n }\n }\n }\n return false;\n };\n\n // Check that:\n // - We don't have an argument named exactly this\n // - The argument starts with a prefix char, e.g., \"--\"\n // - The argument contains an assign char, e.g., \"=\"\n auto assign_char_pos = arg.find_first_of(m_assign_chars);\n\n if (m_argument_map.find(arg) == m_argument_map.end() && argument_starts_with_prefix_chars(arg) &&\n assign_char_pos != std::string::npos) {\n // Get the name of the potential option, and check it exists\n std::string opt_name = arg.substr(0, assign_char_pos);\n if (m_argument_map.find(opt_name) != m_argument_map.end()) {\n // This is the name of an option! Split it into two parts\n arguments.push_back(std::move(opt_name));\n arguments.push_back(arg.substr(assign_char_pos + 1));\n continue;\n }\n }\n // If we've fallen through to here, then it's a standard argument\n arguments.push_back(arg);\n }\n return arguments;\n }\n\n /*\n * @throws std::runtime_error in case of any invalid argument\n */\n void parse_args_internal(const std::vector &raw_arguments) {\n auto arguments = preprocess_arguments(raw_arguments);\n if (m_program_name.empty() && !arguments.empty()) {\n m_program_name = arguments.front();\n }\n auto end = std::end(arguments);\n auto positional_argument_it = std::begin(m_positional_arguments);\n for (auto it = std::next(std::begin(arguments)); it != end;) {\n const auto ¤t_argument = *it;\n if (Argument::is_positional(current_argument, m_prefix_chars)) {\n if (positional_argument_it == std::end(m_positional_arguments)) {\n std::string_view maybe_command = current_argument;\n\n // Check sub-parsers\n auto subparser_it = m_subparser_map.find(maybe_command);\n if (subparser_it != m_subparser_map.end()) {\n // build list of remaining args\n const auto unprocessed_arguments = std::vector(it, end);\n\n // invoke subparser\n m_is_parsed = true;\n m_subparser_used[maybe_command] = true;\n return subparser_it->second->get().parse_args(unprocessed_arguments);\n }\n\n throw std::runtime_error(\"Maximum number of positional arguments exceeded\");\n }\n auto argument = positional_argument_it++;\n it = argument->consume(it, end);\n continue;\n }\n\n auto arg_map_it = m_argument_map.find(current_argument);\n if (arg_map_it != m_argument_map.end()) {\n auto argument = arg_map_it->second;\n it = argument->consume(std::next(it), end, arg_map_it->first);\n } else if (const auto &compound_arg = current_argument; compound_arg.size() > 1 &&\n is_valid_prefix_char(compound_arg[0]) &&\n !is_valid_prefix_char(compound_arg[1])) {\n ++it;\n for (std::size_t j = 1; j < compound_arg.size(); j++) {\n auto hypothetical_arg = std::string{'-', compound_arg[j]};\n auto arg_map_it2 = m_argument_map.find(hypothetical_arg);\n if (arg_map_it2 != m_argument_map.end()) {\n auto argument = arg_map_it2->second;\n it = argument->consume(it, end, arg_map_it2->first);\n } else {\n throw std::runtime_error(\"Unknown argument: \" + current_argument);\n }\n }\n } else {\n throw std::runtime_error(\"Unknown argument: \" + current_argument);\n }\n }\n m_is_parsed = true;\n }\n\n /*\n * Like parse_args_internal but collects unused args into a vector\n */\n std::vector parse_known_args_internal(const std::vector &raw_arguments) {\n auto arguments = preprocess_arguments(raw_arguments);\n\n std::vector unknown_arguments{};\n\n if (m_program_name.empty() && !arguments.empty()) {\n m_program_name = arguments.front();\n }\n auto end = std::end(arguments);\n auto positional_argument_it = std::begin(m_positional_arguments);\n for (auto it = std::next(std::begin(arguments)); it != end;) {\n const auto ¤t_argument = *it;\n if (Argument::is_positional(current_argument, m_prefix_chars)) {\n if (positional_argument_it == std::end(m_positional_arguments)) {\n std::string_view maybe_command = current_argument;\n\n // Check sub-parsers\n auto subparser_it = m_subparser_map.find(maybe_command);\n if (subparser_it != m_subparser_map.end()) {\n // build list of remaining args\n const auto unprocessed_arguments = std::vector(it, end);\n\n // invoke subparser\n m_is_parsed = true;\n m_subparser_used[maybe_command] = true;\n return subparser_it->second->get().parse_known_args_internal(unprocessed_arguments);\n }\n\n // save current argument as unknown and go to next argument\n unknown_arguments.push_back(current_argument);\n ++it;\n } else {\n // current argument is the value of a positional argument\n // consume it\n auto argument = positional_argument_it++;\n it = argument->consume(it, end);\n }\n continue;\n }\n\n auto arg_map_it = m_argument_map.find(current_argument);\n if (arg_map_it != m_argument_map.end()) {\n auto argument = arg_map_it->second;\n it = argument->consume(std::next(it), end, arg_map_it->first);\n } else if (const auto &compound_arg = current_argument; compound_arg.size() > 1 &&\n is_valid_prefix_char(compound_arg[0]) &&\n !is_valid_prefix_char(compound_arg[1])) {\n ++it;\n for (std::size_t j = 1; j < compound_arg.size(); j++) {\n auto hypothetical_arg = std::string{'-', compound_arg[j]};\n auto arg_map_it2 = m_argument_map.find(hypothetical_arg);\n if (arg_map_it2 != m_argument_map.end()) {\n auto argument = arg_map_it2->second;\n it = argument->consume(it, end, arg_map_it2->first);\n } else {\n unknown_arguments.push_back(current_argument);\n break;\n }\n }\n } else {\n // current argument is an optional-like argument that is unknown\n // save it and move to next argument\n unknown_arguments.push_back(current_argument);\n ++it;\n }\n }\n m_is_parsed = true;\n return unknown_arguments;\n }\n\n // Used by print_help.\n std::size_t get_length_of_longest_argument() const {\n if (m_argument_map.empty()) {\n return 0;\n }\n std::size_t max_size = 0;\n for ([[maybe_unused]] const auto &[unused, argument] : m_argument_map) {\n max_size = std::max(max_size, argument->get_arguments_length());\n }\n for ([[maybe_unused]] const auto &[command, unused] : m_subparser_map) {\n max_size = std::max(max_size, command.size());\n }\n return max_size;\n }\n\n using argument_it = std::list::iterator;\n using argument_parser_it = std::list>::iterator;\n\n void index_argument(argument_it it) {\n for (const auto &name : std::as_const(it->m_names)) {\n m_argument_map.insert_or_assign(name, it);\n }\n }\n\n std::string m_program_name;\n std::string m_version;\n std::string m_description;\n std::string m_epilog;\n std::string m_prefix_chars{\"-\"};\n std::string m_assign_chars{\"=\"};\n bool m_is_parsed = false;\n std::list m_positional_arguments;\n std::list m_optional_arguments;\n std::map m_argument_map;\n std::string m_parser_path;\n std::list> m_subparsers;\n std::map m_subparser_map;\n std::map m_subparser_used;\n};\n\n} // namespace argparse\n"], ["/3FS/src/fuse/IovTable.h", "#pragma once\n\n#include \n\n#include \"common/utils/AtomicSharedPtrTable.h\"\n#include \"fbs/meta/Schema.h\"\n#include \"lib/common/Shm.h\"\n\nnamespace hf3fs::fuse {\nclass IovTable {\n public:\n IovTable() = default;\n void init(const Path &mount, int cap);\n Result>> addIov(const char *key,\n const Path &shmPath,\n pid_t pid,\n const meta::UserInfo &ui,\n folly::Executor::KeepAlive<> exec,\n storage::client::StorageClient &sc);\n Result> rmIov(const char *key, const meta::UserInfo &ui);\n Result lookupIov(const char *key, const meta::UserInfo &ui);\n std::optional iovDesc(meta::InodeId iid);\n Result statIov(int key, const meta::UserInfo &ui);\n\n public:\n std::pair>, std::shared_ptr>>>\n listIovs(const meta::UserInfo &ui);\n\n public:\n std::string mountName;\n std::shared_mutex shmLock;\n robin_hood::unordered_map shmsById;\n std::unique_ptr> iovs;\n\n private:\n mutable std::shared_mutex iovdLock_;\n robin_hood::unordered_map iovds_;\n};\n} // namespace hf3fs::fuse\n"], ["/3FS/src/common/utils/FaultInjection.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n// Set fault injection parameter in current code scope and automatically restore after leaving the scope.\n// Probability is expressed as a percentage between 0 and 100.\n// Times determines the maximum number of faults that can be injected (-1 means unlimited).\n// eg: `FAULT_INJECTION_SET(1, 5)` will inject faults with a probability of 1% up to five times.\n#define FAULT_INJECTION_SET(prob, times) hf3fs::FaultInjection::ScopeGuard FB_ANONYMOUS_VARIABLE(guard)(prob, times)\n\n// Fault injection code may be wrapped in loops, which may cause same fault injected many times. In this case, the\n// effect of the loop can be reduced by setting a probability factor. The probability factor only works in the current\n// scope and is automatically restored after leaving the scope.\n#define FAULT_INJECTION_SET_FACTOR(factor) hf3fs::FaultInjectionFactor::ScopeGuard FB_ANONYMOUS_VARIABLE(guard)(factor)\n\n// Use probability factor of current scope.\n#define FAULT_INJECTION() \\\n (UNLIKELY(hf3fs::FaultInjection::get() != nullptr) && \\\n hf3fs::FaultInjection::get()->injectWithFactor(hf3fs::FaultInjectionFactor::get()))\n// Specify a probability factor.\n#define FAULT_INJECTION_WITH_FACTOR(factor) \\\n (UNLIKELY(hf3fs::FaultInjection::get() != nullptr) && hf3fs::FaultInjection::get()->injectWithFactor(factor))\n\nnamespace hf3fs {\n\nclass FaultInjection : public folly::RequestData {\n public:\n class ScopeGuard {\n public:\n ScopeGuard(double prob, int times)\n : guard_(std::nullopt) {\n if (LIKELY(prob == 0)) {\n if (LIKELY(FaultInjection::get() == nullptr)) {\n // fast path, no need to record anything.\n return;\n }\n\n guard_.emplace(token(), nullptr);\n return;\n }\n guard_.emplace(token(),\n std::unique_ptr(new FaultInjection(prob / 100 * kProbabilityBase, times)));\n }\n\n private:\n std::optional guard_;\n };\n\n static ScopeGuard clone() {\n auto fi = FaultInjection::get();\n return fi ? ScopeGuard((double)fi->probability_ / kProbabilityBase * 100, fi->times_) : ScopeGuard(0, 0);\n }\n\n static inline FaultInjection *get() {\n auto requestContext = folly::RequestContext::try_get();\n if (LIKELY(requestContext == nullptr)) {\n return nullptr;\n }\n return dynamic_cast(requestContext->getContextData(token()));\n }\n\n bool hasCallback() override { return false; }\n\n bool injectWithFactor(uint32_t factor) {\n bool inject = folly::Random::rand32(kProbabilityBase) < probability_ && folly::Random::oneIn(factor);\n if (LIKELY(!inject)) {\n return false;\n }\n if (times_ == -1) {\n return true;\n }\n if (injected_ >= times_) return false;\n return injected_.fetch_add(1) < times_;\n }\n\n /** Get fault injection percentage probability. */\n double getProbability() const { return (double)probability_ * 100.0 / kProbabilityBase; }\n\n private:\n static constexpr const char *kTokenName = \"hf3fs::FaultInjection\";\n static constexpr uint32_t kProbabilityBase = 1000000;\n\n static folly::RequestToken const &token() {\n static folly::RequestToken const token(kTokenName);\n return token;\n }\n\n explicit FaultInjection(uint32_t prob, int times)\n : probability_(prob),\n times_(times),\n injected_(0) {\n probability_ = std::min(probability_, (uint32_t)kProbabilityBase);\n }\n\n uint32_t probability_; // probability to trigger fault injection, between 0 and kProbabilityBase\n int32_t times_; // max fault injection times, -1 means unlimited\n std::atomic_int32_t injected_; // injected times, use std::atomic for thread safety.\n};\n\n// This is read only, so it's thread safe as required by folly::RequestData.\nclass FaultInjectionFactor : public folly::RequestData {\n public:\n class ScopeGuard {\n public:\n explicit ScopeGuard(uint32_t factor)\n : guard_(std::nullopt) {\n if (LIKELY(FaultInjection::get() == nullptr)) {\n // fast path, fault injection not enabled.\n return;\n }\n guard_.emplace(token(), std::unique_ptr(new FaultInjectionFactor(factor)));\n }\n\n private:\n std::optional guard_;\n };\n\n static inline uint32_t get() {\n auto requestContext = folly::RequestContext::try_get();\n if (LIKELY(requestContext == nullptr)) {\n return 1;\n }\n auto ptr = dynamic_cast(requestContext->getContextData(token()));\n return ptr ? ptr->factor_ : 1;\n }\n\n bool hasCallback() override { return false; }\n\n uint32_t getFactor() const { return factor_; }\n\n private:\n static constexpr const char *kTokenName = \"hf3fs::FaultInjectionFactor\";\n static folly::RequestToken const &token() {\n static folly::RequestToken const token(kTokenName);\n return token;\n }\n\n FaultInjectionFactor(uint32_t factor)\n : factor_(factor) {}\n uint32_t factor_;\n};\n} // namespace hf3fs\n"], ["/3FS/src/common/utils/ObjectPool.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/utils/Size.h\"\n\nnamespace hf3fs {\n\ntemplate \nclass ObjectPool {\n using Storage = std::aligned_storage_t;\n using Batch = std::vector>;\n\n struct Deleter {\n constexpr Deleter() = default;\n void operator()(T *item) {\n item->~T();\n tls().put(std::unique_ptr(reinterpret_cast(item)));\n }\n };\n\n public:\n using Ptr = std::unique_ptr;\n static Ptr get() { return Ptr(new (tls().get().release()) T); }\n\n template \n static Ptr get(Args &&...args) {\n return Ptr(new (tls().get().release()) T(std::forward(args)...));\n }\n\n protected:\n class TLS {\n public:\n TLS(ObjectPool &parent)\n : parent_(parent) {}\n\n // get a object from thread local cache or global cache.\n std::unique_ptr get() {\n // pop from second batch.\n if (!second_.empty()) {\n auto item = std::move(second_.back());\n second_.pop_back();\n return item;\n }\n\n // allocate a batch when local and global cache is empty.\n if (first_.empty() && !parent_.getBatch(first_)) {\n first_.resize(kThreadLocalMaxNum);\n for (auto &item : first_) {\n item.reset(new Storage); // DO NOT REPLACE IT WITH std::make_unique.\n // std::make_unique_for_overwrite is not available currently.\n }\n }\n\n // pop from the first batch.\n auto item = std::move(first_.back());\n first_.pop_back();\n return item;\n }\n\n // put a object into thread local cache or global cache.\n void put(std::unique_ptr obj) {\n // push to the first batch.\n if (first_.size() < kThreadLocalMaxNum) {\n first_.push_back(std::move(obj));\n return;\n }\n\n // push to the second batch.\n second_.push_back(std::move(obj));\n if (UNLIKELY(second_.size() >= kThreadLocalMaxNum)) {\n // push to the global cache.\n parent_.putBatch(std::move(second_));\n second_.clear();\n second_.reserve(kThreadLocalMaxNum);\n }\n }\n\n private:\n ObjectPool &parent_;\n Batch first_;\n Batch second_;\n };\n\n static auto &tls() {\n static ObjectPool instance;\n thread_local TLS tls{instance};\n return tls;\n }\n\n bool getBatch(Batch &batch) {\n auto lock = std::unique_lock(mutex_);\n if (global_.empty()) {\n return false;\n }\n\n // pop a batch from global cache.\n batch = std::move(global_.back());\n global_.pop_back();\n return true;\n }\n\n void putBatch(Batch batch) {\n auto lock = std::unique_lock(mutex_);\n if (global_.size() < kGlobalMaxBatchNum) {\n global_.push_back(std::move(batch));\n }\n }\n\n private:\n static constexpr auto kThreadLocalMaxNum = std::max(1ul, NumTLSCachedItem);\n static constexpr auto kGlobalMaxBatchNum = std::max(1ul, NumGlobalCachedItem / NumTLSCachedItem);\n\n std::mutex mutex_;\n std::vector global_;\n};\n\n} // namespace hf3fs\n"], ["/3FS/src/core/app/MgmtdClientFetcher.h", "#pragma once\n\n#include \"LauncherUtils.h\"\n#include \"client/mgmtd/MgmtdClient.h\"\n#include \"common/net/Client.h\"\n\nnamespace hf3fs::core::launcher {\nstruct MgmtdClientFetcher {\n MgmtdClientFetcher(String clusterId,\n const net::Client::Config &clientCfg,\n const client::MgmtdClient::Config &mgmtdClientCfg);\n\n template \n MgmtdClientFetcher(const ConfigT &cfg)\n : MgmtdClientFetcher(cfg.cluster_id(), cfg.client(), cfg.mgmtd_client()) {}\n\n virtual ~MgmtdClientFetcher() { stopClient(); }\n\n Result loadConfigTemplate(flat::NodeType nodeType);\n Result ensureClientInited();\n void stopClient();\n\n virtual Result completeAppInfo(flat::AppInfo &appInfo) = 0;\n\n const String clusterId_;\n const net::Client::Config &clientCfg_;\n const client::MgmtdClient::Config &mgmtdClientCfg_;\n std::unique_ptr client_;\n std::shared_ptr mgmtdClient_;\n};\n} // namespace hf3fs::core::launcher\n"], ["/3FS/src/storage/service/StorageServer.h", "#pragma once\n\n#include \n\n#include \"client/mgmtd/MgmtdClientForServer.h\"\n#include \"common/net/Server.h\"\n#include \"core/app/ServerAppConfig.h\"\n#include \"core/app/ServerLauncher.h\"\n#include \"core/app/ServerLauncherConfig.h\"\n#include \"core/app/ServerMgmtdClientFetcher.h\"\n#include \"storage/service/Components.h\"\n#include \"storage/service/ReliableForwarding.h\"\n#include \"storage/service/ReliableUpdate.h\"\n#include \"storage/service/StorageOperator.h\"\n\nnamespace hf3fs::test {\nstruct StorageServerHelper;\n}\n\nnamespace hf3fs::storage {\n\nclass StorageServer : public net::Server {\n public:\n static constexpr auto kName = \"Storage\";\n static constexpr auto kNodeType = flat::NodeType::STORAGE;\n\n using AppConfig = core::ServerAppConfig;\n struct LauncherConfig : public core::ServerLauncherConfig {\n LauncherConfig() { mgmtd_client() = hf3fs::client::MgmtdClientForServer::Config{}; }\n };\n using RemoteConfigFetcher = core::launcher::ServerMgmtdClientFetcher;\n using Launcher = core::ServerLauncher;\n\n using CommonConfig = ApplicationBase::Config;\n using Config = Components::Config;\n StorageServer(const Components::Config &config);\n ~StorageServer() override;\n\n // set up storage server.\n Result beforeStart() final;\n\n // before server stop.\n Result beforeStop() final;\n\n // tear down storage server.\n Result afterStop() final;\n\n using net::Server::start;\n hf3fs::Result start(const flat::AppInfo &info,\n std::unique_ptr<::hf3fs::net::Client> client,\n std::shared_ptr<::hf3fs::client::MgmtdClient> mgmtdClient);\n\n private:\n friend struct test::StorageServerHelper;\n ConstructLog<\"storage::StorageServer\"> constructLog_;\n Components components_;\n};\n\n} // namespace hf3fs::storage\n"], ["/3FS/src/common/kv/WithTransaction.h", "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/kv/ITransaction.h\"\n#include \"common/utils/Coroutine.h\"\n#include \"common/utils/Result.h\"\n\nnamespace hf3fs::kv {\n\ntemplate \nclass WithTransaction : public folly::MoveOnly {\n public:\n WithTransaction(RetryStrategy strategy)\n : strategy_(std::move(strategy)) {}\n\n template \n std::invoke_result_t run(std::unique_ptr txn,\n Handler &&handler) {\n co_return co_await run(*txn, std::forward(handler));\n }\n\n template \n std::invoke_result_t run(std::unique_ptr txn,\n Handler &&handler) {\n co_return co_await run(*txn, std::forward(handler));\n }\n\n template \n std::invoke_result_t run(IReadOnlyTransaction &txn, Handler &&handler) {\n auto result = strategy_.init(&txn);\n CO_RETURN_ON_ERROR(result);\n\n while (true) {\n auto result = co_await handler(txn);\n if (!result.hasError()) {\n co_return std::move(result);\n }\n auto retryResult = co_await strategy_.onError(&txn, std::move(result.error()));\n CO_RETURN_ON_ERROR(retryResult);\n }\n }\n\n template \n std::invoke_result_t run(IReadWriteTransaction &txn, Handler &&handler) {\n auto result = strategy_.init(&txn);\n CO_RETURN_ON_ERROR(result);\n\n while (true) {\n auto result = co_await runAndCommit(txn, std::forward(handler));\n if (!result.hasError()) {\n co_return std::move(result);\n }\n auto retryResult = co_await strategy_.onError(&txn, std::move(result.error()));\n CO_RETURN_ON_ERROR(retryResult);\n }\n }\n\n RetryStrategy &getStrategy() { return strategy_; }\n\n private:\n template \n std::invoke_result_t runAndCommit(IReadWriteTransaction &txn, Handler &&handler) {\n auto result = co_await handler(txn);\n if (!result.hasError()) {\n auto commitResult = co_await txn.commit();\n CO_RETURN_ON_ERROR(commitResult);\n }\n co_return std::move(result);\n }\n\n RetryStrategy strategy_;\n};\n\n} // namespace hf3fs::kv\n"], ["/3FS/src/stubs/common/StubFactory.h", "#pragma once\n\n#include \n\n#include \"common/serde/ClientContext.h\"\n#include \"common/utils/RobinHood.h\"\n#include \"stubs/common/Stub.h\"\n\nnamespace hf3fs::stubs {\n\ntemplate