diff options
48 files changed, 406 insertions, 496 deletions
diff --git a/vcpkg.json b/vcpkg.json deleted file mode 100644 index 4a0c41d3b..000000000 --- a/vcpkg.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "name": "zenfs", - "version-string": "0.1.0-dev", - "dependencies": [ - "asio", - "cpr", - "openssl", - "json11", - "mimalloc", - "spdlog", - "lz4", - "zstd", - "xxhash", - "gsl-lite", - "cxxopts", - "doctest", - "http-parser", - "robin-map", - { - "name": "rocksdb", - "features": [ "lz4", "zstd" ] - }, - "sol2", - "sentry-native" - ] -} diff --git a/vcpkg_overlay-ports/asio/CMakeLists.txt b/vcpkg_overlay-ports/asio/CMakeLists.txt deleted file mode 100644 index 6bdb490ba..000000000 --- a/vcpkg_overlay-ports/asio/CMakeLists.txt +++ /dev/null @@ -1,28 +0,0 @@ -cmake_minimum_required(VERSION 3.8) -project(asio) - -add_library(asio INTERFACE) - -# Export target -install(TARGETS asio - EXPORT asio - INCLUDES DESTINATION include/ -) - -install(EXPORT asio - DESTINATION "share/asio" - FILE asio-targets.cmake -) - -install(DIRECTORY - asio/include/asio - DESTINATION include/ - FILES_MATCHING - PATTERN "*.hpp" - PATTERN "*.ipp" -) - -install(FILES - asio/include/asio.hpp - DESTINATION include/ -) diff --git a/vcpkg_overlay-ports/asio/asio-config.cmake b/vcpkg_overlay-ports/asio/asio-config.cmake deleted file mode 100644 index 6e5325003..000000000 --- a/vcpkg_overlay-ports/asio/asio-config.cmake +++ /dev/null @@ -1,6 +0,0 @@ -include ("${CMAKE_CURRENT_LIST_DIR}/asio-targets.cmake") -add_library(asio::asio INTERFACE IMPORTED) -target_link_libraries(asio::asio INTERFACE asio) - -get_target_property(_ASIO_INCLUDE_DIR asio INTERFACE_INCLUDE_DIRECTORIES) -set(ASIO_INCLUDE_DIR "${_ASIO_INCLUDE_DIR}") diff --git a/vcpkg_overlay-ports/asio/portfile.cmake b/vcpkg_overlay-ports/asio/portfile.cmake deleted file mode 100644 index 08cf98e24..000000000 --- a/vcpkg_overlay-ports/asio/portfile.cmake +++ /dev/null @@ -1,31 +0,0 @@ -#header-only library - -vcpkg_from_git( - OUT_SOURCE_PATH SOURCE_PATH - URL https://github.com/chriskohlhoff/asio.git - REPO chriskohlhoff/asio - REF 57577c6db46a4e2de5351af2b185bf52696699a9 - HEAD_REF master -) - -# Always use "ASIO_STANDALONE" to avoid boost dependency -vcpkg_replace_string("${SOURCE_PATH}/asio/include/asio/detail/config.hpp" "defined(ASIO_STANDALONE)" "!defined(VCPKG_DISABLE_ASIO_STANDALONE)") - -# CMake install -file(COPY ${CMAKE_CURRENT_LIST_DIR}/CMakeLists.txt DESTINATION ${SOURCE_PATH}) -vcpkg_configure_cmake( - SOURCE_PATH ${SOURCE_PATH} - PREFER_NINJA -) -vcpkg_install_cmake() - -vcpkg_fixup_cmake_targets(CONFIG_PATH "share/asio") -file(INSTALL - ${CMAKE_CURRENT_LIST_DIR}/asio-config.cmake - DESTINATION ${CURRENT_PACKAGES_DIR}/share/${PORT} -) -file(REMOVE_RECURSE ${CURRENT_PACKAGES_DIR}/debug) - -# Handle copyright -file(INSTALL ${SOURCE_PATH}/asio/LICENSE_1_0.txt DESTINATION ${CURRENT_PACKAGES_DIR}/share/${PORT} RENAME copyright) - diff --git a/vcpkg_overlay-ports/asio/vcpkg.json b/vcpkg_overlay-ports/asio/vcpkg.json deleted file mode 100644 index 38140acc5..000000000 --- a/vcpkg_overlay-ports/asio/vcpkg.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "asio", - "version": "1.18.1", - "description": "Asio is a cross-platform C++ library for network and low-level I/O programming that provides developers with a consistent asynchronous model using a modern C++ approach.", - "homepage": "https://github.com/chriskohlhoff/asio", - "documentation": "https://think-async.com/Asio/asio-1.18.0/doc/", - "features": { - "coroutine": { - "description": "Boost.Coroutine (optional) if you use spawn() to launch coroutines", - "dependencies": [ - "boost-coroutine" - ] - }, - "openssl": { - "description": "OpenSSL (optional) if you use Asio's SSL support.", - "dependencies": [ - "openssl" - ] - }, - "regex": { - "description": "Boost.Regex (optional) if you use any of the read_until() or async_read_until() overloads that take a boost::regex parameter.", - "dependencies": [ - "boost-regex" - ] - } - } -} @@ -58,10 +58,11 @@ if is_os("windows") then end if is_os("linux") or is_os("macosx") then - add_cxxflags("-Wno-unused-value") - add_cxxflags("-Wno-strict-aliasing") add_cxxflags("-Wno-implicit-fallthrough") add_cxxflags("-Wno-missing-field-initializers") + add_cxxflags("-Wno-strict-aliasing") + add_cxxflags("-Wno-unused-private-field") + add_cxxflags("-Wno-unused-value") end -- Turn use of undefined cpp macros into errors diff --git a/zen/cmds/cache.cpp b/zen/cmds/cache.cpp index 2a911c8c7..f1b953af5 100644 --- a/zen/cmds/cache.cpp +++ b/zen/cmds/cache.cpp @@ -13,8 +13,6 @@ ZEN_THIRD_PARTY_INCLUDES_START #include <cpr/cpr.h> ZEN_THIRD_PARTY_INCLUDES_END -using namespace fmt::literals; - DropCommand::DropCommand() { m_Options.add_options()("h,help", "Print help"); @@ -35,7 +33,7 @@ DropCommand::Run(const ZenCliOptions& GlobalOptions, int argc, char** argv) ZEN_INFO("Dropping cache bucket '{}' from '{}'", m_BucketName, m_HostName); cpr::Session Session; - Session.SetUrl({"{}/z$/{}"_format(m_HostName, m_BucketName)}); + Session.SetUrl({fmt::format("{}/z$/{}", m_HostName, m_BucketName)}); cpr::Response Result = Session.Delete(); if (zen::IsHttpSuccessCode(Result.status_code)) diff --git a/zen/internalfile.cpp b/zen/internalfile.cpp index a1f07992b..dbafcb549 100644 --- a/zen/internalfile.cpp +++ b/zen/internalfile.cpp @@ -192,8 +192,7 @@ InternalFile::OpenWrite(std::filesystem::path FileName, bool IsCreate) if (Success) { - using namespace fmt::literals; - zen::ThrowLastError("Failed to open file for writing: '{}'"_format(FileName)); + zen::ThrowLastError(fmt::format("Failed to open file for writing: '{}'", FileName)); } } @@ -218,8 +217,7 @@ InternalFile::OpenRead(std::filesystem::path FileName) if (Success) { - using namespace fmt::literals; - zen::ThrowLastError("Failed to open file for reading: '{}'"_format(FileName)); + zen::ThrowLastError(fmt::format("Failed to open file for reading: '{}'", FileName)); } } @@ -267,8 +265,7 @@ InternalFile::Read(void* Data, uint64_t Size, uint64_t Offset) if (Success) { - using namespace fmt::literals; - zen::ThrowLastError("Failed to read from file '{}'"_format("")); // zen::PathFromHandle(m_File))); + zen::ThrowLastError(fmt::format("Failed to read from file '{}'", "")); // zen::PathFromHandle(m_File))); } } @@ -293,7 +290,6 @@ InternalFile::Write(const void* Data, uint64_t Size, uint64_t Offset) if (Success) { - using namespace fmt::literals; - zen::ThrowLastError("Failed to write to file '{}'"_format(zen::PathFromHandle(m_File))); + zen::ThrowLastError(fmt::format("Failed to write to file '{}'", zen::PathFromHandle(m_File))); } } diff --git a/zencore/compactbinary.cpp b/zencore/compactbinary.cpp index 494b45581..cded378a1 100644 --- a/zencore/compactbinary.cpp +++ b/zencore/compactbinary.cpp @@ -197,8 +197,6 @@ DateTime::GetDate(int& Year, int& Month, int& Day) const std::string DateTime::ToString(const char* Format) const { - using namespace fmt::literals; - ExtendableStringBuilder<32> Result; int Year, Month, Day; @@ -215,32 +213,32 @@ DateTime::ToString(const char* Format) const // case 'a': Result.Append(IsMorning() ? TEXT("am") : TEXT("pm")); break; // case 'A': Result.Append(IsMorning() ? TEXT("AM") : TEXT("PM")); break; case 'd': - Result.Append("{:02}"_format(Day)); + Result.Append(fmt::format("{:02}", Day)); break; // case 'D': Result.Appendf(TEXT("%03i"), GetDayOfYear()); break; case 'm': - Result.Append("{:02}"_format(Month)); + Result.Append(fmt::format("{:02}", Month)); break; case 'y': - Result.Append("{:02}"_format(Year % 100)); + Result.Append(fmt::format("{:02}", Year % 100)); break; case 'Y': - Result.Append("{:04}"_format(Year)); + Result.Append(fmt::format("{:04}", Year)); break; case 'h': - Result.Append("{:02}"_format(GetHour12())); + Result.Append(fmt::format("{:02}", GetHour12())); break; case 'H': - Result.Append("{:02}"_format(GetHour())); + Result.Append(fmt::format("{:02}", GetHour())); break; case 'M': - Result.Append("{:02}"_format(GetMinute())); + Result.Append(fmt::format("{:02}", GetMinute())); break; case 'S': - Result.Append("{:02}"_format(GetSecond())); + Result.Append(fmt::format("{:02}", GetSecond())); break; case 's': - Result.Append("{:03}"_format(GetMillisecond())); + Result.Append(fmt::format("{:03}", GetMillisecond())); break; default: Result.Append(*Format); @@ -282,8 +280,6 @@ TimeSpan::Set(int Days, int Hours, int Minutes, int Seconds, int FractionNano) std::string TimeSpan::ToString(const char* Format) const { - using namespace fmt::literals; - StringBuilder<128> Result; Result.Append((int64_t(Ticks) < 0) ? '-' : '+'); @@ -295,31 +291,31 @@ TimeSpan::ToString(const char* Format) const switch (*Format) { case 'd': - Result.Append("{}"_format(GetDays())); + Result.Append(fmt::format("{}", GetDays())); break; case 'D': - Result.Append("{:08}"_format(GetDays())); + Result.Append(fmt::format("{:08}", GetDays())); break; case 'h': - Result.Append("{:02}"_format(GetHours())); + Result.Append(fmt::format("{:02}", GetHours())); break; case 'm': - Result.Append("{:02}"_format(GetMinutes())); + Result.Append(fmt::format("{:02}", GetMinutes())); break; case 's': - Result.Append("{:02}"_format(GetSeconds())); + Result.Append(fmt::format("{:02}", GetSeconds())); break; case 'f': - Result.Append("{:03}"_format(GetFractionMilli())); + Result.Append(fmt::format("{:03}", GetFractionMilli())); break; case 'u': - Result.Append("{:06}"_format(GetFractionMicro())); + Result.Append(fmt::format("{:06}", GetFractionMicro())); break; case 't': - Result.Append("{:07}"_format(GetFractionTicks())); + Result.Append(fmt::format("{:07}", GetFractionTicks())); break; case 'n': - Result.Append("{:09}"_format(GetFractionNano())); + Result.Append(fmt::format("{:09}", GetFractionNano())); break; default: Result.Append(*Format); @@ -1442,7 +1438,6 @@ public: void WriteField(CbFieldView Field) { - using namespace fmt::literals; using namespace std::literals; WriteOptionalComma(); @@ -1512,7 +1507,7 @@ public: const float Value = Accessor.AsFloat32(); if (std::isfinite(Value)) { - Builder.Append("{:.9g}"_format(Value)); + Builder.Append(fmt::format("{:.9g}", Value)); } else { @@ -1525,7 +1520,7 @@ public: const double Value = Accessor.AsFloat64(); if (std::isfinite(Value)) { - Builder.Append("{:.17g}"_format(Value)); + Builder.Append(fmt::format("{:.17g}", Value)); } else { diff --git a/zencore/except.cpp b/zencore/except.cpp index fae629286..2749d1984 100644 --- a/zencore/except.cpp +++ b/zencore/except.cpp @@ -58,12 +58,6 @@ ThrowSystemException([[maybe_unused]] HRESULT hRes, [[maybe_unused]] std::string #endif // ZEN_PLATFORM_WINDOWS void -ThrowLastError(std::string_view Message) -{ - throw std::system_error(std::error_code(zen::GetLastError(), std::system_category()), std::string(Message)); -} - -void ThrowSystemError(uint32_t ErrorCode, std::string_view Message) { throw std::system_error(std::error_code(ErrorCode, std::system_category()), std::string(Message)); @@ -83,11 +77,16 @@ GetSystemErrorAsString(uint32_t ErrorCode) #if defined(__cpp_lib_source_location) void -ThrowLastError(std::string_view Message, const std::source_location& Location) +ThrowLastErrorImpl(std::string_view Message, const std::source_location& Location) { - using namespace fmt::literals; throw std::system_error(std::error_code(zen::GetLastError(), std::system_category()), - "{}({}): {}"_format(Location.file_name(), Location.line(), Message)); + fmt::format("{}({}): {}", Location.file_name(), Location.line(), Message)); +} +#else +void +ThrowLastError(std::string_view Message) +{ + throw std::system_error(std::error_code(zen::GetLastError(), std::system_category()), std::string(Message)); } #endif diff --git a/zencore/filesystem.cpp b/zencore/filesystem.cpp index 2507037ea..bed08b3f5 100644 --- a/zencore/filesystem.cpp +++ b/zencore/filesystem.cpp @@ -487,8 +487,6 @@ CopyFile(std::filesystem::path FromPath, std::filesystem::path ToPath, const Cop &CancelFlag, /* dwCopyFlags */ 0); #else - using namespace fmt::literals; - struct ScopedFd { ~ScopedFd() { close(Fd); } @@ -499,7 +497,7 @@ CopyFile(std::filesystem::path FromPath, std::filesystem::path ToPath, const Cop int FromFd = open(FromPath.c_str(), O_RDONLY | O_CLOEXEC); if (FromFd < 0) { - ThrowLastError("failed to open file {}"_format(FromPath)); + ThrowLastError(fmt::format("failed to open file {}", FromPath)); } ScopedFd $From = {FromFd}; @@ -507,7 +505,7 @@ CopyFile(std::filesystem::path FromPath, std::filesystem::path ToPath, const Cop int ToFd = open(ToPath.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0644); if (ToFd < 0) { - ThrowLastError("failed to create file {}"_format(ToPath)); + ThrowLastError(fmt::format("failed to create file {}", ToPath)); } ScopedFd $To = {ToFd}; @@ -543,8 +541,6 @@ CopyFile(std::filesystem::path FromPath, std::filesystem::path ToPath, const Cop void WriteFile(std::filesystem::path Path, const IoBuffer* const* Data, size_t BufferCount) { - using namespace fmt::literals; - #if ZEN_PLATFORM_WINDOWS CAtlFile Outfile; HRESULT hRes = Outfile.Create(Path.c_str(), GENERIC_WRITE, FILE_SHARE_READ, CREATE_ALWAYS); @@ -557,7 +553,7 @@ WriteFile(std::filesystem::path Path, const IoBuffer* const* Data, size_t Buffer if (FAILED(hRes)) { - ThrowSystemException(hRes, "File open failed for '{}'"_format(Path).c_str()); + ThrowSystemException(hRes, fmt::format("File open failed for '{}'", Path).c_str()); } #else @@ -571,7 +567,7 @@ WriteFile(std::filesystem::path Path, const IoBuffer* const* Data, size_t Buffer if (Fd < 0) { - ThrowLastError("File open failed for '{}'"_format(Path)); + ThrowLastError(fmt::format("File open failed for '{}'", Path)); } #endif @@ -590,12 +586,12 @@ WriteFile(std::filesystem::path Path, const IoBuffer* const* Data, size_t Buffer hRes = Outfile.Write(DataPtr, gsl::narrow_cast<uint32_t>(WriteSize)); if (FAILED(hRes)) { - ThrowSystemException(hRes, "File write failed for '{}'"_format(Path).c_str()); + ThrowSystemException(hRes, fmt::format("File write failed for '{}'", Path).c_str()); } #else if (write(Fd, DataPtr, WriteSize) != int64_t(WriteSize)) { - ThrowLastError("File write failed for '{}'"_format(Path)); + ThrowLastError(fmt::format("File write failed for '{}'", Path)); } #endif // ZEN_PLATFORM_WINDOWS @@ -867,14 +863,12 @@ FileSystemTraversal::TraverseFileSystem(const std::filesystem::path& RootDir, Tr } } #else - using namespace fmt::literals; - /* Could also implement this using Linux's getdents() syscall */ DIR* Dir = opendir(RootDir.c_str()); if (Dir == nullptr) { - ThrowLastError("Failed to open directory for traversal: {}"_format(RootDir.c_str())); + ThrowLastError(fmt::format("Failed to open directory for traversal: {}", RootDir.c_str())); } for (struct dirent* Entry; (Entry = readdir(Dir));) diff --git a/zencore/include/zencore/compactbinarybuilder.h b/zencore/include/zencore/compactbinarybuilder.h index 5f6d9fd0c..aee95ea5b 100644 --- a/zencore/include/zencore/compactbinarybuilder.h +++ b/zencore/include/zencore/compactbinarybuilder.h @@ -539,6 +539,15 @@ operator<<(CbWriter& Writer, std::nullptr_t) return Writer; } +#if defined(__clang__) +inline CbWriter& +operator<<(CbWriter& Writer, std::size_t Value) +{ + Writer.AddInteger(uint64_t(Value)); + return Writer; +} +#endif + inline CbWriter& operator<<(CbWriter& Writer, std::wstring_view Value) { diff --git a/zencore/include/zencore/except.h b/zencore/include/zencore/except.h index 6719c1319..d714b6ade 100644 --- a/zencore/include/zencore/except.h +++ b/zencore/include/zencore/except.h @@ -20,10 +20,11 @@ namespace zen { ZENCORE_API void ThrowSystemException [[noreturn]] (HRESULT hRes, std::string_view Message); #endif // ZEN_PLATFORM_WINDOWS -ZENCORE_API void ThrowLastError [[noreturn]] (std::string_view Message); - #if defined(__cpp_lib_source_location) -ZENCORE_API void ThrowLastError [[noreturn]] (std::string_view Message, const std::source_location& Location); +ZENCORE_API void ThrowLastErrorImpl [[noreturn]] (std::string_view Message, const std::source_location& Location); +#define ThrowLastError(Message) ThrowLastErrorImpl(Message, std::source_location::current()) +#else +ZENCORE_API void ThrowLastError [[noreturn]] (std::string_view Message); #endif ZENCORE_API void ThrowSystemError [[noreturn]] (uint32_t ErrorCode, std::string_view Message); diff --git a/zencore/include/zencore/trace.h b/zencore/include/zencore/trace.h index 8d8cebb51..f28fdeeaf 100644 --- a/zencore/include/zencore/trace.h +++ b/zencore/include/zencore/trace.h @@ -2,6 +2,8 @@ #pragma once +/* clang-format off */ + #include <zencore/zencore.h> #if ZEN_WITH_TRACE @@ -29,3 +31,5 @@ void TraceInit(const char* HostOrPath, TraceType Type); #define ZEN_TRACE_CPU(x) #endif // ZEN_WITH_TRACE + +/* clang-format on */ diff --git a/zencore/include/zencore/zencore.h b/zencore/include/zencore/zencore.h index 8688ddc13..12eacfb00 100644 --- a/zencore/include/zencore/zencore.h +++ b/zencore/include/zencore/zencore.h @@ -132,7 +132,7 @@ template <class T> concept Integral = std::is_integral_v<T>; template <class T> concept SignedIntegral = Integral<T> && std::is_signed_v<T>; template <class T> concept UnsignedIntegral = Integral<T> && !std::is_signed_v<T>; - template <class F, class... A> concept Invocable = true; + template <class F, class... A> concept Invocable = requires(F&& f, A&&... a) { std::invoke(std::forward<F>(f), std::forward<A>(a)...); }; template <class D, class B> concept DerivedFrom = std::is_base_of_v<B, D> && std::is_convertible_v<const volatile D*, const volatile B*>; #endif diff --git a/zencore/iobuffer.cpp b/zencore/iobuffer.cpp index 30865068a..b6bbedc40 100644 --- a/zencore/iobuffer.cpp +++ b/zencore/iobuffer.cpp @@ -231,8 +231,6 @@ static RwLock g_MappingLock; void IoBufferExtendedCore::Materialize() const { - using namespace fmt::literals; - // The synchronization scheme here is very primitive, if we end up with // a lot of contention we can make it more fine-grained @@ -264,7 +262,7 @@ IoBufferExtendedCore::Materialize() const if (NewMmapHandle == nullptr) { throw std::system_error(std::error_code(::GetLastError(), std::system_category()), - "CreateFileMapping failed on file '{}'"_format(zen::PathFromHandle(m_FileHandle))); + fmt::format("CreateFileMapping failed on file '{}'", zen::PathFromHandle(m_FileHandle))); } NewFlags |= kOwnsMmap; @@ -291,7 +289,7 @@ IoBufferExtendedCore::Materialize() const { throw std::system_error( std::error_code(zen::GetLastError(), std::system_category()), - "MapViewOfFile failed (offset {:#x}, size {:#x}) file: '{}'"_format(MapOffset, MapSize, zen::PathFromHandle(m_FileHandle))); + fmt::format("MapViewOfFile failed (offset {:#x}, size {:#x}) file: '{}'", MapOffset, MapSize, zen::PathFromHandle(m_FileHandle))); } m_MappedPointer = MappedBase; diff --git a/zencore/thread.cpp b/zencore/thread.cpp index 596549bb5..97d44e733 100644 --- a/zencore/thread.cpp +++ b/zencore/thread.cpp @@ -8,17 +8,22 @@ #include <zencore/string.h> #include <zencore/testing.h> +#if ZEN_PLATFORM_LINUX +# if !defined(_GNU_SOURCE) +# define _GNU_SOURCE // for semtimedop() +# endif +#endif + #if ZEN_PLATFORM_WINDOWS # include <shellapi.h> # include <Shlobj.h> # include <zencore/windows.h> -#elif ZEN_PLATFORM_LINUX +#else # include <chrono> # include <condition_variable> # include <mutex> # include <fcntl.h> -# include <mqueue.h> # include <pthread.h> # include <signal.h> # include <sys/file.h> @@ -27,6 +32,14 @@ # include <unistd.h> #endif +#if ZEN_PLATFORM_LINUX +# include <mqueue.h> +#endif + +#if ZEN_PLATFORM_MAC +# include <sys/sem.h> +#endif + #include <thread> ZEN_THIRD_PARTY_INCLUDES_START @@ -278,9 +291,9 @@ NamedEvent::NamedEvent(std::string_view EventName) int LockResult = flock(Inner, LOCK_EX | LOCK_NB); if (LockResult == 0) { - // This is really thread safe as the message queue could be set between - // getting the exclusive lock and checking the queue. But for the our - // simple synchronising of process, this should be okay. + // This isn't really thread safe as the message queue could be set + // between getting the exclusive lock and checking the queue. But for + // the our simple synchronising of process, this should be okay. while (!IsMessageQueueEmpty(Inner)) { char Sink; @@ -289,8 +302,51 @@ NamedEvent::NamedEvent(std::string_view EventName) } m_EventHandle = (void*)intptr_t(Inner); -#else -# error Implement NamedEvent for this platform +#elif ZEN_PLATFORM_MAC + // Create a file to back the semaphore + ExtendableStringBuilder<64> EventPath; + EventPath << "/tmp/" << EventName; + + int Fd = open(EventPath.c_str(), O_RDWR|O_CREAT, 0644); + if (Fd < 0) + { + ThrowLastError(fmt::format("Failed to create '{}' for named event", EventPath)); + } + + // Use the file path to generate an IPC key + key_t IpcKey = ftok(EventPath.c_str(), 1); + if (IpcKey < 0) + { + close(Fd); + ThrowLastError("Failed to create an SysV IPC key"); + } + + // Use the key to create/open the semaphore + int Sem = semget(IpcKey, 1, 0600 | IPC_CREAT); + if (Sem < 0) + { + close(Fd); + ThrowLastError("Failed creating an SysV semaphore"); + } + + // Atomically claim ownership of the semaphore's key. The owner initialises + // the semaphore to 1 so we can use the wait-for-zero op as that does not + // modify the semaphore's value on a successful wait. + int LockResult = flock(Fd, LOCK_EX | LOCK_NB); + if (LockResult == 0) + { + // This isn't thread safe really. Another thread could open the same + // semaphore and successfully wait on it in the period of time where + // this comment is but before the semaphore's initialised. + semctl(Sem, 0, SETVAL, 1); + } + + // Pack into the handle + static_assert(sizeof(Sem) + sizeof(Fd) <= sizeof(void*), "Semaphore packing assumptions not met"); + intptr_t Packed; + Packed = intptr_t(Sem) << 32; + Packed |= intptr_t(Fd) & 0xffff'ffff; + m_EventHandle = (void*)Packed; #endif } @@ -310,7 +366,7 @@ NamedEvent::Close() #if ZEN_PLATFORM_WINDOWS CloseHandle(m_EventHandle); #elif ZEN_PLATFORM_LINUX - int Inner = int(intptr_t(m_EventHandle)); + int Inner = int(intptr_t(m_EventHandle)); if (flock(Inner, LOCK_EX | LOCK_NB) == 0) { @@ -320,6 +376,20 @@ NamedEvent::Close() } close(Inner); +#elif ZEN_PLATFORM_MAC + int Fd = int(intptr_t(m_EventHandle) & 0xffff'ffff); + + if (flock(Fd, LOCK_EX | LOCK_NB) == 0) + { + std::filesystem::path Name = PathFromHandle((void*)(intptr_t(Fd))); + unlink(Name.c_str()); + + flock(Fd, LOCK_UN | LOCK_NB); + close(Fd); + + int Sem = int(intptr_t(m_EventHandle) >> 32); + semctl(Sem, 0, IPC_RMID); + } #endif m_EventHandle = nullptr; @@ -343,6 +413,9 @@ NamedEvent::Set() { ThrowLastError("Unable to send set message to queue"); } +#elif ZEN_PLATFORM_MAC + int Sem = int(intptr_t(m_EventHandle) >> 32); + semctl(Sem, 0, SETVAL, 0); #endif } @@ -370,8 +443,8 @@ NamedEvent::Wait(int TimeoutMs) } struct timeval TimeoutValue = { - .tv_sec = 0, - .tv_usec = TimeoutMs << 10, + .tv_sec = (TimeoutMs >> 10), + .tv_usec = (TimeoutMs & 0x3ff) << 10, }; struct timeval* TimeoutPtr = (TimeoutMs < 0) ? nullptr : &TimeoutValue; @@ -379,6 +452,43 @@ NamedEvent::Wait(int TimeoutMs) FD_ZERO(&FdSet); FD_SET(Inner, &FdSet); return select(Inner + 1, &FdSet, nullptr, nullptr, TimeoutPtr) > 0; +#elif ZEN_PLATFORM_MAC + int Sem = int(intptr_t(m_EventHandle) >> 32); + + int Result; + struct sembuf SemOp = {}; + + if (TimeoutMs < 0) + { + Result = semop(Sem, &SemOp, 1); + return Result == 0; + } + +#if defined(_GNU_SOURCE) + struct timespec TimeoutValue = { + .tv_sec = TimeoutMs >> 10, + .tv_nsec = (TimeoutMs & 0x3ff) << 20, + }; + int Result = semtimedop(Sem, &SemOp, 1, &TimeoutValue); + return Result == 0; +#else + const int SleepTimeMs = 10; + SemOp.sem_flg = IPC_NOWAIT; + do + { + Result = semop(Sem, &SemOp, 1); + if (Result == 0 || errno != EAGAIN) + { + break; + } + + Sleep(SleepTimeMs); + TimeoutMs -= SleepTimeMs; + } + while (TimeoutMs > 0); + + return Result == 0; +#endif // _GNU_SOURCE #endif } @@ -511,19 +621,16 @@ ProcessHandle::Initialize(int Pid) #if ZEN_PLATFORM_WINDOWS m_ProcessHandle = OpenProcess(PROCESS_QUERY_INFORMATION | SYNCHRONIZE, FALSE, Pid); -#elif ZEN_PLATFORM_LINUX +#elif ZEN_PLATFORM_LINUX || ZEN_PLATFORM_MAC if (Pid > 0) { m_ProcessHandle = (void*)(intptr_t(Pid)); } -#else -# error Check process control on this platform #endif if (!m_ProcessHandle) { - using namespace fmt::literals; - ThrowLastError("ProcessHandle::Initialize(pid: {}) failed"_format(Pid)); + ThrowLastError(fmt::format("ProcessHandle::Initialize(pid: {}) failed", Pid)); } m_Pid = Pid; @@ -538,12 +645,8 @@ ProcessHandle::IsRunning() const DWORD ExitCode = 0; GetExitCodeProcess(m_ProcessHandle, &ExitCode); bActive = (ExitCode == STILL_ACTIVE); -#elif ZEN_PLATFORM_LINUX - StringBuilder<64> ProcPath; - ProcPath << "/proc/" << m_Pid; - bActive = (access(ProcPath.c_str(), F_OK) != 0); -#else -# error Check process control on this platform +#elif ZEN_PLATFORM_LINUX || ZEN_PLATFORM_MAC + bActive = (kill(pid_t(m_Pid), 0) == 0); #endif return bActive; @@ -569,11 +672,9 @@ ProcessHandle::Terminate(int ExitCode) TerminateProcess(m_ProcessHandle, ExitCode); DWORD WaitResult = WaitForSingleObject(m_ProcessHandle, INFINITE); bSuccess = (WaitResult != WAIT_OBJECT_0); -#elif ZEN_PLATFORM_LINUX +#elif ZEN_PLATFORM_LINUX || ZEN_PLATFORM_MAC ZEN_UNUSED(ExitCode); - bSuccess = (kill(m_Pid, SIGKILL) == 0); -#else -# error Check kill() on this platform + bSuccess = (kill(m_Pid, SIGKILL) == 0); #endif if (!bSuccess) @@ -616,7 +717,7 @@ ProcessHandle::Wait(int TimeoutMs) case WAIT_FAILED: break; } -#elif ZEN_PLATFORM_LINUX +#elif ZEN_PLATFORM_LINUX || ZEN_PLATFORM_MAC const int SleepMs = 20; timespec SleepTime = {0, SleepMs * 1000 * 1000}; for (int i = 0;; i += SleepMs) @@ -640,8 +741,6 @@ ProcessHandle::Wait(int TimeoutMs) nanosleep(&SleepTime, nullptr); } -#else -# error Check kill() on this platform #endif // What might go wrong here, and what is meaningful to act on? @@ -1012,20 +1111,14 @@ IsProcessRunning(int pid) return false; } - using namespace fmt::literals; - ThrowSystemError(Error, "failed to open process with pid {}"_format(pid)); + ThrowSystemError(Error, fmt::format("failed to open process with pid {}", pid)); } CloseHandle(hProc); return true; -#elif ZEN_PLATFORM_LINUX - char Buffer[64]; - sprintf(Buffer, "/proc/%d", pid); - return access(Buffer, F_OK) == 0; -#elif ZEN_PLATFORM_MAC - kill(pid_t(pid), 0); - return errno != ESRCH; +#elif ZEN_PLATFORM_LINUX || ZEN_PLATFORM_MAC + return (kill(pid_t(pid), 0) == 0); #endif } @@ -1078,6 +1171,8 @@ TEST_CASE("Thread") int Pid = GetCurrentProcessId(); CHECK(Pid > 0); CHECK(IsProcessRunning(Pid)); + + CHECK_FALSE(GetCurrentThreadId() == 0); } TEST_CASE("BuildArgV") diff --git a/zencore/trace.cpp b/zencore/trace.cpp index f6a303960..6a35571e6 100644 --- a/zencore/trace.cpp +++ b/zencore/trace.cpp @@ -1,12 +1,13 @@ // Copyright Epic Games, Inc. All Rights Reserved. +/* clang-format off */ + #if ZEN_WITH_TRACE -# include <zencore/zencore.h> +#include <zencore/zencore.h> -# define TRACE_IMPLEMENT 1 -# include <zencore/trace.h> -//#undef TRACE_IMPLEMENT +#define TRACE_IMPLEMENT 1 +#include <zencore/trace.h> void TraceInit(const char* HostOrPath, TraceType Type) @@ -31,3 +32,5 @@ TraceInit(const char* HostOrPath, TraceType Type) } #endif // ZEN_WITH_TRACE + +/* clang-format on */ diff --git a/zenhttp/httpasio.cpp b/zenhttp/httpasio.cpp index e1d417d06..7a6efd884 100644 --- a/zenhttp/httpasio.cpp +++ b/zenhttp/httpasio.cpp @@ -7,7 +7,7 @@ #include <deque> #include <memory> -#include <memory_resource> +#include <vector> ZEN_THIRD_PARTY_INCLUDES_START #if ZEN_PLATFORM_WINDOWS @@ -28,7 +28,6 @@ ZEN_THIRD_PARTY_INCLUDES_END namespace zen::asio_http { using namespace std::literals; -using namespace fmt::literals; struct HttpAcceptor; struct HttpRequest; @@ -154,6 +153,14 @@ struct HttpRequest private: struct HeaderEntry { + HeaderEntry() = default; + + HeaderEntry(std::string_view InName, std::string_view InValue) + : Name(InName) + , Value(InValue) + { + } + std::string_view Name; std::string_view Value; }; @@ -1127,7 +1134,7 @@ HttpAsioServerImpl::Start(uint16_t Port, int ThreadCount) for (int i = 0; i < ThreadCount; ++i) { m_ThreadPool.emplace_back([this, Index = i + 1] { - SetCurrentThreadName("asio worker {}"_format(Index)); + SetCurrentThreadName(fmt::format("asio worker {}", Index)); try { diff --git a/zenhttp/httpserver.cpp b/zenhttp/httpserver.cpp index 5712563c3..62b8d11a1 100644 --- a/zenhttp/httpserver.cpp +++ b/zenhttp/httpserver.cpp @@ -379,7 +379,7 @@ HttpServerRequest::WriteResponse(HttpResponseCode ResponseCode, HttpContentType Buffers.push_back(Segment.AsIoBuffer()); } - WriteResponse(ResponseCode, ContentType, Payload); + WriteResponse(ResponseCode, ContentType, Buffers); } HttpServerRequest::QueryParams @@ -400,7 +400,8 @@ HttpServerRequest::GetQueryParams() continue; } - const std::string_view Query{QueryIt, QueryEnd}; + size_t QueryLen = ptrdiff_t(QueryEnd - QueryIt); + const std::string_view Query{QueryIt, QueryLen}; size_t DelimIndex = Query.find('&', 0); @@ -415,10 +416,10 @@ HttpServerRequest::GetQueryParams() if (EqIndex != std::string_view::npos) { - std::string_view Parm{ThisQuery.data(), EqIndex}; + std::string_view Param{ThisQuery.data(), EqIndex}; ThisQuery.remove_prefix(EqIndex + 1); - Params.KvPairs.emplace_back(Parm, ThisQuery); + Params.KvPairs.emplace_back(Param, ThisQuery); } QueryIt += DelimIndex; diff --git a/zenhttp/httpsys.cpp b/zenhttp/httpsys.cpp index a17c2661c..67ff6b46b 100644 --- a/zenhttp/httpsys.cpp +++ b/zenhttp/httpsys.cpp @@ -674,8 +674,6 @@ HttpAsyncWorkRequest::HandleCompletion(ULONG IoResult, ULONG_PTR NumberOfBytesTr void HttpAsyncWorkRequest::AsyncWorkItem::Execute() { - using namespace fmt::literals; - try { HttpSysServerRequest& ThisRequest = Tx.ServerRequest(); @@ -705,7 +703,7 @@ HttpAsyncWorkRequest::AsyncWorkItem::Execute() } catch (std::exception& Ex) { - return (void)Tx.IssueNextRequest(new HttpMessageResponseRequest(Tx, 500, "Exception thrown in async work: '{}'"_format(Ex.what()))); + return (void)Tx.IssueNextRequest(new HttpMessageResponseRequest(Tx, 500, fmt::format("Exception thrown in async work: '{}'", Ex.what()))); } } diff --git a/zenserver-test/projectclient.cpp b/zenserver-test/projectclient.cpp index 88608bfe0..597838e0d 100644 --- a/zenserver-test/projectclient.cpp +++ b/zenserver-test/projectclient.cpp @@ -19,8 +19,6 @@ namespace zen { -using namespace fmt::literals; - struct ProjectClientConnection { ProjectClientConnection(int BasePort) { Connect(BasePort); } @@ -45,7 +43,7 @@ struct ProjectClientConnection { ZEN_WARN("failed while creating named pipe {}", WideToUtf8(PipeName)); - throw std::system_error(GetLastError(), std::system_category(), "Failed to open named pipe '{}'"_format(WideToUtf8(PipeName))); + throw std::system_error(GetLastError(), std::system_category(), fmt::format("Failed to open named pipe '{}'", WideToUtf8(PipeName))); } // Change to message mode @@ -56,7 +54,7 @@ struct ProjectClientConnection { throw std::system_error(GetLastError(), std::system_category(), - "Failed to change named pipe '{}' to message mode"_format(WideToUtf8(PipeName))); + fmt::format("Failed to change named pipe '{}' to message mode", WideToUtf8(PipeName))); } m_hPipe.Attach(hPipe); // This now owns the handle and will close it diff --git a/zenserver-test/zenserver-test.cpp b/zenserver-test/zenserver-test.cpp index 2266e5305..d5e68caed 100644 --- a/zenserver-test/zenserver-test.cpp +++ b/zenserver-test/zenserver-test.cpp @@ -71,7 +71,6 @@ ZEN_THIRD_PARTY_INCLUDES_END # undef DOCTEST_CONFIG_IMPLEMENT #endif -using namespace fmt::literals; using namespace std::literals; #if ZEN_PLATFORM_LINUX || ZEN_PLATFORM_MAC @@ -173,8 +172,7 @@ private: return; } - using namespace fmt::literals; - zen::ThrowLastError("HTTP client error! '{}'"_format(Error.message())); + zen::ThrowLastError(fmt::format("HTTP client error! '{}'", Error.message())); } int OnHeader(const char* Data, size_t Bytes) @@ -344,8 +342,6 @@ HttpConnectionPool::~HttpConnectionPool() std::unique_ptr<HttpClientConnection> HttpConnectionPool::GetConnection() { - using namespace fmt::literals; - zen::RwLock::ExclusiveLockScope ScopedLock(m_Lock); if (m_AvailableConnections.empty()) @@ -361,7 +357,7 @@ HttpConnectionPool::GetConnection() if (ErrCode) { - zen::ThrowLastError("Unabled to resolve '{}'"_format(m_HostName)); + zen::ThrowLastError(fmt::format("Unabled to resolve '{}'", m_HostName)); } asio::ip::tcp::socket Socket{m_Context}; @@ -369,7 +365,7 @@ HttpConnectionPool::GetConnection() if (ErrCode) { - zen::ThrowLastError("Failed connecting '{}:{}'"_format(m_HostName, m_Port)); + zen::ThrowLastError(fmt::format("Failed connecting '{}:{}'", m_HostName, m_Port)); } return std::make_unique<HttpClientConnection>(m_Context, this, std::move(Socket)); @@ -835,7 +831,7 @@ TEST_CASE("multi.basic") ZEN_INFO("query batch {} started (thread {}) for port {}", BatchNo, ThreadId, PortNumber); cpr::Session cli; - cli.SetUrl(cpr::Url{"http://localhost:{}/test/hello"_format(PortNumber)}); + cli.SetUrl(cpr::Url{fmt::format("http://localhost:{}/test/hello", PortNumber)}); for (int i = 0; i < 10000; ++i) { @@ -877,13 +873,12 @@ TEST_CASE("cas.basic") Instance1.WaitUntilReady(); std::atomic<uint64_t> RequestCount{0}; - std::atomic<uint64_t> BatchCounter{0}; zen::Stopwatch timer; std::mt19937_64 mt; - auto BaseUri = "http://localhost:{}/cas"_format(PortNumber); + auto BaseUri = fmt::format("http://localhost:{}/cas", PortNumber); cpr::Session cli; cli.SetUrl(cpr::Url{BaseUri}); @@ -946,7 +941,7 @@ TEST_CASE("cas.basic") for (int i = 0; i < IterationCount; ++i) { zen::ExtendableStringBuilder<128> Uri; - Uri << "http://localhost:{}/cas/"_format(PortNumber); + Uri << fmt::format("http://localhost:{}/cas/", PortNumber); ChunkHashes[i].ToHexString(Uri); auto res = cpr::Get(cpr::Url{Uri.c_str()}); @@ -980,7 +975,7 @@ TEST_CASE("project.basic") std::mt19937_64 mt; zen::StringBuilder<64> BaseUri; - BaseUri << "http://localhost:{}/prj/test"_format(PortNumber); + BaseUri << fmt::format("http://localhost:{}/prj/test", PortNumber); std::filesystem::path BinPath = zen::GetRunningExecutablePath(); std::filesystem::path RootPath = BinPath.parent_path().parent_path(); @@ -1148,13 +1143,13 @@ namespace utils { { return ZenConfig{.DataDir = TestEnv.CreateNewTestDir(), .Port = Port, - .BaseUri = "http://localhost:{}/z$"_format(Port), + .BaseUri = fmt::format("http://localhost:{}/z$", Port), .Args = std::move(Args)}; } static ZenConfig NewWithUpstream(uint16_t UpstreamPort) { - return New(13337, "--debug --upstream-thread-count=0 --upstream-zen-url=http://localhost:{}"_format(UpstreamPort)); + return New(13337, fmt::format("--debug --upstream-thread-count=0 --upstream-zen-url=http://localhost:{}", UpstreamPort)); } void Spawn(ZenServerInstance& Inst) @@ -1183,7 +1178,7 @@ TEST_CASE("zcache.basic") const uint16_t PortNumber = 13337; const int kIterationCount = 100; - const auto BaseUri = "http://localhost:{}/z$"_format(PortNumber); + const auto BaseUri = fmt::format("http://localhost:{}/z$", PortNumber); auto HashKey = [](int i) -> zen::IoHash { return zen::IoHash::HashBuffer(&i, sizeof i); }; @@ -1205,7 +1200,7 @@ TEST_CASE("zcache.basic") zen::IoHash Key = HashKey(i); - cpr::Response Result = cpr::Put(cpr::Url{"{}/{}/{}"_format(BaseUri, "test", Key)}, + cpr::Response Result = cpr::Put(cpr::Url{fmt::format("{}/{}/{}", BaseUri, "test", Key)}, cpr::Body{(const char*)MemOut.Data(), MemOut.Size()}, cpr::Header{{"Content-Type", "application/x-ue-cb"}}); @@ -1218,7 +1213,7 @@ TEST_CASE("zcache.basic") { zen::IoHash Key = zen::IoHash::HashBuffer(&i, sizeof i); - cpr::Response Result = cpr::Get(cpr::Url{"{}/{}/{}"_format(BaseUri, "test", Key)}); + cpr::Response Result = cpr::Get(cpr::Url{fmt::format("{}/{}/{}", BaseUri, "test", Key)}); CHECK(Result.status_code == 200); } @@ -1234,7 +1229,7 @@ TEST_CASE("zcache.basic") zen::IoHash Key = HashKey(442); - cpr::Response Result = cpr::Put(cpr::Url{"{}/{}/{}"_format(BaseUri, "te!st", Key)}, + cpr::Response Result = cpr::Put(cpr::Url{fmt::format("{}/{}/{}", BaseUri, "te!st", Key)}, cpr::Body{(const char*)MemOut.Data(), MemOut.Size()}, cpr::Header{{"Content-Type", "application/x-ue-cb"}}); @@ -1256,7 +1251,7 @@ TEST_CASE("zcache.basic") { zen::IoHash Key = HashKey(i); - cpr::Response Result = cpr::Get(cpr::Url{"{}/{}/{}"_format(BaseUri, "test", Key)}); + cpr::Response Result = cpr::Get(cpr::Url{fmt::format("{}/{}/{}", BaseUri, "test", Key)}); CHECK(Result.status_code == 200); } @@ -1297,7 +1292,7 @@ TEST_CASE("zcache.cbpackage") std::span<const zen::CbAttachment> LhsAttachments = Lhs.GetAttachments(); std::span<const zen::CbAttachment> RhsAttachments = Rhs.GetAttachments(); - if (LhsAttachments.size() != LhsAttachments.size()) + if (LhsAttachments.size() != RhsAttachments.size()) { return false; } @@ -1326,7 +1321,7 @@ TEST_CASE("zcache.cbpackage") { std::filesystem::path TestDir = TestEnv.CreateNewTestDir(); const uint16_t PortNumber = 13337; - const auto BaseUri = "http://localhost:{}/z$"_format(PortNumber); + const auto BaseUri = fmt::format("http://localhost:{}/z$", PortNumber); ZenServerInstance Instance1(TestEnv); Instance1.SetTestDir(TestDir); @@ -1340,7 +1335,7 @@ TEST_CASE("zcache.cbpackage") // PUT { zen::IoBuffer Body = SerializeToBuffer(ExpectedPackage); - cpr::Response Result = cpr::Put(cpr::Url{"{}/{}/{}"_format(BaseUri, Bucket, Key)}, + cpr::Response Result = cpr::Put(cpr::Url{fmt::format("{}/{}/{}", BaseUri, Bucket, Key)}, cpr::Body{(const char*)Body.Data(), Body.Size()}, cpr::Header{{"Content-Type", "application/x-ue-cbpkg"}}); CHECK(Result.status_code == 201); @@ -1349,7 +1344,7 @@ TEST_CASE("zcache.cbpackage") // GET { cpr::Response Result = - cpr::Get(cpr::Url{"{}/{}/{}"_format(BaseUri, Bucket, Key)}, cpr::Header{{"Accept", "application/x-ue-cbpkg"}}); + cpr::Get(cpr::Url{fmt::format("{}/{}/{}", BaseUri, Bucket, Key)}, cpr::Header{{"Accept", "application/x-ue-cbpkg"}}); CHECK(Result.status_code == 200); zen::IoBuffer Response(zen::IoBuffer::Wrap, Result.text.data(), Result.text.size()); @@ -1369,8 +1364,8 @@ TEST_CASE("zcache.cbpackage") const uint16_t LocalPortNumber = 13337; const uint16_t RemotePortNumber = 13338; - const auto LocalBaseUri = "http://localhost:{}/z$"_format(LocalPortNumber); - const auto RemoteBaseUri = "http://localhost:{}/z$"_format(RemotePortNumber); + const auto LocalBaseUri = fmt::format("http://localhost:{}/z$", LocalPortNumber); + const auto RemoteBaseUri = fmt::format("http://localhost:{}/z$", RemotePortNumber); ZenServerInstance RemoteInstance(TestEnv); RemoteInstance.SetTestDir(RemoteDataDir); @@ -1380,7 +1375,7 @@ TEST_CASE("zcache.cbpackage") ZenServerInstance LocalInstance(TestEnv); LocalInstance.SetTestDir(LocalDataDir); LocalInstance.SpawnServer(LocalPortNumber, - "--upstream-thread-count=0 --upstream-zen-url=http://localhost:{}"_format(RemotePortNumber)); + fmt::format("--upstream-thread-count=0 --upstream-zen-url=http://localhost:{}", RemotePortNumber)); LocalInstance.WaitUntilReady(); const std::string_view Bucket = "mosdef"sv; @@ -1390,7 +1385,7 @@ TEST_CASE("zcache.cbpackage") // Store the cache record package in the local instance { zen::IoBuffer Body = SerializeToBuffer(ExpectedPackage); - cpr::Response Result = cpr::Put(cpr::Url{"{}/{}/{}"_format(LocalBaseUri, Bucket, Key)}, + cpr::Response Result = cpr::Put(cpr::Url{fmt::format("{}/{}/{}", LocalBaseUri, Bucket, Key)}, cpr::Body{(const char*)Body.Data(), Body.Size()}, cpr::Header{{"Content-Type", "application/x-ue-cbpkg"}}); @@ -1400,7 +1395,7 @@ TEST_CASE("zcache.cbpackage") // The cache record can be retrieved as a package from the local instance { cpr::Response Result = - cpr::Get(cpr::Url{"{}/{}/{}"_format(LocalBaseUri, Bucket, Key)}, cpr::Header{{"Accept", "application/x-ue-cbpkg"}}); + cpr::Get(cpr::Url{fmt::format("{}/{}/{}", LocalBaseUri, Bucket, Key)}, cpr::Header{{"Accept", "application/x-ue-cbpkg"}}); CHECK(Result.status_code == 200); zen::IoBuffer Body(zen::IoBuffer::Wrap, Result.text.data(), Result.text.size()); @@ -1413,7 +1408,7 @@ TEST_CASE("zcache.cbpackage") // The cache record can be retrieved as a package from the remote instance { cpr::Response Result = - cpr::Get(cpr::Url{"{}/{}/{}"_format(RemoteBaseUri, Bucket, Key)}, cpr::Header{{"Accept", "application/x-ue-cbpkg"}}); + cpr::Get(cpr::Url{fmt::format("{}/{}/{}", RemoteBaseUri, Bucket, Key)}, cpr::Header{{"Accept", "application/x-ue-cbpkg"}}); CHECK(Result.status_code == 200); zen::IoBuffer Body(zen::IoBuffer::Wrap, Result.text.data(), Result.text.size()); @@ -1432,8 +1427,8 @@ TEST_CASE("zcache.cbpackage") const uint16_t LocalPortNumber = 13337; const uint16_t RemotePortNumber = 13338; - const auto LocalBaseUri = "http://localhost:{}/z$"_format(LocalPortNumber); - const auto RemoteBaseUri = "http://localhost:{}/z$"_format(RemotePortNumber); + const auto LocalBaseUri = fmt::format("http://localhost:{}/z$", LocalPortNumber); + const auto RemoteBaseUri = fmt::format("http://localhost:{}/z$", RemotePortNumber); ZenServerInstance RemoteInstance(TestEnv); RemoteInstance.SetTestDir(RemoteDataDir); @@ -1443,7 +1438,7 @@ TEST_CASE("zcache.cbpackage") ZenServerInstance LocalInstance(TestEnv); LocalInstance.SetTestDir(LocalDataDir); LocalInstance.SpawnServer(LocalPortNumber, - "--upstream-thread-count=0 --upstream-zen-url=http://localhost:{}"_format(RemotePortNumber)); + fmt::format("--upstream-thread-count=0 --upstream-zen-url=http://localhost:{}", RemotePortNumber)); LocalInstance.WaitUntilReady(); const std::string_view Bucket = "mosdef"sv; @@ -1453,7 +1448,7 @@ TEST_CASE("zcache.cbpackage") // Store the cache record package in upstream cache { zen::IoBuffer Body = SerializeToBuffer(ExpectedPackage); - cpr::Response Result = cpr::Put(cpr::Url{"{}/{}/{}"_format(RemoteBaseUri, Bucket, Key)}, + cpr::Response Result = cpr::Put(cpr::Url{fmt::format("{}/{}/{}", RemoteBaseUri, Bucket, Key)}, cpr::Body{(const char*)Body.Data(), Body.Size()}, cpr::Header{{"Content-Type", "application/x-ue-cbpkg"}}); @@ -1463,7 +1458,7 @@ TEST_CASE("zcache.cbpackage") // The cache record can be retrieved as a package from the local cache { cpr::Response Result = - cpr::Get(cpr::Url{"{}/{}/{}"_format(LocalBaseUri, Bucket, Key)}, cpr::Header{{"Accept", "application/x-ue-cbpkg"}}); + cpr::Get(cpr::Url{fmt::format("{}/{}/{}", LocalBaseUri, Bucket, Key)}, cpr::Header{{"Accept", "application/x-ue-cbpkg"}}); CHECK(Result.status_code == 200); zen::IoBuffer Body(zen::IoBuffer::Wrap, Result.text.data(), Result.text.size()); @@ -1534,20 +1529,20 @@ TEST_CASE("zcache.policy") // Store binary cache value upstream { - cpr::Response Result = cpr::Put(cpr::Url{"{}/{}/{}"_format(UpstreamCfg.BaseUri, Bucket, Key)}, + cpr::Response Result = cpr::Put(cpr::Url{fmt::format("{}/{}/{}", UpstreamCfg.BaseUri, Bucket, Key)}, cpr::Body{(const char*)BinaryValue.GetData(), BinaryValue.GetSize()}, cpr::Header{{"Content-Type", "application/octet-stream"}}); CHECK(Result.status_code == 201); } { - cpr::Response Result = cpr::Get(cpr::Url{"{}/{}/{}?query=local"_format(LocalCfg.BaseUri, Bucket, Key)}, + cpr::Response Result = cpr::Get(cpr::Url{fmt::format("{}/{}/{}?query=local", LocalCfg.BaseUri, Bucket, Key)}, cpr::Header{{"Accept", "application/octet-stream"}}); CHECK(Result.status_code == 404); } { - cpr::Response Result = cpr::Get(cpr::Url{"{}/{}/{}?query=local,remote"_format(LocalCfg.BaseUri, Bucket, Key)}, + cpr::Response Result = cpr::Get(cpr::Url{fmt::format("{}/{}/{}?query=local,remote", LocalCfg.BaseUri, Bucket, Key)}, cpr::Header{{"Accept", "application/octet-stream"}}); CHECK(Result.status_code == 200); } @@ -1569,21 +1564,21 @@ TEST_CASE("zcache.policy") // Store binary cache value locally { - cpr::Response Result = cpr::Put(cpr::Url{"{}/{}/{}?store=local"_format(LocalCfg.BaseUri, Bucket, Key)}, + cpr::Response Result = cpr::Put(cpr::Url{fmt::format("{}/{}/{}?store=local", LocalCfg.BaseUri, Bucket, Key)}, cpr::Body{(const char*)BinaryValue.GetData(), BinaryValue.GetSize()}, cpr::Header{{"Content-Type", "application/octet-stream"}}); CHECK(Result.status_code == 201); } { - cpr::Response Result = cpr::Get(cpr::Url{"{}/{}/{}"_format(UpstreamCfg.BaseUri, Bucket, Key)}, + cpr::Response Result = cpr::Get(cpr::Url{fmt::format("{}/{}/{}", UpstreamCfg.BaseUri, Bucket, Key)}, cpr::Header{{"Accept", "application/octet-stream"}}); CHECK(Result.status_code == 404); } { cpr::Response Result = - cpr::Get(cpr::Url{"{}/{}/{}"_format(LocalCfg.BaseUri, Bucket, Key)}, cpr::Header{{"Accept", "application/octet-stream"}}); + cpr::Get(cpr::Url{fmt::format("{}/{}/{}", LocalCfg.BaseUri, Bucket, Key)}, cpr::Header{{"Accept", "application/octet-stream"}}); CHECK(Result.status_code == 200); } } @@ -1604,21 +1599,21 @@ TEST_CASE("zcache.policy") // Store binary cache value locally and upstream { - cpr::Response Result = cpr::Put(cpr::Url{"{}/{}/{}?store=local,remote"_format(LocalCfg.BaseUri, Bucket, Key)}, + cpr::Response Result = cpr::Put(cpr::Url{fmt::format("{}/{}/{}?store=local,remote", LocalCfg.BaseUri, Bucket, Key)}, cpr::Body{(const char*)BinaryValue.GetData(), BinaryValue.GetSize()}, cpr::Header{{"Content-Type", "application/octet-stream"}}); CHECK(Result.status_code == 201); } { - cpr::Response Result = cpr::Get(cpr::Url{"{}/{}/{}"_format(UpstreamCfg.BaseUri, Bucket, Key)}, + cpr::Response Result = cpr::Get(cpr::Url{fmt::format("{}/{}/{}", UpstreamCfg.BaseUri, Bucket, Key)}, cpr::Header{{"Accept", "application/octet-stream"}}); CHECK(Result.status_code == 200); } { cpr::Response Result = - cpr::Get(cpr::Url{"{}/{}/{}"_format(LocalCfg.BaseUri, Bucket, Key)}, cpr::Header{{"Accept", "application/octet-stream"}}); + cpr::Get(cpr::Url{fmt::format("{}/{}/{}", LocalCfg.BaseUri, Bucket, Key)}, cpr::Header{{"Accept", "application/octet-stream"}}); CHECK(Result.status_code == 200); } } @@ -1641,20 +1636,20 @@ TEST_CASE("zcache.policy") // Store package upstream { - cpr::Response Result = cpr::Put(cpr::Url{"{}/{}/{}"_format(UpstreamCfg.BaseUri, Bucket, Key)}, + cpr::Response Result = cpr::Put(cpr::Url{fmt::format("{}/{}/{}", UpstreamCfg.BaseUri, Bucket, Key)}, cpr::Body{(const char*)Buf.GetData(), Buf.GetSize()}, cpr::Header{{"Content-Type", "application/x-ue-cbpkg"}}); CHECK(Result.status_code == 201); } { - cpr::Response Result = cpr::Get(cpr::Url{"{}/{}/{}?query=local"_format(LocalCfg.BaseUri, Bucket, Key)}, + cpr::Response Result = cpr::Get(cpr::Url{fmt::format("{}/{}/{}?query=local", LocalCfg.BaseUri, Bucket, Key)}, cpr::Header{{"Accept", "application/x-ue-cbpkg"}}); CHECK(Result.status_code == 404); } { - cpr::Response Result = cpr::Get(cpr::Url{"{}/{}/{}?query=local,remote"_format(LocalCfg.BaseUri, Bucket, Key)}, + cpr::Response Result = cpr::Get(cpr::Url{fmt::format("{}/{}/{}?query=local,remote", LocalCfg.BaseUri, Bucket, Key)}, cpr::Header{{"Accept", "application/x-ue-cbpkg"}}); CHECK(Result.status_code == 200); } @@ -1678,7 +1673,7 @@ TEST_CASE("zcache.policy") // Store packge locally { - cpr::Response Result = cpr::Put(cpr::Url{"{}/{}/{}?store=local"_format(LocalCfg.BaseUri, Bucket, Key)}, + cpr::Response Result = cpr::Put(cpr::Url{fmt::format("{}/{}/{}?store=local", LocalCfg.BaseUri, Bucket, Key)}, cpr::Body{(const char*)Buf.GetData(), Buf.GetSize()}, cpr::Header{{"Content-Type", "application/x-ue-cbpkg"}}); CHECK(Result.status_code == 201); @@ -1686,13 +1681,13 @@ TEST_CASE("zcache.policy") { cpr::Response Result = - cpr::Get(cpr::Url{"{}/{}/{}"_format(UpstreamCfg.BaseUri, Bucket, Key)}, cpr::Header{{"Accept", "application/x-ue-cbpkg"}}); + cpr::Get(cpr::Url{fmt::format("{}/{}/{}", UpstreamCfg.BaseUri, Bucket, Key)}, cpr::Header{{"Accept", "application/x-ue-cbpkg"}}); CHECK(Result.status_code == 404); } { cpr::Response Result = - cpr::Get(cpr::Url{"{}/{}/{}"_format(LocalCfg.BaseUri, Bucket, Key)}, cpr::Header{{"Accept", "application/x-ue-cbpkg"}}); + cpr::Get(cpr::Url{fmt::format("{}/{}/{}", LocalCfg.BaseUri, Bucket, Key)}, cpr::Header{{"Accept", "application/x-ue-cbpkg"}}); CHECK(Result.status_code == 200); } } @@ -1715,7 +1710,7 @@ TEST_CASE("zcache.policy") // Store package locally and upstream { - cpr::Response Result = cpr::Put(cpr::Url{"{}/{}/{}?store=local,remote"_format(LocalCfg.BaseUri, Bucket, Key)}, + cpr::Response Result = cpr::Put(cpr::Url{fmt::format("{}/{}/{}?store=local,remote", LocalCfg.BaseUri, Bucket, Key)}, cpr::Body{(const char*)Buf.GetData(), Buf.GetSize()}, cpr::Header{{"Content-Type", "application/x-ue-cbpkg"}}); CHECK(Result.status_code == 201); @@ -1723,13 +1718,13 @@ TEST_CASE("zcache.policy") { cpr::Response Result = - cpr::Get(cpr::Url{"{}/{}/{}"_format(UpstreamCfg.BaseUri, Bucket, Key)}, cpr::Header{{"Accept", "application/x-ue-cbpkg"}}); + cpr::Get(cpr::Url{fmt::format("{}/{}/{}", UpstreamCfg.BaseUri, Bucket, Key)}, cpr::Header{{"Accept", "application/x-ue-cbpkg"}}); CHECK(Result.status_code == 200); } { cpr::Response Result = - cpr::Get(cpr::Url{"{}/{}/{}"_format(LocalCfg.BaseUri, Bucket, Key)}, cpr::Header{{"Accept", "application/x-ue-cbpkg"}}); + cpr::Get(cpr::Url{fmt::format("{}/{}/{}", LocalCfg.BaseUri, Bucket, Key)}, cpr::Header{{"Accept", "application/x-ue-cbpkg"}}); CHECK(Result.status_code == 200); } } @@ -1751,14 +1746,14 @@ TEST_CASE("zcache.policy") auto Buf = ToBuffer(Package); CHECK(Package.GetAttachments().size() != 0); - cpr::Response Result = cpr::Put(cpr::Url{"{}/{}/{}"_format(LocalCfg.BaseUri, Bucket, Key)}, + cpr::Response Result = cpr::Put(cpr::Url{fmt::format("{}/{}/{}", LocalCfg.BaseUri, Bucket, Key)}, cpr::Body{(const char*)Buf.GetData(), Buf.GetSize()}, cpr::Header{{"Content-Type", "application/x-ue-cbpkg"}}); CHECK(Result.status_code == 201); } { - cpr::Response Result = cpr::Get(cpr::Url{"{}/{}/{}?skip=attachments"_format(LocalCfg.BaseUri, Bucket, Key)}, + cpr::Response Result = cpr::Get(cpr::Url{fmt::format("{}/{}/{}?skip=attachments", LocalCfg.BaseUri, Bucket, Key)}, cpr::Header{{"Accept", "application/x-ue-cbpkg"}}); CHECK(Result.status_code == 200); @@ -1781,7 +1776,7 @@ TEST_CASE("zcache.policy") { cpr::Response Result = - cpr::Get(cpr::Url{"{}/{}/{}"_format(LocalCfg.BaseUri, Bucket, Key)}, cpr::Header{{"Accept", "application/x-ue-cbpkg"}}); + cpr::Get(cpr::Url{fmt::format("{}/{}/{}", LocalCfg.BaseUri, Bucket, Key)}, cpr::Header{{"Accept", "application/x-ue-cbpkg"}}); CHECK(Result.status_code == 200); zen::IoBuffer Body(zen::IoBuffer::Wrap, Result.text.data(), Result.text.size()); @@ -1814,14 +1809,14 @@ TEST_CASE("zcache.policy") auto Buf = ToBuffer(Package); CHECK(Package.GetAttachments().size() != 0); - cpr::Response Result = cpr::Put(cpr::Url{"{}/{}/{}"_format(UpstreamCfg.BaseUri, Bucket, Key)}, + cpr::Response Result = cpr::Put(cpr::Url{fmt::format("{}/{}/{}", UpstreamCfg.BaseUri, Bucket, Key)}, cpr::Body{(const char*)Buf.GetData(), Buf.GetSize()}, cpr::Header{{"Content-Type", "application/x-ue-cbpkg"}}); CHECK(Result.status_code == 201); } { - cpr::Response Result = cpr::Get(cpr::Url{"{}/{}/{}?skip=attachments"_format(LocalCfg.BaseUri, Bucket, Key)}, + cpr::Response Result = cpr::Get(cpr::Url{fmt::format("{}/{}/{}?skip=attachments", LocalCfg.BaseUri, Bucket, Key)}, cpr::Header{{"Accept", "application/x-ue-cbpkg"}}); CHECK(Result.status_code == 200); @@ -1844,7 +1839,7 @@ TEST_CASE("zcache.policy") { cpr::Response Result = - cpr::Get(cpr::Url{"{}/{}/{}"_format(LocalCfg.BaseUri, Bucket, Key)}, cpr::Header{{"Accept", "application/x-ue-cbpkg"}}); + cpr::Get(cpr::Url{fmt::format("{}/{}/{}", LocalCfg.BaseUri, Bucket, Key)}, cpr::Header{{"Accept", "application/x-ue-cbpkg"}}); CHECK(Result.status_code == 200); zen::IoBuffer Body(zen::IoBuffer::Wrap, Result.text.data(), Result.text.size()); @@ -1872,7 +1867,7 @@ TEST_CASE("zcache.policy") // Store package { - cpr::Response Result = cpr::Put(cpr::Url{"{}/{}/{}"_format(Cfg.BaseUri, Bucket, Key)}, + cpr::Response Result = cpr::Put(cpr::Url{fmt::format("{}/{}/{}", Cfg.BaseUri, Bucket, Key)}, cpr::Body{(const char*)Buf.GetData(), Buf.GetSize()}, cpr::Header{{"Content-Type", "application/x-ue-cbpkg"}}); CHECK(Result.status_code == 201); @@ -1880,7 +1875,7 @@ TEST_CASE("zcache.policy") // Get package { - cpr::Response Result = cpr::Get(cpr::Url{"{}/{}/{}?skip=data"_format(Cfg.BaseUri, Bucket, Key)}, + cpr::Response Result = cpr::Get(cpr::Url{fmt::format("{}/{}/{}?skip=data", Cfg.BaseUri, Bucket, Key)}, cpr::Header{{"Accept", "application/x-ue-cbpkg"}}); CHECK(IsHttpSuccessCode(Result.status_code)); CHECK(Result.text.size() == 0); @@ -1888,7 +1883,7 @@ TEST_CASE("zcache.policy") // Get record { - cpr::Response Result = cpr::Get(cpr::Url{"{}/{}/{}?skip=data"_format(Cfg.BaseUri, Bucket, Key)}, + cpr::Response Result = cpr::Get(cpr::Url{fmt::format("{}/{}/{}?skip=data", Cfg.BaseUri, Bucket, Key)}, cpr::Header{{"Accept", "application/x-ue-cbobject"}}); CHECK(IsHttpSuccessCode(Result.status_code)); CHECK(Result.text.size() == 0); @@ -1896,7 +1891,7 @@ TEST_CASE("zcache.policy") // Get payload { - cpr::Response Result = cpr::Get(cpr::Url{"{}/{}/{}/{}?skip=data"_format(Cfg.BaseUri, Bucket, Key, PayloadId)}, + cpr::Response Result = cpr::Get(cpr::Url{fmt::format("{}/{}/{}/{}?skip=data", Cfg.BaseUri, Bucket, Key, PayloadId)}, cpr::Header{{"Accept", "application/x-ue-comp"}}); CHECK(IsHttpSuccessCode(Result.status_code)); CHECK(Result.text.size() == 0); @@ -1916,7 +1911,7 @@ TEST_CASE("zcache.policy") // Store binary cache value { - cpr::Response Result = cpr::Put(cpr::Url{"{}/{}/{}"_format(Cfg.BaseUri, Bucket, Key)}, + cpr::Response Result = cpr::Put(cpr::Url{fmt::format("{}/{}/{}", Cfg.BaseUri, Bucket, Key)}, cpr::Body{(const char*)BinaryValue.GetData(), BinaryValue.GetSize()}, cpr::Header{{"Content-Type", "application/octet-stream"}}); CHECK(Result.status_code == 201); @@ -1924,7 +1919,7 @@ TEST_CASE("zcache.policy") // Get package { - cpr::Response Result = cpr::Get(cpr::Url{"{}/{}/{}?skip=data"_format(Cfg.BaseUri, Bucket, Key)}, + cpr::Response Result = cpr::Get(cpr::Url{fmt::format("{}/{}/{}?skip=data", Cfg.BaseUri, Bucket, Key)}, cpr::Header{{"Accept", "application/octet-stream"}}); CHECK(IsHttpSuccessCode(Result.status_code)); CHECK(Result.text.size() == 0); @@ -1981,7 +1976,7 @@ TEST_CASE("zcache.rpc") IoBuffer Payload = ToIoBuffer(CacheRecord); - cpr::Response Result = cpr::Put(cpr::Url{"{}/{}/{}{}"_format(BaseUri, CacheKey.Bucket, CacheKey.Hash, Query)}, + cpr::Response Result = cpr::Put(cpr::Url{fmt::format("{}/{}/{}{}", BaseUri, CacheKey.Bucket, CacheKey.Hash, Query)}, cpr::Body{(const char*)Payload.Data(), Payload.Size()}, cpr::Header{{"Content-Type", "application/x-ue-cbpkg"}}); @@ -2025,7 +2020,7 @@ TEST_CASE("zcache.rpc") BinaryWriter Body; Request.Save(Body); - cpr::Response Result = cpr::Post(cpr::Url{"{}/$rpc"_format(BaseUri)}, + cpr::Response Result = cpr::Post(cpr::Url{fmt::format("{}/$rpc", BaseUri)}, cpr::Header{{"Content-Type", "application/x-ue-cb"}, {"Accept", "application/x-ue-cbpkg"}}, cpr::Body{(const char*)Body.GetData(), Body.GetSize()}); @@ -2063,7 +2058,7 @@ TEST_CASE("zcache.rpc") { std::filesystem::path TestDir = TestEnv.CreateNewTestDir(); const uint16_t PortNumber = 13337; - const auto BaseUri = "http://localhost:{}/z$"_format(PortNumber); + const auto BaseUri = fmt::format("http://localhost:{}/z$", PortNumber); ZenServerInstance Inst(TestEnv); Inst.SetTestDir(TestDir); @@ -2095,7 +2090,7 @@ TEST_CASE("zcache.rpc") { std::filesystem::path TestDir = TestEnv.CreateNewTestDir(); const uint16_t PortNumber = 13337; - const auto BaseUri = "http://localhost:{}/z$"_format(PortNumber); + const auto BaseUri = fmt::format("http://localhost:{}/z$", PortNumber); ZenServerInstance Inst(TestEnv); Inst.SetTestDir(TestDir); @@ -2143,7 +2138,7 @@ TEST_CASE("zcache.rpc") { std::filesystem::path TestDir = TestEnv.CreateNewTestDir(); const uint16_t PortNumber = 13337; - const auto BaseUri = "http://localhost:{}/z$"_format(PortNumber); + const auto BaseUri = fmt::format("http://localhost:{}/z$", PortNumber); ZenServerInstance Inst(TestEnv); Inst.SetTestDir(TestDir); @@ -2261,7 +2256,7 @@ struct RemoteExecutionRequest void Prep() { - cpr::Response Response = cpr::Post(cpr::Url("{}/prep"_format(m_BaseUri)), cpr::Body((const char*)m_MemOut.Data(), m_MemOut.Size())); + cpr::Response Response = cpr::Post(cpr::Url(fmt::format("{}/prep", m_BaseUri)), cpr::Body((const char*)m_MemOut.Data(), m_MemOut.Size())); if (Response.status_code < 300) { @@ -2355,8 +2350,8 @@ private: std::string m_HostName; int m_PortNumber; std::filesystem::path m_TreePath; - const std::string m_BaseUri = "http://{}:{}/exec/jobs"_format(m_HostName, m_PortNumber); - const std::string m_CasUri = "http://{}:{}/cas"_format(m_HostName, m_PortNumber); + const std::string m_BaseUri = fmt::format("http://{}:{}/exec/jobs", m_HostName, m_PortNumber); + const std::string m_CasUri = fmt::format("http://{}:{}/cas", m_HostName, m_PortNumber); Visitor m_Visit{m_TreePath}; zen::BinaryWriter m_MemOut; }; @@ -2486,17 +2481,17 @@ TEST_CASE("http.basics") const std::string BaseUri = Instance.GetBaseUri(); { - cpr::Response r = cpr::Get(cpr::Url{"{}/testing/hello"_format(BaseUri)}); + cpr::Response r = cpr::Get(cpr::Url{fmt::format("{}/testing/hello", BaseUri)}); CHECK(IsHttpSuccessCode(r.status_code)); } { - cpr::Response r = cpr::Post(cpr::Url{"{}/testing/hello"_format(BaseUri)}); + cpr::Response r = cpr::Post(cpr::Url{fmt::format("{}/testing/hello", BaseUri)}); CHECK_EQ(r.status_code, 404); } { - cpr::Response r = cpr::Post(cpr::Url{"{}/testing/echo"_format(BaseUri)}, cpr::Body{"yoyoyoyo"}); + cpr::Response r = cpr::Post(cpr::Url{fmt::format("{}/testing/echo", BaseUri)}, cpr::Body{"yoyoyoyo"}); CHECK_EQ(r.status_code, 200); CHECK_EQ(r.text, "yoyoyoyo"); } diff --git a/zenserver/admin/admin.cpp b/zenserver/admin/admin.cpp index 01c35a1d8..676e9a830 100644 --- a/zenserver/admin/admin.cpp +++ b/zenserver/admin/admin.cpp @@ -16,7 +16,7 @@ HttpAdminService::HttpAdminService(GcScheduler& Scheduler) : m_GcScheduler(Sched m_Router.RegisterRoute( "health", - [this](HttpRouterRequest& Req) { + [](HttpRouterRequest& Req) { CbObjectWriter Obj; Obj.AddBool("ok", true); Req.ServerRequest().WriteResponse(HttpResponseCode::OK, Obj.Save()); @@ -64,7 +64,7 @@ HttpAdminService::HttpAdminService(GcScheduler& Scheduler) : m_GcScheduler(Sched m_Router.RegisterRoute( "", - [this](HttpRouterRequest& Req) { + [](HttpRouterRequest& Req) { CbObject Payload = Req.ServerRequest().ReadPayloadObject(); CbObjectWriter Obj; diff --git a/zenserver/cache/cachetracking.cpp b/zenserver/cache/cachetracking.cpp index ae132f37f..9119e3122 100644 --- a/zenserver/cache/cachetracking.cpp +++ b/zenserver/cache/cachetracking.cpp @@ -26,8 +26,6 @@ ZEN_THIRD_PARTY_INCLUDES_END namespace zen { -using namespace fmt::literals; - namespace rocksdb = ROCKSDB_NAMESPACE; static constinit auto Epoch = std::chrono::time_point<std::chrono::system_clock>{}; @@ -180,14 +178,14 @@ struct ZenCacheTracker::Impl } else { - throw std::runtime_error("column family iteration failed for '{}': '{}'"_format(RocksdbPath, Status.getState()).c_str()); + throw std::runtime_error(fmt::format("column family iteration failed for '{}': '{}'", RocksdbPath, Status.getState()).c_str()); } Status = rocksdb::DB::Open(Options, RocksdbPath, ColumnDescriptors, &m_RocksDbColumnHandles, &Db); if (!Status.ok()) { - throw std::runtime_error("database open failed for '{}': '{}'"_format(RocksdbPath, Status.getState()).c_str()); + throw std::runtime_error(fmt::format("database open failed for '{}': '{}'", RocksdbPath, Status.getState()).c_str()); } m_RocksDb.reset(Db); @@ -297,7 +295,6 @@ ZenCacheTracker::IterateSnapshots(std::function<void(uint64_t TimeStamp, CbObjec TEST_CASE("z$.tracker") { - using namespace fmt::literals; using namespace std::literals; const uint64_t t0 = GetCurrentCacheTimeStamp(); diff --git a/zenserver/cache/structuredcache.cpp b/zenserver/cache/structuredcache.cpp index 8639ed1c8..6078f892e 100644 --- a/zenserver/cache/structuredcache.cpp +++ b/zenserver/cache/structuredcache.cpp @@ -152,19 +152,16 @@ HttpStructuredCacheService::HandleRequest(HttpServerRequest& Request) void HttpStructuredCacheService::HandleCacheBucketRequest(HttpServerRequest& Request, std::string_view Bucket) { - ZEN_UNUSED(Request, Bucket); switch (Request.RequestVerb()) { - using enum HttpVerb; - - case kHead: - case kGet: + case HttpVerb::kHead: + case HttpVerb::kGet: { // Query stats } break; - case kDelete: + case HttpVerb::kDelete: // Drop bucket if (m_CacheStore.DropBucket(Bucket)) @@ -187,16 +184,14 @@ HttpStructuredCacheService::HandleCacheRecordRequest(HttpServerRequest& Request, { switch (Request.RequestVerb()) { - using enum HttpVerb; - - case kHead: - case kGet: + case HttpVerb::kHead: + case HttpVerb::kGet: { HandleGetCacheRecord(Request, Ref, Policy); } break; - case kPut: + case HttpVerb::kPut: HandlePutCacheRecord(Request, Ref, Policy); break; default: @@ -228,7 +223,7 @@ HttpStructuredCacheService::HandleGetCacheRecord(zen::HttpServerRequest& Request if (!SkipAttachments) { - CacheRecord.IterateAttachments([this, &Ref, &Package, &AttachmentCount, &ValidCount](CbFieldView AttachmentHash) { + CacheRecord.IterateAttachments([this, &Package, &AttachmentCount, &ValidCount](CbFieldView AttachmentHash) { if (IoBuffer Chunk = m_CidStore.FindChunkByCid(AttachmentHash.AsHash())) { Package.AddAttachment(CbAttachment(CompressedBuffer::FromCompressed(SharedBuffer(Chunk)))); @@ -588,15 +583,13 @@ HttpStructuredCacheService::HandleCachePayloadRequest(HttpServerRequest& Request { switch (Request.RequestVerb()) { - using enum HttpVerb; - - case kHead: - case kGet: + case HttpVerb::kHead: + case HttpVerb::kGet: { HandleGetCachePayload(Request, Ref, Policy); } break; - case kPut: + case HttpVerb::kPut: HandlePutCachePayload(Request, Ref, Policy); break; default: @@ -772,9 +765,7 @@ HttpStructuredCacheService::HandleRpcRequest(zen::HttpServerRequest& Request) { switch (Request.RequestVerb()) { - using enum HttpVerb; - - case kPost: + case HttpVerb::kPost: { const HttpContentType ContentType = Request.RequestContentType(); const HttpContentType AcceptType = Request.AcceptContentType(); @@ -817,8 +808,6 @@ HttpStructuredCacheService::HandleRpcGetCacheRecords(zen::HttpServerRequest& Req { ZEN_TRACE_CPU("Z$::RpcGetCacheRecords"); - using namespace fmt::literals; - CbPackage RpcResponse; CacheRecordPolicy Policy; CbObjectView Params = RpcRequest["Params"sv].AsObjectView(); @@ -906,7 +895,7 @@ HttpStructuredCacheService::HandleRpcGetCacheRecords(zen::HttpServerRequest& Req if (!UpstreamRequests.empty() && m_UpstreamCache) { const auto OnCacheRecordGetComplete = - [this, &CacheKeys, &CacheValues, &RpcResponse, PartialOnError, SkipAttachments](CacheRecordGetCompleteParams&& Params) { + [this, &CacheValues, &RpcResponse, PartialOnError, SkipAttachments](CacheRecordGetCompleteParams&& Params) { ZEN_ASSERT(Params.KeyIndex < CacheValues.size()); IoBuffer CacheValue; @@ -1015,8 +1004,6 @@ HttpStructuredCacheService::HandleRpcGetCachePayloads(zen::HttpServerRequest& Re { ZEN_TRACE_CPU("Z$::RpcGetCachePayloads"); - using namespace fmt::literals; - ZEN_ASSERT(RpcRequest["Method"sv].AsString() == "GetCachePayloads"sv); std::vector<CacheChunkRequest> ChunkRequests; @@ -1035,7 +1022,10 @@ HttpStructuredCacheService::HandleRpcGetCachePayloads(zen::HttpServerRequest& Re const uint64_t RawSize = RequestObject["RawSize"sv].AsUInt64(); const uint32_t ChunkPolicy = RequestObject["Policy"sv].AsUInt32(); - ChunkRequests.emplace_back(Key, ChunkId, PayloadId, RawOffset, RawSize, static_cast<CachePolicy>(ChunkPolicy)); + // Note we could use emplace_back here but [Apple] LLVM-12's C++ library + // can't infer a constructor like other platforms (or can't handle an + // initializer list like others do). + ChunkRequests.push_back({Key, ChunkId, PayloadId, RawOffset, RawSize, static_cast<CachePolicy>(ChunkPolicy)}); } if (ChunkRequests.empty()) @@ -1153,7 +1143,7 @@ HttpStructuredCacheService::HandleRpcGetCachePayloads(zen::HttpServerRequest& Re if (!UpstreamRequests.empty() && m_UpstreamCache) { - const auto OnCachePayloadGetComplete = [this, &ChunkRequests, &Chunks](CachePayloadGetCompleteParams&& Params) { + const auto OnCachePayloadGetComplete = [this, &Chunks](CachePayloadGetCompleteParams&& Params) { if (CompressedBuffer Compressed = CompressedBuffer::FromCompressed(SharedBuffer(Params.Payload))) { m_CidStore.AddChunk(Compressed); diff --git a/zenserver/cache/structuredcachestore.cpp b/zenserver/cache/structuredcachestore.cpp index e74becb3a..68b7e2a48 100644 --- a/zenserver/cache/structuredcachestore.cpp +++ b/zenserver/cache/structuredcachestore.cpp @@ -26,8 +26,6 @@ #endif #include <concepts> -#include <memory_resource> -#include <ranges> ZEN_THIRD_PARTY_INCLUDES_START #include <fmt/core.h> @@ -38,7 +36,6 @@ ZEN_THIRD_PARTY_INCLUDES_END namespace zen { -using namespace fmt::literals; namespace fs = std::filesystem; static CbObject @@ -1066,14 +1063,14 @@ ZenCacheDiskLayer::CacheBucket::PutStandaloneCacheValue(const IoHash& HashKey, c if (Ec) { - throw std::system_error(Ec, "Failed to open temporary file for put at '{}'"_format(m_BucketDir)); + throw std::system_error(Ec, fmt::format("Failed to open temporary file for put at '{}'", m_BucketDir)); } DataFile.WriteAll(Value.Value, Ec); if (Ec) { - throw std::system_error(Ec, "Failed to write payload ({} bytes) to file"_format(NiceBytes(Value.Value.Size()))); + throw std::system_error(Ec, fmt::format("Failed to write payload ({} bytes) to file", NiceBytes(Value.Value.Size()))); } // Move file into place (atomically) @@ -1113,7 +1110,7 @@ ZenCacheDiskLayer::CacheBucket::PutStandaloneCacheValue(const IoHash& HashKey, c if (Ec) { - throw std::system_error(Ec, "Failed to finalize file '{}'"_format(DataFilePath.ToUtf8())); + throw std::system_error(Ec, fmt::format("Failed to finalize file '{}'", DataFilePath.ToUtf8())); } } @@ -1396,7 +1393,6 @@ ZenCacheDiskLayer::TotalSize() const #if ZEN_WITH_TESTS using namespace std::literals; -using namespace fmt::literals; namespace testutils { IoHash CreateKey(size_t KeyValue) { return IoHash::HashBuffer(&KeyValue, sizeof(size_t)); } @@ -1483,7 +1479,7 @@ TEST_CASE("z$.size") for (size_t Key = 0; Key < Count; ++Key) { const size_t Bucket = Key % 4; - Zcs.Put("test_bucket-{}"_format(Bucket), IoHash::HashBuffer(&Key, sizeof(uint32_t)), {.Value = Buffer}); + Zcs.Put(fmt::format("test_bucket-{}", Bucket), IoHash::HashBuffer(&Key, sizeof(uint32_t)), {.Value = Buffer}); } CacheSize = Zcs.StorageSize(); @@ -1501,7 +1497,7 @@ TEST_CASE("z$.size") for (size_t Bucket = 0; Bucket < 4; ++Bucket) { - Zcs.DropBucket("test_bucket-{}"_format(Bucket)); + Zcs.DropBucket(fmt::format("test_bucket-{}", Bucket)); } CHECK_EQ(0, Zcs.StorageSize().DiskSize); } @@ -1526,7 +1522,7 @@ TEST_CASE("z$.size") for (size_t Key = 0; Key < Count; ++Key) { const size_t Bucket = Key % 4; - Zcs.Put("test_bucket-{}"_format(Bucket), IoHash::HashBuffer(&Key, sizeof(uint32_t)), {.Value = Buffer}); + Zcs.Put(fmt::format("test_bucket-{}", Bucket), IoHash::HashBuffer(&Key, sizeof(uint32_t)), {.Value = Buffer}); } CacheSize = Zcs.StorageSize(); @@ -1544,7 +1540,7 @@ TEST_CASE("z$.size") for (size_t Bucket = 0; Bucket < 4; ++Bucket) { - Zcs.DropBucket("test_bucket-{}"_format(Bucket)); + Zcs.DropBucket(fmt::format("test_bucket-{}", Bucket)); } CHECK_EQ(0, Zcs.StorageSize().DiskSize); } @@ -1585,7 +1581,7 @@ TEST_CASE("z$.gc") for (size_t Idx = 0; auto& Cid : Cids) { - Record.AddBinaryAttachment("attachment-{}"_format(Idx++), Cid); + Record.AddBinaryAttachment(fmt::format("attachment-{}", Idx++), Cid); } IoBuffer Buffer = Record.Save().GetBuffer().AsIoBuffer(); diff --git a/zenserver/compute/apply.cpp b/zenserver/compute/apply.cpp index d483fd4f7..95902a752 100644 --- a/zenserver/compute/apply.cpp +++ b/zenserver/compute/apply.cpp @@ -61,8 +61,6 @@ BasicFunctionJob::~BasicFunctionJob() bool BasicFunctionJob::SpawnJob(std::filesystem::path ExePath, std::wstring CommandLine) { - using namespace fmt::literals; - STARTUPINFOEX StartupInfo = {sizeof(STARTUPINFOEX)}; PROCESS_INFORMATION ProcessInfo{}; @@ -82,7 +80,7 @@ BasicFunctionJob::SpawnJob(std::filesystem::path ExePath, std::wstring CommandLi if (!Created) { - throw std::system_error(::GetLastError(), std::system_category(), "Failed to create process '{}'"_format(ExePath).c_str()); + throw std::system_error(::GetLastError(), std::system_category(), fmt::format("Failed to create process '{}'", ExePath).c_str()); } m_ProcessId = ProcessInfo.dwProcessId; @@ -714,7 +712,6 @@ CbPackage HttpFunctionService::ExecAction(const WorkerDesc& Worker, CbObject Action) { using namespace std::literals; - using namespace fmt::literals; std::filesystem::path SandboxPath = CreateNewSandbox(); @@ -735,12 +732,12 @@ HttpFunctionService::ExecAction(const WorkerDesc& Worker, CbObject Action) if (!DataBuffer) { - throw std::runtime_error("worker CAS chunk '{}' missing"_format(ChunkHash)); + throw std::runtime_error(fmt::format("worker CAS chunk '{}' missing", ChunkHash)); } if (DataBuffer.Size() != Size) { - throw std::runtime_error("worker CAS chunk '{}' size: {}, action spec expected {}"_format(ChunkHash, DataBuffer.Size(), Size)); + throw std::runtime_error(fmt::format("worker CAS chunk '{}' size: {}, action spec expected {}", ChunkHash, DataBuffer.Size(), Size)); } zen::WriteFile(FilePath, DataBuffer); @@ -766,12 +763,12 @@ HttpFunctionService::ExecAction(const WorkerDesc& Worker, CbObject Action) if (!DataBuffer) { - throw std::runtime_error("worker CAS chunk '{}' missing"_format(ChunkHash)); + throw std::runtime_error(fmt::format("worker CAS chunk '{}' missing", ChunkHash)); } if (DataBuffer.Size() != Size) { - throw std::runtime_error("worker CAS chunk '{}' size: {}, action spec expected {}"_format(ChunkHash, DataBuffer.Size(), Size)); + throw std::runtime_error(fmt::format("worker CAS chunk '{}' size: {}, action spec expected {}", ChunkHash, DataBuffer.Size(), Size)); } zen::WriteFile(FilePath, DataBuffer); @@ -790,7 +787,7 @@ HttpFunctionService::ExecAction(const WorkerDesc& Worker, CbObject Action) if (!DataBuffer) { - throw std::runtime_error("input CID chunk '{}' missing"_format(Cid)); + throw std::runtime_error(fmt::format("input CID chunk '{}' missing", Cid)); } zen::WriteFile(FilePath, DataBuffer); @@ -942,11 +939,10 @@ HttpFunctionService::ExecActionUpstream(const WorkerDesc& Worker, CbObject Actio HttpResponseCode HttpFunctionService::ExecActionUpstreamResult(const IoHash& WorkerId, const IoHash& ActionId, CbPackage& Package) { - using namespace fmt::literals; auto Status = m_UpstreamApply->GetStatus(WorkerId, ActionId); if (!Status.Success) { - // throw std::runtime_error("Action {}/{} not found"_format(WorkerId.ToHexString(), ActionId.ToHexString()).c_str()); + // throw std::runtime_error(fmt::format("Action {}/{} not found", WorkerId.ToHexString(), ActionId.ToHexString()).c_str()); return HttpResponseCode::NotFound; } diff --git a/zenserver/config.cpp b/zenserver/config.cpp index 722bc3b97..9fd4bfa69 100644 --- a/zenserver/config.cpp +++ b/zenserver/config.cpp @@ -394,8 +394,6 @@ ParseCliOptions(int argc, char* argv[], ZenServerOptions& ServerOptions) void ParseConfigFile(const std::filesystem::path& Path, ZenServerOptions& ServerOptions) { - using namespace fmt::literals; - zen::IoBuffer LuaScript = zen::IoBufferBuilder::MakeFromFile(Path); if (LuaScript) @@ -433,14 +431,14 @@ ParseConfigFile(const std::filesystem::path& Path, ZenServerOptions& ServerOptio std::string ErrorString = sol::to_string(config.status()); - throw std::runtime_error("{} error: {}"_format(ErrorString, err.what())); + throw std::runtime_error(fmt::format("{} error: {}", ErrorString, err.what())); } config(); } catch (std::exception& e) { - throw std::runtime_error("failed to load config script ('{}'): {}"_format(Path, e.what()).c_str()); + throw std::runtime_error(fmt::format("failed to load config script ('{}'): {}", Path, e.what()).c_str()); } if (sol::optional<sol::table> ServerConfig = lua["server"]) diff --git a/zenserver/diag/diagsvcs.cpp b/zenserver/diag/diagsvcs.cpp index eed23dff2..ef2baa1b4 100644 --- a/zenserver/diag/diagsvcs.cpp +++ b/zenserver/diag/diagsvcs.cpp @@ -44,7 +44,7 @@ HttpHealthService::HttpHealthService() { m_Router.RegisterRoute( "", - [this](HttpRouterRequest& RoutedReq) { + [](HttpRouterRequest& RoutedReq) { HttpServerRequest& HttpReq = RoutedReq.ServerRequest(); HttpReq.WriteResponse(HttpResponseCode::OK, HttpContentType::kText, u8"OK!"sv); }, diff --git a/zenserver/projectstore.cpp b/zenserver/projectstore.cpp index 4f9897e07..42d785126 100644 --- a/zenserver/projectstore.cpp +++ b/zenserver/projectstore.cpp @@ -42,8 +42,6 @@ ZEN_THIRD_PARTY_INCLUDES_END namespace zen { -using namespace fmt::literals; - #if USE_ROCKSDB namespace rocksdb = ROCKSDB_NAMESPACE; #endif @@ -154,14 +152,14 @@ struct ProjectStore::OplogStorage : public RefCounted } else { - throw std::runtime_error("column family iteration failed for '{}': '{}'"_format(RocksdbPath, Status.getState()).c_str()); + throw std::runtime_error(fmt::format("column family iteration failed for '{}': '{}'", RocksdbPath, Status.getState()).c_str()); } Status = rocksdb::DB::Open(Options, RocksdbPath, ColumnDescriptors, &m_RocksDbColumnHandles, &Db); if (!Status.ok()) { - throw std::runtime_error("database open failed for '{}': '{}'"_format(RocksdbPath, Status.getState()).c_str()); + throw std::runtime_error(fmt::format("database open failed for '{}': '{}'", RocksdbPath, Status.getState()).c_str()); } m_RocksDb.reset(Db); @@ -1560,7 +1558,7 @@ HttpProjectService::HttpProjectService(CidStore& Store, ProjectStore* Projects) if (!legacy::TryLoadCbPackage(Package, Payload, &UniqueBuffer::Alloc, &Resolver)) { std::filesystem::path BadPackagePath = - Oplog.TempPath() / "bad_packages" / "session{}_request{}"_format(HttpReq.SessionId(), HttpReq.RequestId()); + Oplog.TempPath() / "bad_packages" / fmt::format("session{}_request{}", HttpReq.SessionId(), HttpReq.RequestId()); ZEN_ERROR("Received malformed package! Saving payload to '{}'", BadPackagePath); @@ -1600,7 +1598,7 @@ HttpProjectService::HttpProjectService(CidStore& Store, ProjectStore* Projects) m_Router.RegisterRoute( "{project}/oplog/{log}/{op}", - [this](HttpRouterRequest& Req) { + [](HttpRouterRequest& Req) { HttpServerRequest& HttpReq = Req.ServerRequest(); // TODO: look up op and respond with the payload! @@ -1609,8 +1607,6 @@ HttpProjectService::HttpProjectService(CidStore& Store, ProjectStore* Projects) }, HttpVerb::kGet); - using namespace fmt::literals; - m_Router.RegisterRoute( "{project}/oplog/{log}", [this](HttpRouterRequest& Req) { @@ -1623,7 +1619,7 @@ HttpProjectService::HttpProjectService(CidStore& Store, ProjectStore* Projects) { return Req.ServerRequest().WriteResponse(HttpResponseCode::NotFound, HttpContentType::kText, - "project {} not found"_format(ProjectId)); + fmt::format("project {} not found", ProjectId)); } ProjectStore::Project& Prj = *ProjectIt; @@ -1638,7 +1634,7 @@ HttpProjectService::HttpProjectService(CidStore& Store, ProjectStore* Projects) { return Req.ServerRequest().WriteResponse(HttpResponseCode::NotFound, HttpContentType::kText, - "oplog {} not found in project {}"_format(OplogId, ProjectId)); + fmt::format("oplog {} not found in project {}", OplogId, ProjectId)); } ProjectStore::Oplog& Log = *OplogIt; @@ -1777,7 +1773,7 @@ HttpProjectService::HttpProjectService(CidStore& Store, ProjectStore* Projects) { return Req.ServerRequest().WriteResponse(HttpResponseCode::NotFound, HttpContentType::kText, - "project {} not found"_format(ProjectId)); + fmt::format("project {} not found", ProjectId)); } const ProjectStore::Project& Prj = *ProjectIt; @@ -1801,7 +1797,7 @@ HttpProjectService::HttpProjectService(CidStore& Store, ProjectStore* Projects) { return Req.ServerRequest().WriteResponse(HttpResponseCode::NotFound, HttpContentType::kText, - "project {} not found"_format(ProjectId)); + fmt::format("project {} not found", ProjectId)); } m_ProjectStore->DeleteProject(ProjectId); @@ -2142,7 +2138,6 @@ LocalProjectService::~LocalProjectService() TEST_CASE("prj.store") { - using namespace fmt::literals; using namespace std::literals; ScopedTemporaryDirectory TempDir; diff --git a/zenserver/testing/httptest.cpp b/zenserver/testing/httptest.cpp index 924546762..230d5d6c5 100644 --- a/zenserver/testing/httptest.cpp +++ b/zenserver/testing/httptest.cpp @@ -8,51 +8,49 @@ namespace zen { -using namespace fmt::literals; - HttpTestingService::HttpTestingService() { m_Router.RegisterRoute( "hello", - [this](HttpRouterRequest& Req) { Req.ServerRequest().WriteResponse(HttpResponseCode::OK); }, + [](HttpRouterRequest& Req) { Req.ServerRequest().WriteResponse(HttpResponseCode::OK); }, HttpVerb::kGet); m_Router.RegisterRoute( "hello_slow", - [this](HttpRouterRequest& Req) { - Req.ServerRequest().WriteResponseAsync([this](HttpServerRequest& Request) { + [](HttpRouterRequest& Req) { + Req.ServerRequest().WriteResponseAsync([](HttpServerRequest& Request) { Stopwatch Timer; Sleep(1000); Request.WriteResponse(HttpResponseCode::OK, HttpContentType::kText, - "hello, took me {}"_format(NiceTimeSpanMs(Timer.GetElapsedTimeMs()))); + fmt::format("hello, took me {}", NiceTimeSpanMs(Timer.GetElapsedTimeMs()))); }); }, HttpVerb::kGet); m_Router.RegisterRoute( "hello_veryslow", - [this](HttpRouterRequest& Req) { - Req.ServerRequest().WriteResponseAsync([this](HttpServerRequest& Request) { + [](HttpRouterRequest& Req) { + Req.ServerRequest().WriteResponseAsync([](HttpServerRequest& Request) { Stopwatch Timer; Sleep(60000); Request.WriteResponse(HttpResponseCode::OK, HttpContentType::kText, - "hello, took me {}"_format(NiceTimeSpanMs(Timer.GetElapsedTimeMs()))); + fmt::format("hello, took me {}", NiceTimeSpanMs(Timer.GetElapsedTimeMs()))); }); }, HttpVerb::kGet); m_Router.RegisterRoute( "hello_throw", - [this](HttpRouterRequest& Req) { - Req.ServerRequest().WriteResponseAsync([this](HttpServerRequest&) { throw std::runtime_error("intentional error"); }); + [](HttpRouterRequest& Req) { + Req.ServerRequest().WriteResponseAsync([](HttpServerRequest&) { throw std::runtime_error("intentional error"); }); }, HttpVerb::kGet); m_Router.RegisterRoute( "hello_noresponse", - [this](HttpRouterRequest& Req) { Req.ServerRequest().WriteResponseAsync([this](HttpServerRequest&) {}); }, + [](HttpRouterRequest& Req) { Req.ServerRequest().WriteResponseAsync([](HttpServerRequest&) {}); }, HttpVerb::kGet); m_Router.RegisterRoute( @@ -84,7 +82,7 @@ HttpTestingService::HttpTestingService() m_Router.RegisterRoute( "echo", - [this](HttpRouterRequest& Req) { + [](HttpRouterRequest& Req) { IoBuffer Body = Req.ServerRequest().ReadPayload(); Req.ServerRequest().WriteResponse(HttpResponseCode::OK, HttpContentType::kBinary, Body); }, @@ -92,7 +90,7 @@ HttpTestingService::HttpTestingService() m_Router.RegisterRoute( "package", - [this](HttpRouterRequest& Req) { + [](HttpRouterRequest& Req) { CbPackage Pkg = Req.ServerRequest().ReadPayloadPackage(); Req.ServerRequest().WriteResponse(HttpResponseCode::OK, Pkg); }, diff --git a/zenserver/testing/launch.cpp b/zenserver/testing/launch.cpp index 706594b10..f315ec1b4 100644 --- a/zenserver/testing/launch.cpp +++ b/zenserver/testing/launch.cpp @@ -55,8 +55,6 @@ BasicJob::~BasicJob() bool BasicJob::SpawnJob(std::filesystem::path ExePath, std::wstring CommandLine) { - using namespace fmt::literals; - STARTUPINFOEX StartupInfo = {sizeof(STARTUPINFOEX)}; PROCESS_INFORMATION ProcessInfo{}; @@ -76,7 +74,7 @@ BasicJob::SpawnJob(std::filesystem::path ExePath, std::wstring CommandLine) if (!Created) { - throw std::system_error(::GetLastError(), std::system_category(), "Failed to create process '{}'"_format(ExePath).c_str()); + throw std::system_error(::GetLastError(), std::system_category(), fmt::format("Failed to create process '{}'", ExePath).c_str()); } m_ProcessId = ProcessInfo.dwProcessId; diff --git a/zenserver/upstream/jupiter.cpp b/zenserver/upstream/jupiter.cpp index ffb9b1cbf..c952d8e10 100644 --- a/zenserver/upstream/jupiter.cpp +++ b/zenserver/upstream/jupiter.cpp @@ -25,7 +25,6 @@ ZEN_THIRD_PARTY_INCLUDES_END #include <json11.hpp> using namespace std::literals; -using namespace fmt::literals; namespace zen { diff --git a/zenserver/upstream/upstreamapply.cpp b/zenserver/upstream/upstreamapply.cpp index f8a8c3e62..fe7f7d9c8 100644 --- a/zenserver/upstream/upstreamapply.cpp +++ b/zenserver/upstream/upstreamapply.cpp @@ -53,10 +53,9 @@ namespace detail { , m_CasStore(CasStore) , m_CidStore(CidStore) { - using namespace fmt::literals; - m_DisplayName = "Horde - '{}'"_format(Options.ServiceUrl); + m_DisplayName = fmt::format("Horde - '{}'", Options.ServiceUrl); m_Client = new CloudCacheClient(Options); - m_ChannelId = "zen-{}"_format(zen::GetSessionIdString()); + m_ChannelId = fmt::format("zen-{}", zen::GetSessionIdString()); } virtual ~HordeUpstreamApplyEndpoint() = default; @@ -442,14 +441,13 @@ namespace detail { if (Outcome != ComputeTaskOutcome::Success) { - using namespace fmt::literals; const std::string_view Detail = TaskStatus["d"sv].AsString(); if (!Detail.empty()) { return {.Error{.ErrorCode = -1, - .Reason = "Task {}: {}"_format(ComputeTaskOutcomeToString(Outcome), std::string(Detail))}}; + .Reason = fmt::format("Task {}: {}", ComputeTaskOutcomeToString(Outcome), std::string(Detail))}}; } - return {.Error{.ErrorCode = -1, .Reason = "Task {}"_format(ComputeTaskOutcomeToString(Outcome))}}; + return {.Error{.ErrorCode = -1, .Reason = fmt::format("Task {}", ComputeTaskOutcomeToString(Outcome))}}; } const IoHash TaskId = TaskStatus["h"sv].AsObjectAttachment(); @@ -713,8 +711,6 @@ namespace detail { [[nodiscard]] bool ProcessApplyKey(const UpstreamApplyRecord& ApplyRecord, UpstreamData& Data) { - using namespace fmt::literals; - std::string ExecutablePath; std::map<std::string, std::string> Environment; std::set<std::filesystem::path> InputFiles; @@ -749,7 +745,7 @@ namespace detail { for (auto& It : ApplyRecord.WorkerDescriptor["dirs"sv]) { std::string_view Directory = It.AsString(); - std::string DummyFile = "{}/.zen_empty_file"_format(Directory); + std::string DummyFile = fmt::format("{}/.zen_empty_file", Directory); InputFiles.insert(DummyFile); Data.Blobs[EmptyBufferId] = EmptyBuffer; InputFileHashes[DummyFile] = EmptyBufferId; @@ -816,7 +812,6 @@ namespace detail { Data.Objects[SandboxHash] = std::move(Sandbox); { - using namespace fmt::literals; std::string_view HostPlatform = ApplyRecord.WorkerDescriptor["host"sv].AsString(); if (HostPlatform.empty()) { @@ -829,7 +824,7 @@ namespace detail { bool Exclusive = ApplyRecord.WorkerDescriptor["exclusive"sv].AsBool(); // TODO: Remove override when Horde accepts the UE style Host Platforms (Win64, Linux, Mac) - std::string Condition = "Platform == '{}'"_format(HostPlatform); + std::string Condition = fmt::format("Platform == '{}'", HostPlatform); if (HostPlatform == "Win64") { Condition += " && Pool == 'Win-RemoteExec'"; diff --git a/zenserver/upstream/upstreamcache.cpp b/zenserver/upstream/upstreamcache.cpp index 2ed74cdd4..1a35f7283 100644 --- a/zenserver/upstream/upstreamcache.cpp +++ b/zenserver/upstream/upstreamcache.cpp @@ -48,7 +48,7 @@ namespace detail { virtual ~JupiterUpstreamEndpoint() = default; - virtual const UpstreamEndpointInfo& GetEndpointInfo() const { return m_Info; } + virtual const UpstreamEndpointInfo& GetEndpointInfo() const override { return m_Info; } virtual UpstreamEndpointHealth Initialize() override { return CheckHealth(); } @@ -270,8 +270,6 @@ namespace detail { { ZEN_TRACE_CPU("Upstream::Horde::PutCacheRecord"); - using namespace fmt::literals; - ZEN_ASSERT(CacheRecord.PayloadIds.size() == Payloads.size()); const int32_t MaxAttempts = 3; @@ -313,7 +311,7 @@ namespace detail { if (It == std::end(CacheRecord.PayloadIds)) { - OutReason = "payload '{}' MISSING from local cache"_format(PayloadId); + OutReason = fmt::format("payload '{}' MISSING from local cache", PayloadId); return false; } @@ -329,7 +327,7 @@ namespace detail { if (!BlobResult.Success) { - OutReason = "upload payload '{}' FAILED, reason '{}'"_format(PayloadId, BlobResult.Reason); + OutReason = fmt::format("upload payload '{}' FAILED, reason '{}'", PayloadId, BlobResult.Reason); return false; } @@ -350,7 +348,7 @@ namespace detail { if (!RefResult.Success) { - return {.Reason = "upload cache record '{}/{}' FAILED, reason '{}'"_format(CacheRecord.Key.Bucket, + return {.Reason = fmt::format("upload cache record '{}/{}' FAILED, reason '{}'", CacheRecord.Key.Bucket, CacheRecord.Key.Hash, RefResult.Reason), .Success = false}; @@ -371,7 +369,7 @@ namespace detail { if (!FinalizeResult.Success) { - return {.Reason = "finalize cache record '{}/{}' FAILED, reason '{}'"_format(CacheRecord.Key.Bucket, + return {.Reason = fmt::format("finalize cache record '{}/{}' FAILED, reason '{}'", CacheRecord.Key.Bucket, CacheRecord.Key.Hash, FinalizeResult.Reason), .Success = false}; @@ -389,7 +387,7 @@ namespace detail { if (!FinalizeResult.Success) { - return {.Reason = "finalize '{}/{}' FAILED, reason '{}'"_format(CacheRecord.Key.Bucket, + return {.Reason = fmt::format("finalize '{}/{}' FAILED, reason '{}'", CacheRecord.Key.Bucket, CacheRecord.Key.Hash, FinalizeResult.Reason), .Success = false}; @@ -403,7 +401,7 @@ namespace detail { Sb << MissingHash.ToHexString() << ","; } - return {.Reason = "finalize '{}/{}' FAILED, still needs payload(s) '{}'"_format(CacheRecord.Key.Bucket, + return {.Reason = fmt::format("finalize '{}/{}' FAILED, still needs payload(s) '{}'", CacheRecord.Key.Bucket, CacheRecord.Key.Hash, Sb.ToString()), .Success = false}; @@ -476,12 +474,10 @@ namespace detail { ~ZenUpstreamEndpoint() = default; - virtual const UpstreamEndpointInfo& GetEndpointInfo() const { return m_Info; } + virtual const UpstreamEndpointInfo& GetEndpointInfo() const override { return m_Info; } virtual UpstreamEndpointHealth Initialize() override { - using namespace fmt::literals; - const ZenEndpoint& Ep = GetEndpoint(); if (Ep.Ok) { @@ -500,8 +496,6 @@ namespace detail { virtual UpstreamEndpointHealth CheckHealth() override { - using namespace fmt::literals; - try { if (m_Client.IsNull()) diff --git a/zenserver/zenserver.cpp b/zenserver/zenserver.cpp index 6e5d2fe93..40d40e908 100644 --- a/zenserver/zenserver.cpp +++ b/zenserver/zenserver.cpp @@ -114,7 +114,6 @@ ZEN_THIRD_PARTY_INCLUDES_END namespace zen { using namespace std::literals; -using namespace fmt::literals; namespace utils { asio::error_code ResolveHostname(asio::io_context& Ctx, @@ -139,7 +138,7 @@ namespace utils { { for (const asio::ip::tcp::endpoint Ep : Endpoints) { - OutEndpoints.push_back("http://{}:{}"_format(Ep.address().to_string(), Ep.port())); + OutEndpoints.push_back(fmt::format("http://{}:{}", Ep.address().to_string(), Ep.port())); } } @@ -152,8 +151,6 @@ class ZenServer : public IHttpStatusProvider public: void Initialize(const ZenServerOptions& ServerOptions, ZenServerState::ZenServerEntry* ServerEntry) { - using namespace fmt::literals; - m_ServerEntry = ServerEntry; m_DebugOptionForcedCrash = ServerOptions.ShouldCrash; const int ParentPid = ServerOptions.OwnerPid; @@ -180,11 +177,11 @@ public: // Initialize/check mutex based on base port - std::string MutexName = "zen_{}"_format(ServerOptions.BasePort); + std::string MutexName = fmt::format("zen_{}", ServerOptions.BasePort); if (zen::NamedMutex::Exists(MutexName) || ((m_ServerMutex.Create(MutexName) == false))) { - throw std::runtime_error("Failed to create mutex '{}' - is another instance already running?"_format(MutexName).c_str()); + throw std::runtime_error(fmt::format("Failed to create mutex '{}' - is another instance already running?", MutexName).c_str()); } InitializeState(ServerOptions); @@ -585,7 +582,7 @@ ZenServer::InitializeState(const ZenServerOptions& ServerOptions) else { WipeState = true; - WipeReason = "No manifest present at '{}'"_format(ManifestPath); + WipeReason = fmt::format("No manifest present at '{}'", ManifestPath); } } else @@ -598,7 +595,7 @@ ZenServer::InitializeState(const ZenServerOptions& ServerOptions) ZEN_ERROR("Manifest validation failed: {}, state will be wiped", ValidationResult); WipeState = true; - WipeReason = "Validation of manifest at '{}' failed: {}"_format(ManifestPath, ValidationResult); + WipeReason = fmt::format("Validation of manifest at '{}' failed: {}", ManifestPath, ValidationResult); } else { @@ -609,7 +606,7 @@ ZenServer::InitializeState(const ZenServerOptions& ServerOptions) if (ManifestVersion != ZEN_CFG_SCHEMA_VERSION) { WipeState = true; - WipeReason = "Manifest schema version: {}, differs from required: {}"_format(ManifestVersion, ZEN_CFG_SCHEMA_VERSION); + WipeReason = fmt::format("Manifest schema version: {}, differs from required: {}", ManifestVersion, ZEN_CFG_SCHEMA_VERSION); } } } diff --git a/zenstore/basicfile.cpp b/zenstore/basicfile.cpp index 80d9a2204..dcd9a8575 100644 --- a/zenstore/basicfile.cpp +++ b/zenstore/basicfile.cpp @@ -15,6 +15,7 @@ # include <fcntl.h> # include <sys/file.h> # include <sys/stat.h> +# include <unistd.h> #endif #include <fmt/format.h> @@ -22,8 +23,6 @@ namespace zen { -using namespace fmt::literals; - BasicFile::~BasicFile() { Close(); @@ -37,7 +36,7 @@ BasicFile::Open(std::filesystem::path FileName, bool IsCreate) if (Ec) { - throw std::system_error(Ec, "failed to open file '{}'"_format(FileName)); + throw std::system_error(Ec, fmt::format("failed to open file '{}'", FileName)); } } @@ -132,7 +131,7 @@ BasicFile::Read(void* Data, uint64_t BytesToRead, uint64_t FileOffset) if (!Success) { - ThrowLastError("Failed to read from file '{}'"_format(zen::PathFromHandle(m_FileHandle))); + ThrowLastError(fmt::format("Failed to read from file '{}'", zen::PathFromHandle(m_FileHandle))); } BytesToRead -= NumberOfBytesToRead; @@ -238,7 +237,7 @@ BasicFile::Write(const void* Data, uint64_t Size, uint64_t Offset) if (Ec) { - throw std::system_error(Ec, "Failed to write to file '{}'"_format(zen::PathFromHandle(m_FileHandle))); + throw std::system_error(Ec, fmt::format("Failed to write to file '{}'", zen::PathFromHandle(m_FileHandle))); } } @@ -334,11 +333,9 @@ LockFile::LockFile() LockFile::~LockFile() { -#if ZEN_PLATFORM_LINUX +#if ZEN_PLATFORM_LINUX || ZEN_PLATFORM_MAC int Fd = int(intptr_t(m_FileHandle)); flock(Fd, LOCK_UN | LOCK_NB); -#elif ZEN_PLATFORM_MAC -# error check flock() support #endif } @@ -368,7 +365,7 @@ LockFile::Create(std::filesystem::path FileName, CbObject Payload, std::error_co return; } -#elif ZEN_PLATFORM_LINUX +#elif ZEN_PLATFORM_LINUX || ZEN_PLATFORM_MAC int Fd = open(FileName.c_str(), O_RDWR | O_CREAT, 0666); if (Fd < 0) { @@ -385,8 +382,6 @@ LockFile::Create(std::filesystem::path FileName, CbObject Payload, std::error_co } void* FileHandle = (void*)uintptr_t(Fd); -#else -# error check flock() support #endif m_FileHandle = FileHandle; diff --git a/zenstore/cas.cpp b/zenstore/cas.cpp index 1fd01ff0c..7b58111db 100644 --- a/zenstore/cas.cpp +++ b/zenstore/cas.cpp @@ -201,7 +201,7 @@ CasImpl::OpenOrCreateManifest() } else { - ZEN_ERROR("Store manifest validation failed: {:#x}, will generate new manifest to recover", ValidationResult); + ZEN_ERROR("Store manifest validation failed: {:#x}, will generate new manifest to recover", uint32_t(ValidationResult)); } if (ManifestIsOk) diff --git a/zenstore/caslog.cpp b/zenstore/caslog.cpp index dc4891e9f..055e3feda 100644 --- a/zenstore/caslog.cpp +++ b/zenstore/caslog.cpp @@ -24,8 +24,6 @@ namespace zen { -using namespace fmt::literals; - uint32_t CasLogFile::FileHeader::ComputeChecksum() { @@ -50,7 +48,7 @@ CasLogFile::Open(std::filesystem::path FileName, size_t RecordSize, bool IsCreat if (Ec) { - throw std::system_error(Ec, "Failed to open log file '{}'"_format(FileName)); + throw std::system_error(Ec, fmt::format("Failed to open log file '{}'", FileName)); } uint64_t AppendOffset = 0; @@ -76,7 +74,7 @@ CasLogFile::Open(std::filesystem::path FileName, size_t RecordSize, bool IsCreat if ((0 != memcmp(Header.Magic, FileHeader::MagicSequence, sizeof Header.Magic)) || (Header.Checksum != Header.ComputeChecksum())) { - throw std::runtime_error("Mangled log header (invalid header magic) in '{}'"_format(FileName)); + throw std::runtime_error(fmt::format("Mangled log header (invalid header magic) in '{}'", FileName)); } AppendOffset = m_File.FileSize(); @@ -153,7 +151,7 @@ CasLogFile::Append(const void* DataPointer, uint64_t DataSize) if (Ec) { - throw std::system_error(Ec, "Failed to write to log file '{}'"_format(PathFromHandle(m_File.Handle()))); + throw std::system_error(Ec, fmt::format("Failed to write to log file '{}'", PathFromHandle(m_File.Handle()))); } } diff --git a/zenstore/compactcas.cpp b/zenstore/compactcas.cpp index aa60ec37b..3bf0c70df 100644 --- a/zenstore/compactcas.cpp +++ b/zenstore/compactcas.cpp @@ -31,8 +31,6 @@ namespace zen { -using namespace fmt::literals; - CasContainerStrategy::CasContainerStrategy(const CasStoreConfiguration& Config, CasGc& Gc) : GcStorage(Gc) , m_Config(Config) diff --git a/zenstore/compactcas.h b/zenstore/compactcas.h index 974f45a0c..c039feec9 100644 --- a/zenstore/compactcas.h +++ b/zenstore/compactcas.h @@ -14,14 +14,17 @@ #include <zenstore/caslog.h> #include <zenstore/gc.h> -namespace spdlog { -class logger; -} - #if ZEN_PLATFORM_WINDOWS # include <zencore/windows.h> #endif +#include <atomic> +#include <unordered_map> + +namespace spdlog { +class logger; +} + namespace zen { ////////////////////////////////////////////////////////////////////////// diff --git a/zenstore/filecas.cpp b/zenstore/filecas.cpp index 76b921994..533c99569 100644 --- a/zenstore/filecas.cpp +++ b/zenstore/filecas.cpp @@ -35,8 +35,6 @@ ZEN_THIRD_PARTY_INCLUDES_END namespace zen { -using namespace fmt::literals; - FileCasStrategy::ShardingHelper::ShardingHelper(const std::filesystem::path& RootPath, const IoHash& ChunkHash) { ShardedPath.Append(RootPath.c_str()); @@ -241,7 +239,7 @@ FileCasStrategy::InsertChunk(IoBuffer Chunk, const IoHash& ChunkHash) if (FAILED(hRes)) { - ThrowSystemException(hRes, "Failed to open shard directory '{}'"_format(FilePath)); + ThrowSystemException(hRes, fmt::format("Failed to open shard directory '{}'", FilePath)); } // Retry rename/move @@ -271,7 +269,7 @@ FileCasStrategy::InsertChunk(IoBuffer Chunk, const IoHash& ChunkHash) ChunkHash); DeletePayloadFileOnClose(); -#elif ZEN_PLATFORM_LINUX +#elif ZEN_PLATFORM_LINUX || ZEN_PLATFORM_MAC std::filesystem::path SourcePath = PathFromHandle(FileRef.FileHandle); std::filesystem::path DestPath = Name.ShardedPath.c_str(); int Ret = link(SourcePath.c_str(), DestPath.c_str()); @@ -311,8 +309,6 @@ FileCasStrategy::InsertChunk(IoBuffer Chunk, const IoHash& ChunkHash) { return CasStore::InsertResult{.New = true}; } -#else -# error check link/unlink for this platform #endif // ZEN_PLATFORM_* } @@ -345,13 +341,11 @@ FileCasStrategy::InsertChunk(const void* const ChunkData, const size_t ChunkSize } PayloadFile.Close(); -#elif ZEN_PLATFORM_LINUX +#elif ZEN_PLATFORM_LINUX || ZEN_PLATFORM_MAC if (access(Name.ShardedPath.c_str(), F_OK) == 0) { return CasStore::InsertResult{.New = false}; } -#else -# error Check access() for this platform #endif RwLock::ExclusiveLockScope _(LockForHash(ChunkHash)); @@ -390,7 +384,7 @@ FileCasStrategy::InsertChunk(const void* const ChunkData, const size_t ChunkSize if (FAILED(hRes)) { - ThrowSystemException(hRes, "Failed to open shard file '{}'"_format(Name.ShardedPath.ToUtf8())); + ThrowSystemException(hRes, fmt::format("Failed to open shard file '{}'", Name.ShardedPath.ToUtf8())); } #else // Attempt to exclusively create the file. @@ -413,10 +407,10 @@ FileCasStrategy::InsertChunk(const void* const ChunkData, const size_t ChunkSize break; } } - ThrowLastError("Failed creating shard directory '{}'"_format(Name.ShardedPath)); + ThrowLastError(fmt::format("Failed creating shard directory '{}'", Name.ShardedPath)); default: - ThrowLastError("Unexpected error occurred opening shard file '{}'"_format(Name.ShardedPath)); + ThrowLastError(fmt::format("Unexpected error occurred opening shard file '{}'", Name.ShardedPath)); } } @@ -573,7 +567,7 @@ FileCasStrategy::IterateChunks(std::function<void(const IoHash& Hash, BasicFile& } } - virtual bool VisitDirectory([[maybe_unused]] const std::filesystem::path& Parent, [[maybe_unused]] const path_view& DirectoryName) + virtual bool VisitDirectory([[maybe_unused]] const std::filesystem::path& Parent, [[maybe_unused]] const path_view& DirectoryName) override { return true; } @@ -727,8 +721,6 @@ FileCasStrategy::CollectGarbage(GcContext& GcCtx) TEST_CASE("cas.file.move") { - using namespace fmt::literals; - // specifying an absolute path here can be helpful when using procmon to dig into things ScopedTemporaryDirectory TempDir; // {"d:\\filecas_testdir"}; @@ -773,7 +765,7 @@ TEST_CASE("cas.file.move") *reinterpret_cast<int*>(Payload.MutableData()) = i; PayloadHashes.push_back(IoHash::HashBuffer(Payload)); - std::filesystem::path PayloadPath{TempDir.Path() / "payload_{}_{}"_format(w, i)}; + std::filesystem::path PayloadPath{TempDir.Path() / fmt::format("payload_{}_{}", w, i)}; WriteFile(PayloadPath, Payload); } } @@ -785,7 +777,7 @@ TEST_CASE("cas.file.move") for (int i = 0; i < kItemCount; ++i) { - std::filesystem::path PayloadPath{TempDir.Path() / "payload_{}_{}"_format(w, i)}; + std::filesystem::path PayloadPath{TempDir.Path() / fmt::format("payload_{}_{}", w, i)}; IoBuffer Payload = IoBufferBuilder::MakeFromTemporaryFile(PayloadPath); Buffers.push_back(Payload); Sync.arrive_and_wait(); diff --git a/zenstore/gc.cpp b/zenstore/gc.cpp index d23e0c466..0e93f1c3d 100644 --- a/zenstore/gc.cpp +++ b/zenstore/gc.cpp @@ -393,7 +393,7 @@ GcScheduler::Initialize(const GcSchedulerConfig& Config) } m_NextGcTime = NextGcTime(m_LastGcTime); - m_GcThread = std::jthread(&GcScheduler::SchedulerThread, this); + m_GcThread = std::thread(&GcScheduler::SchedulerThread, this); } void @@ -403,6 +403,8 @@ GcScheduler::Shutdown() { m_Status = static_cast<uint32_t>(GcSchedulerStatus::kStopped); m_GcSignal.notify_one(); + + m_GcThread.join(); } } @@ -427,8 +429,6 @@ GcScheduler::Trigger(const GcScheduler::TriggerParams& Params) void GcScheduler::SchedulerThread() { - using namespace fmt::literals; - std::chrono::seconds WaitTime = m_Config.MonitorInterval; for (;;) @@ -472,7 +472,7 @@ GcScheduler::SchedulerThread() NiceBytes(Space.Free), NiceBytes(Space.Total), m_Config.Interval.count() - ? "{} until next GC"_format(NiceTimeSpanMs(uint64_t(std::chrono::milliseconds(RemaingTime).count()))) + ? fmt::format("{} until next GC", NiceTimeSpanMs(uint64_t(std::chrono::milliseconds(RemaingTime).count()))) : std::string("next scheduled GC no set")); // TODO: Trigger GC if max disk usage water mark is reached diff --git a/zenstore/include/zenstore/cas.h b/zenstore/include/zenstore/cas.h index 9371e4de0..1823fd630 100644 --- a/zenstore/include/zenstore/cas.h +++ b/zenstore/include/zenstore/cas.h @@ -49,7 +49,7 @@ public: [[nodiscard]] inline bool IsEmpty() const { return m_ChunkSet.empty(); } [[nodiscard]] inline size_t GetSize() const { return m_ChunkSet.size(); } - inline void FilterChunks(std::span<const IoHash> Candidates, std::invocable<const IoHash&> auto MatchFunc) + inline void FilterChunks(std::span<const IoHash> Candidates, Invocable<const IoHash&> auto MatchFunc) { for (const IoHash& Candidate : Candidates) { @@ -60,7 +60,7 @@ public: } } - inline void FilterChunks(std::span<const IoHash> Candidates, std::invocable<const IoHash&, bool> auto MatchFunc) + inline void FilterChunks(std::span<const IoHash> Candidates, Invocable<const IoHash&, bool> auto MatchFunc) { for (const IoHash& Candidate : Candidates) { diff --git a/zenstore/include/zenstore/caslog.h b/zenstore/include/zenstore/caslog.h index 1ecb721f7..1bd11800c 100644 --- a/zenstore/include/zenstore/caslog.h +++ b/zenstore/include/zenstore/caslog.h @@ -66,7 +66,7 @@ public: // This should be called before the Replay() is called to do some basic sanity checking bool Initialize() { return true; } - void Replay(std::invocable<const T&> auto Handler) + void Replay(Invocable<const T&> auto Handler) { CasLogFile::Replay([&](const void* VoidPtr) { const T& Record = *reinterpret_cast<const T*>(VoidPtr); diff --git a/zenstore/include/zenstore/gc.h b/zenstore/include/zenstore/gc.h index 1540b66c2..b8ba338f0 100644 --- a/zenstore/include/zenstore/gc.h +++ b/zenstore/include/zenstore/gc.h @@ -204,7 +204,7 @@ private: GcClock::TimePoint m_LastGcTime{}; GcClock::TimePoint m_NextGcTime{}; std::atomic_uint32_t m_Status{}; - std::jthread m_GcThread; + std::thread m_GcThread; std::mutex m_GcMutex; std::condition_variable m_GcSignal; std::optional<TriggerParams> m_TriggerParams; diff --git a/zenutil/zenserverprocess.cpp b/zenutil/zenserverprocess.cpp index 93886a6b7..fe6236d18 100644 --- a/zenutil/zenserverprocess.cpp +++ b/zenutil/zenserverprocess.cpp @@ -11,7 +11,6 @@ #include <zencore/thread.h> #include <atomic> -#include <source_location> #if ZEN_PLATFORM_WINDOWS # include <atlbase.h> @@ -52,7 +51,7 @@ namespace zenutil { { if (!SetSecurityDescriptorDacl(&m_Sd, TRUE, (PACL)NULL, FALSE)) { - ThrowLastError("SetSecurityDescriptorDacl failed", std::source_location::current()); + ThrowLastError("SetSecurityDescriptorDacl failed"); } m_Attributes.lpSecurityDescriptor = &m_Sd; @@ -651,9 +650,7 @@ ZenServerInstance::GetBaseUri() const { ZEN_ASSERT(m_BasePort); - using namespace fmt::literals; - - return "http://localhost:{}"_format(m_BasePort); + return fmt::format("http://localhost:{}", m_BasePort); } } // namespace zen |