From 053ee5b296d1f41b0653b4301bbea1e857be2279 Mon Sep 17 00:00:00 2001 From: faumaray Date: Sat, 25 Jul 2026 23:42:52 +0300 Subject: [PATCH] update Signed-off-by: faumaray --- CMakeLists.txt | 5 + cmake/BoostProbe/CMakeLists.txt | 14 ++ cmake/Dependencies.cmake | 123 +++++++++++-- cmake/Module.cmake | 76 +++++++- cmake/VoidConfig.cmake.in | 20 ++- cmake/VoidTestScanner.cmake | 19 +- docs/short-url.md | 29 ++++ include/Void/Plugin/Manager.hpp | 5 + include/Void/Service/PluginService.hpp | 220 ++++++++++++++++++------ include/Void/ShortUrl/ShortUrl.hpp | 165 ++++++++++++++++++ include/Void/Time/Bench.hpp | 7 +- src/Net/module.cmake | 2 + src/Plugin/Manager.cpp | 33 ++-- src/ShortUrl/module.cmake | 3 + src/Stacktrace/Stacktrace.cpp | 1 - src/Stacktrace/module.cmake | 14 +- tests/CMakeLists.txt | 10 ++ tests/internal/FsmServiceHotReload.cpp | 88 ++++++++++ tests/package/External/CMakeLists.txt | 20 +++ tests/package/External/main.cpp | 19 ++ tests/package/InstalledComponents.cmake | 5 + tests/standalone/Log/Fields.cpp | 2 +- tests/standalone/ShortUrl/ShortUrl.cpp | 58 +++++++ 23 files changed, 845 insertions(+), 93 deletions(-) create mode 100644 cmake/BoostProbe/CMakeLists.txt create mode 100644 docs/short-url.md create mode 100644 include/Void/ShortUrl/ShortUrl.hpp create mode 100644 src/ShortUrl/module.cmake create mode 100644 tests/package/External/CMakeLists.txt create mode 100644 tests/package/External/main.cpp create mode 100644 tests/standalone/ShortUrl/ShortUrl.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index b46e8d7..d05e795 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -53,6 +53,11 @@ get_property(ALL_MODULE_DEPENDENCY_RECORDS GLOBAL PROPERTY set(VOID_MODULES_LIST "${ALL_DISCOVERED_MODULES}") set(VOID_MODULE_DEPENDENCY_RECORDS "${ALL_MODULE_DEPENDENCY_RECORDS}") +if(WIN32 AND NOT CYGWIN) + set(VOID_BOOST_STACKTRACE_COMPONENT stacktrace_windbg) +else() + set(VOID_BOOST_STACKTRACE_COMPONENT stacktrace_addr2line) +endif() write_basic_package_version_file( "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake" diff --git a/cmake/BoostProbe/CMakeLists.txt b/cmake/BoostProbe/CMakeLists.txt new file mode 100644 index 0000000..f2104c0 --- /dev/null +++ b/cmake/BoostProbe/CMakeLists.txt @@ -0,0 +1,14 @@ +# Isolated completeness probe used by cmake/Dependencies.cmake. Imported +# targets created by a failed find_package stay scoped to this directory, so a +# subsequent FetchContent fallback can define its own Boost targets safely. +if(WIN32 AND NOT CYGWIN) + set(_stacktrace_component stacktrace_windbg) +else() + set(_stacktrace_component stacktrace_addr2line) +endif() +find_package(Boost CONFIG QUIET + COMPONENTS ${_stacktrace_component} url) + +if(TARGET Boost::${_stacktrace_component} AND TARGET Boost::url) + set_property(GLOBAL PROPERTY VOID_COMPLETE_SYSTEM_BOOST TRUE) +endif() diff --git a/cmake/Dependencies.cmake b/cmake/Dependencies.cmake index 102c6b1..897ae7e 100644 --- a/cmake/Dependencies.cmake +++ b/cmake/Dependencies.cmake @@ -1,33 +1,127 @@ include(FetchContent) +function(void_ensure_boost_header_targets) + if(NOT TARGET Boost::headers AND TARGET Boost::boost) + add_library(Boost::headers INTERFACE IMPORTED) + set_property(TARGET Boost::headers PROPERTY + INTERFACE_LINK_LIBRARIES Boost::boost) + endif() + foreach(_component IN ITEMS beast asio) + if(NOT TARGET Boost::${_component} AND + TARGET boost_${_component}) + add_library(Boost::${_component} ALIAS boost_${_component}) + elseif(NOT TARGET Boost::${_component} AND TARGET Boost::headers) + # System Boost packages commonly expose one aggregate include + # target rather than per-header-library targets. + add_library(Boost::${_component} INTERFACE IMPORTED) + set_property(TARGET Boost::${_component} PROPERTY + INTERFACE_LINK_LIBRARIES Boost::headers) + endif() + endforeach() +endfunction() + +function(void_install_fetched_boost_runtime) + get_property(_runtime_registered GLOBAL + PROPERTY VOID_FETCHED_BOOST_RUNTIME_REGISTERED) + if(_runtime_registered) + return() + endif() + set_property(GLOBAL PROPERTY VOID_FETCHED_BOOST_RUNTIME_REGISTERED TRUE) + + # Boost disables its install rules when consumed through add_subdirectory. + # Register the selected shared runtime closure explicitly so an installed + # shared Void package never points back into its build tree. + foreach(_target IN ITEMS + boost_container + boost_context + boost_coroutine + boost_date_time + boost_stacktrace_addr2line + boost_stacktrace_windbg + boost_url) + if(TARGET ${_target}) + get_target_property(_type ${_target} TYPE) + if(_type STREQUAL "SHARED_LIBRARY" OR + _type STREQUAL "MODULE_LIBRARY") + if(UNIX) + set_property(TARGET ${_target} PROPERTY + INSTALL_RPATH "$ORIGIN") + endif() + install(TARGETS ${_target} + RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" + LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}") + endif() + endif() + endforeach() +endfunction() + function(void_fetch_dependency DEP_NAME) if(DEP_NAME STREQUAL "Boost") - # Components Void uses across modules: stacktrace_backtrace (Stacktrace), - # url + system (Net; beast/asio are header-only and come via Boost::headers). - if(TARGET Boost::stacktrace_backtrace AND TARGET Boost::url) + if(WIN32 AND NOT CYGWIN) + set(_stacktrace_component stacktrace_windbg) + else() + set(_stacktrace_component stacktrace_addr2line) + endif() + + # Components Void uses across modules: a platform Stacktrace backend, + # plus url, beast, and asio (Net). + if(TARGET Boost::${_stacktrace_component} AND TARGET Boost::url) + void_ensure_boost_header_targets() return() endif() - # On modern Boost (1.85+) system/asio/beast are header-only and folded - # into Boost::headers; only stacktrace_backtrace and url are components. - find_package(Boost QUIET COMPONENTS stacktrace_backtrace url) - if(TARGET Boost::stacktrace_backtrace AND TARGET Boost::url) + # Probe in a child directory because a failed component-aware + # find_package(Boost) can still leave partial imported targets such as + # Boost::headers in its directory scope. Those partial targets collide + # with Boost's FetchContent build. Imported targets created by this + # probe stay in the child scope; only a boolean result is exported. + get_property(_boost_probe_ran GLOBAL + PROPERTY VOID_COMPLETE_SYSTEM_BOOST SET) + if(NOT _boost_probe_ran) + set_property(GLOBAL PROPERTY VOID_COMPLETE_SYSTEM_BOOST FALSE) + add_subdirectory( + "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/BoostProbe" + "${PROJECT_BINARY_DIR}/void-boost-probe" + EXCLUDE_FROM_ALL) + endif() + get_property(_complete_system_boost GLOBAL + PROPERTY VOID_COMPLETE_SYSTEM_BOOST) + if(_complete_system_boost) + # On modern Boost, beast/asio are header-only and folded into + # Boost::headers. The fetched Asio target carries its own System + # dependency; requiring a separate system component here rejects + # otherwise complete distro packages where Boost.System is folded + # into Boost::headers. + find_package(Boost CONFIG REQUIRED + COMPONENTS ${_stacktrace_component} url) + void_ensure_boost_header_targets() return() endif() + if(TARGET Boost::headers OR TARGET Boost::boost) + message(FATAL_ERROR + "[Void] Incomplete Boost targets already exist in the parent " + "project. Provide ${_stacktrace_component} and url before " + "adding Void, or let Void resolve Boost first.") + endif() + message(STATUS "[Void] Boost (stacktrace/url) not found — falling back to FetchContent") - set(BOOST_INCLUDE_LIBRARIES "stacktrace;url;system;beast;asio" CACHE STRING "" FORCE) - set(BOOST_ENABLE_CMAKE ON CACHE BOOL "" FORCE) + # Keep Boost's selection local to this dependency resolution. Avoid + # overwriting a parent project's cache when Void is embedded. + set(BOOST_INCLUDE_LIBRARIES "stacktrace;url;system;beast;asio") FetchContent_Declare(Boost URL https://github.com/boostorg/boost/releases/download/boost-1.84.0/boost-1.84.0.tar.xz URL_HASH SHA256=2e64e5d79a738d0fa6fb546c6e5c2bd28f88d268a2a080546f74e5ff98f29d0e - EXCLUDE_FROM_ALL ) FetchContent_MakeAvailable(Boost) - if(NOT TARGET Boost::stacktrace_backtrace AND TARGET boost_stacktrace_backtrace) - add_library(Boost::stacktrace_backtrace ALIAS boost_stacktrace_backtrace) + if(NOT TARGET Boost::${_stacktrace_component} AND + TARGET boost_${_stacktrace_component}) + add_library(Boost::${_stacktrace_component} + ALIAS boost_${_stacktrace_component}) endif() + void_ensure_boost_header_targets() + void_install_fetched_boost_runtime() return() endif() @@ -47,9 +141,12 @@ function(void_fetch_dependency DEP_NAME) endif() if(DEP_NAME STREQUAL "SQLite3") - if(NOT TARGET SQLite3::SQLite3) + if(NOT TARGET SQLite3::SQLite3 AND NOT TARGET SQLite::SQLite3) find_package(SQLite3 REQUIRED) endif() + if(NOT TARGET SQLite3::SQLite3 AND TARGET SQLite::SQLite3) + add_library(SQLite3::SQLite3 ALIAS SQLite::SQLite3) + endif() return() endif() diff --git a/cmake/Module.cmake b/cmake/Module.cmake index 3c7ffef..a328b7f 100644 --- a/cmake/Module.cmake +++ b/cmake/Module.cmake @@ -35,15 +35,42 @@ function(void_add_module MODULE_NAME) target_sources(${TGT} PRIVATE ${SRC}) target_compile_features(${TGT} PUBLIC cxx_std_26) endif() + get_target_property(_module_target_type ${TGT} TYPE) + if(_module_target_type STREQUAL "SHARED_LIBRARY" OR + _module_target_type STREQUAL "MODULE_LIBRARY") + # External packages are implementation details of compiled shared + # modules: Void's installed public headers do not expose their types. + # Keeping these links private also lets a shared Void SDK carry a + # fetched runtime dependency without requiring that dependency's CMake + # development package on every consumer machine. + set(_external_scope PRIVATE) + set(_record_external_dependencies FALSE) + else() + set(_external_scope ${SCOPE}) + set(_record_external_dependencies TRUE) + endif() add_library(${ALIAS} ALIAS ${TGT}) set_property(GLOBAL APPEND PROPERTY VOID_MODULES ${MODULE_NAME}) set(_module_external_deps "") foreach(ext_dep IN LISTS ARG_EXTERNAL_DEPS) - string(REGEX REPLACE "::.*" "" BASE_DEP ${ext_dep}) - list(APPEND _module_external_deps ${BASE_DEP}) + # FindSQLite3's package name and imported-target namespace differ. + # Preserve the package name in exported dependency metadata. + if(ext_dep MATCHES "^SQLite::") + set(BASE_DEP SQLite3) + else() + string(REGEX REPLACE "::.*" "" BASE_DEP ${ext_dep}) + endif() + if(_record_external_dependencies) + list(APPEND _module_external_deps ${BASE_DEP}) + endif() include(cmake/Dependencies.cmake) void_fetch_dependency(${BASE_DEP}) + if(NOT TARGET ${ext_dep}) + message(FATAL_ERROR + "[Void] Dependency '${ext_dep}' required by module " + "'${MODULE_NAME}' was not provided") + endif() endforeach() set(_module_internal_deps ${ARG_INTERNAL_DEPS} ${ARG_OPTIONAL_DEPS}) @@ -78,7 +105,41 @@ function(void_add_module MODULE_NAME) endif() if(ARG_EXTERNAL_DEPS) - target_link_libraries(${TGT} ${SCOPE} ${ARG_EXTERNAL_DEPS}) + if(_external_scope STREQUAL "PRIVATE") + foreach(_external_dep IN LISTS ARG_EXTERNAL_DEPS) + string(MAKE_C_IDENTIFIER "${_external_dep}" + _external_dep_identifier) + set(_build_external_target + "_void_${MODULE_NAME}_${_external_dep_identifier}") + add_library(${_build_external_target} INTERFACE IMPORTED) + set_property(TARGET ${_build_external_target} PROPERTY + INTERFACE_LINK_LIBRARIES "${_external_dep}") + target_link_libraries(${TGT} PRIVATE + "$") + endforeach() + else() + # Keep fetched dependency build targets out of Void's install + # export. Static and interface consumers still receive the same + # canonical targets after find_dependency(). + foreach(_external_dep IN LISTS ARG_EXTERNAL_DEPS) + string(MAKE_C_IDENTIFIER "${_external_dep}" + _external_dep_identifier) + set(_build_external_target + "_void_${MODULE_NAME}_${_external_dep_identifier}") + add_library(${_build_external_target} INTERFACE IMPORTED) + set_property(TARGET ${_build_external_target} PROPERTY + INTERFACE_LINK_LIBRARIES "${_external_dep}") + # Defer namespace reconstruction until a consumer evaluates + # the installed target. Otherwise CMake canonicalizes aliases + # from a FetchContent dependency (Boost::url -> boost_url) and + # requires the third-party target in Void's export set. + string(REPLACE "::" "$<1:::>" _install_external_dep + "${_external_dep}") + target_link_libraries(${TGT} ${_external_scope} + "$" + "$") + endforeach() + endif() endif() foreach(_lib IN LISTS ARG_DEPS_WIN32) @@ -140,6 +201,15 @@ function(void_add_module MODULE_NAME) CXX_EXTENSIONS OFF EXPORT_NAME ${MODULE_NAME} ) + if(UNIX AND _module_target_type STREQUAL "SHARED_LIBRARY") + set_property(TARGET ${TGT} PROPERTY INSTALL_RPATH "$ORIGIN") + endif() + if(WIN32 AND _module_target_type STREQUAL "SHARED_LIBRARY") + # Void's public headers do not require consumers to opt into a DLL + # import macro. Generate the export table for compiled shared modules + # so the same installed targets remain usable on Windows. + set_property(TARGET ${TGT} PROPERTY WINDOWS_EXPORT_ALL_SYMBOLS ON) + endif() # GCC 16+ exposes experimental C++26 reflection (P2996) via -freflection. # Apply it to every module unconditionally so any module is free to use diff --git a/cmake/VoidConfig.cmake.in b/cmake/VoidConfig.cmake.in index 40550f9..1f27c48 100644 --- a/cmake/VoidConfig.cmake.in +++ b/cmake/VoidConfig.cmake.in @@ -64,7 +64,20 @@ if(_void_external_deps) endif() foreach(dep IN LISTS _void_external_deps) if(dep STREQUAL "Boost") - find_dependency(Boost REQUIRED COMPONENTS stacktrace_backtrace url) + find_dependency(Boost CONFIG REQUIRED COMPONENTS + @VOID_BOOST_STACKTRACE_COMPONENT@ url) + if(NOT TARGET Boost::headers AND TARGET Boost::boost) + add_library(Boost::headers INTERFACE IMPORTED) + set_property(TARGET Boost::headers PROPERTY + INTERFACE_LINK_LIBRARIES Boost::boost) + endif() + foreach(_component IN ITEMS beast asio) + if(NOT TARGET Boost::${_component} AND TARGET Boost::headers) + add_library(Boost::${_component} INTERFACE IMPORTED) + set_property(TARGET Boost::${_component} PROPERTY + INTERFACE_LINK_LIBRARIES Boost::headers) + endif() + endforeach() elseif(dep STREQUAL "Sodium") find_dependency(PkgConfig REQUIRED) pkg_check_modules(SODIUM REQUIRED IMPORTED_TARGET libsodium) @@ -75,6 +88,11 @@ foreach(dep IN LISTS _void_external_deps) endif() elseif(dep STREQUAL "LibArchive") find_dependency(LibArchive REQUIRED) + elseif(dep STREQUAL "SQLite3") + find_dependency(SQLite3 REQUIRED) + if(NOT TARGET SQLite3::SQLite3 AND TARGET SQLite::SQLite3) + add_library(SQLite3::SQLite3 ALIAS SQLite::SQLite3) + endif() elseif(NOT TARGET ${dep}) find_dependency(${dep}) endif() diff --git a/cmake/VoidTestScanner.cmake b/cmake/VoidTestScanner.cmake index 7ea1f9e..db8406a 100644 --- a/cmake/VoidTestScanner.cmake +++ b/cmake/VoidTestScanner.cmake @@ -51,7 +51,11 @@ foreach(line IN LISTS lines) if(_match) string(REGEX REPLACE "^[ \t]*class[ \t]+([A-Za-z_][A-Za-z0-9_]*)[ \t]*:.*" "\\1" fixture_class_name "${line}") set(in_fixture_class TRUE) - string(REGEX MATCH "^[ \t]*" fixture_indent "${line}") + # Derive indentation without an empty-match-capable regex. CMake 4 + # rejects such expressions even when the current input is non-empty. + string(STRIP "${line}" _trimmed_fixture_line) + string(FIND "${line}" "${_trimmed_fixture_line}" _indent_length) + string(SUBSTRING "${line}" 0 ${_indent_length} fixture_indent) endif() if(in_fixture_class) @@ -127,8 +131,17 @@ foreach(line IN LISTS lines) set(current_skip "") else() # If line is code (not comment/empty), break the comment association - string(REGEX MATCH "^[ \t]*$" _is_empty "${line}") - string(REGEX MATCH "^[ \t]*//" _is_comment "${line}") + string(STRIP "${line}" _stripped_line) + if(_stripped_line STREQUAL "") + set(_is_empty TRUE) + else() + set(_is_empty FALSE) + endif() + if(line MATCHES "^[ \t]*//") + set(_is_comment TRUE) + else() + set(_is_comment FALSE) + endif() if(NOT _is_empty AND NOT _is_comment) set(current_tags "") set(current_skip "") diff --git a/docs/short-url.md b/docs/short-url.md new file mode 100644 index 0000000..5defccc --- /dev/null +++ b/docs/short-url.md @@ -0,0 +1,29 @@ +# Short URL service + +Void::ShortUrl::IShortener is a provider-neutral ABI-v1 service for creating +short URLs and, when supported, resolving their keys. It has no dependency on +Echoion or any specific HTTP provider. + +Implementations derive from IShortener and can be registered directly in a +Void::Service::ServiceRegistry. Plugin implementations export the standard +void_plugin_service(void*) symbol and are bound with +Void::Service::PluginServiceBinding. + +The versioned contract lives in Void::ShortUrl::V1; aliases in Void::ShortUrl +select the current ABI. Implementations report a provider identifier and health +status. An empty custom key asks the provider to generate one, and an expiry of +zero means permanent. + +Keep the returned shared pointer for the complete operation. That pin guarantees +the implementation and its shared object remain alive during plugin reload. +resolve() intentionally defaults to not_supported, which permits providers +backed by external APIs that cannot reverse a short link. + +V1 is frozen: enum ordinals, data-member order, and virtual method order must +not change after release. Incompatible evolution is introduced as V2 with a +new service interface. Because the ABI carries C++ standard-library values, +host and provider must use the same C++ runtime and the exact toolchain +contract recorded by the application release. + +A provider must either honor a non-empty custom key and non-zero expiry or +return unsupported/conflict; silently ignoring either request is invalid. diff --git a/include/Void/Plugin/Manager.hpp b/include/Void/Plugin/Manager.hpp index 51486bb..69b0b5a 100644 --- a/include/Void/Plugin/Manager.hpp +++ b/include/Void/Plugin/Manager.hpp @@ -49,6 +49,11 @@ namespace Void::Plugin [[nodiscard]] explicit operator bool() const noexcept; [[nodiscard]] const PluginInfo& info() const noexcept; + /// Resolve an optional symbol from the exact shared object pinned + /// by this handle. The returned address remains valid while the + /// handle is alive, even if the manager concurrently reloads the + /// plugin. + [[nodiscard]] void* raw_symbol(const char* symbol) const noexcept; private: diff --git a/include/Void/Service/PluginService.hpp b/include/Void/Service/PluginService.hpp index b44d38a..3e1bba8 100644 --- a/include/Void/Service/PluginService.hpp +++ b/include/Void/Service/PluginService.hpp @@ -5,7 +5,10 @@ #include #include +#include +#include #include +#include #include #include #include @@ -17,8 +20,8 @@ namespace Void::Service /// extern "C" Void::Service::IService* void_plugin_service(void* inst); /// It returns the IService subobject of the plugin's service object /// (which must derive the host interface I, and I must derive - /// IService). The host recovers I* by static_cast — no dynamic_cast, so - /// it is robust across RTLD_LOCAL plugin boundaries. + /// IService). The host verifies the exported subobject with dynamic_cast; + /// host and provider must therefore share RTTI identity for I. using service_factory_fn = IService* (*)(void* instance); inline constexpr const char* kServiceSymbol = "void_plugin_service"; @@ -32,23 +35,28 @@ namespace Void::Service /// callers never see a freed object. /// /// Requires: I derives Void::Service::IService; the plugin's service - /// type derives I; the plugin exports void_plugin_service. + /// type derives I; the plugin exports void_plugin_service. RTTI identity + /// for I must be shared by host and provider, just like PluginManager's + /// host-specific instance_validator interfaces. template class PluginServiceBinding { public: static_assert(std::is_base_of_v, "plugin service interface must derive IService"); + using Validator = + std::function& service)>; PluginServiceBinding(Plugin::PluginManager& manager, - ServiceRegistry& registry, std::string name) - : m_manager(&manager), m_registry(®istry), - m_name(std::move(name)) + ServiceRegistry& registry, std::string name, + Validator validator = {}) + : m_state(std::make_shared( + manager, registry, std::move(name), std::move(validator))) { } - // The reload callback captures `this`; the binding must - // deregister it before dying and therefore cannot move. + // Lifecycle registration cannot be transferred while callbacks may + // be in flight. PluginServiceBinding(const PluginServiceBinding&) = delete; PluginServiceBinding& operator=(const PluginServiceBinding&) = delete; @@ -56,65 +64,181 @@ namespace Void::Service ~PluginServiceBinding() { disable_hot_reload(); } /// Resolve the current instance's service and (re)register it. - [[nodiscard]] bool bind() - { - auto handle = m_manager->acquire(m_name); - if (!handle) { - return false; - } - auto* fn = reinterpret_cast( - m_manager->raw_symbol(m_name, kServiceSymbol)); - if (fn == nullptr) { - return false; - } - IService* base = fn(handle.get()); - if (base == nullptr) { - return false; - } - I* iface = static_cast(base); // I : IService - - // Keep the plugin instance (and its mapped .so) alive for - // as long as the registry holds this service. - auto owner = std::make_shared(handle); - std::shared_ptr pinned(std::move(owner), iface); - m_registry->provide(std::move(pinned)); - Void::Log::debug("Service.Plugin", - "bound service from plugin '{}'", m_name); - return true; - } + [[nodiscard]] bool bind() noexcept { return m_state->bind(); } /// Auto-rebind on hot reload (debounced file watching). The /// manager keeps old instances alive while pinned, so the swap /// is seamless. Idempotent. void enable_hot_reload() { + std::lock_guard lifecycleLock{m_lifecycleMutex}; if (m_reload_id != 0) { return; } - m_reload_id = - m_manager->on_reloaded([this](std::string_view name) { - if (name == m_name) { - (void)bind(); - } - }); - m_manager->watch(m_name); + m_state->set_hot_reload_enabled(true); + try { + std::weak_ptr weakState{m_state}; + m_reload_id = m_state->manager().on_reloaded( + [weakState](std::string_view name) noexcept { + if (auto state = weakState.lock()) { + state->rebind(name); + } + }); + m_state->manager().watch(m_state->name()); + } catch (...) { + m_state->set_hot_reload_enabled(false); + if (m_reload_id != 0) { + m_state->manager().remove_on_reloaded(m_reload_id); + m_reload_id = 0; + } + throw; + } } /// Stop observing reloads (the file watch itself is shared and /// stays). Idempotent; called by the destructor. - void disable_hot_reload() + void disable_hot_reload() noexcept { - if (m_reload_id != 0) { - m_manager->remove_on_reloaded(m_reload_id); - m_reload_id = 0; + try { + std::lock_guard lifecycleLock{m_lifecycleMutex}; + m_state->set_hot_reload_enabled(false); + if (m_reload_id != 0) { + m_state->manager().remove_on_reloaded(m_reload_id); + m_reload_id = 0; + } + } catch (...) { + // Destruction must remain noexcept. The weak callback + // cannot keep State alive after m_state is released even if + // observer removal itself reports a failure. } } private: - Plugin::PluginManager* m_manager; - ServiceRegistry* m_registry; - std::string m_name; + class State + { + public: + + State(Plugin::PluginManager& manager, + ServiceRegistry& registry, std::string name, + Validator validator) + : m_manager(&manager), m_registry(®istry), + m_name(std::move(name)), + m_validator(std::move(validator)) + { + } + + [[nodiscard]] bool bind() noexcept + { + try { + std::lock_guard lock{m_mutex}; + return bind_locked(); + } catch (...) { + return false; + } + } + + void rebind(std::string_view name) noexcept + { + if (name != m_name) { + return; + } + try { + std::lock_guard lock{m_mutex}; + if (m_hotReloadEnabled) { + (void)bind_locked(); + } + } catch (...) { + } + } + + void set_hot_reload_enabled(bool enabled) + { + std::lock_guard lock{m_mutex}; + m_hotReloadEnabled = enabled; + } + + [[nodiscard]] Plugin::PluginManager& + manager() const noexcept + { + return *m_manager; + } + + [[nodiscard]] const std::string& name() const noexcept + { + return m_name; + } + + private: + + [[nodiscard]] bool bind_locked() noexcept + { + try { + auto handle = m_manager->acquire(m_name); + if (!handle) { + return false; + } + auto* factory = + reinterpret_cast( + handle.raw_symbol(kServiceSymbol)); + if (factory == nullptr) { + return false; + } + IService* base = factory(handle.get()); + if (base == nullptr) { + return false; + } + I* iface = dynamic_cast(base); + if (iface == nullptr) { + Void::Log::warn( + "Service.Plugin", + "plugin '{}' exported an incompatible " + "service interface", + m_name); + return false; + } + + // Pin the exact instance and shared object that + // supplied the factory and service subobject. + auto owner = std::make_shared( + std::move(handle)); + std::shared_ptr pinned(std::move(owner), iface); + if (m_validator && !m_validator(pinned)) { + Void::Log::warn( + "Service.Plugin", + "plugin '{}' service validation failed", + m_name); + return false; + } + m_registry->provide(std::move(pinned)); + Void::Log::debug("Service.Plugin", + "bound service from plugin '{}'", + m_name); + return true; + } catch (const std::exception& error) { + Void::Log::warn( + "Service.Plugin", + "binding service from plugin '{}' threw: {}", + m_name, error.what()); + } catch (...) { + Void::Log::warn( + "Service.Plugin", + "binding service from plugin '{}' threw", + m_name); + } + return false; + } + + Plugin::PluginManager* m_manager; + ServiceRegistry* m_registry; + std::string m_name; + Validator m_validator; + std::mutex m_mutex; + bool m_hotReloadEnabled{false}; + }; + + std::shared_ptr m_state; + std::mutex m_lifecycleMutex; Plugin::ReloadCallbackId m_reload_id{0}; }; diff --git a/include/Void/ShortUrl/ShortUrl.hpp b/include/Void/ShortUrl/ShortUrl.hpp new file mode 100644 index 0000000..14aca13 --- /dev/null +++ b/include/Void/ShortUrl/ShortUrl.hpp @@ -0,0 +1,165 @@ +#pragma once + +#include + +#include +#include +#include +#include + +namespace Void::ShortUrl::V1 +{ + inline constexpr std::string_view kServiceId{"void.short-url"}; + inline constexpr std::uint32_t kServiceVersion{1}; + + enum class ErrorCode : std::uint32_t { + none = 0, + invalid_request, + unsupported, + not_found, + expired, + conflict, + unauthorized, + rate_limited, + timeout, + unavailable, + provider_error, + internal_error, + invalid_url, + revoked, + storage, + response_too_large, + }; + + struct Error { + ErrorCode code{ErrorCode::none}; + std::string message; + std::uint32_t retry_after_seconds{0}; + + [[nodiscard]] bool ok() const noexcept + { + return code == ErrorCode::none; + } + + [[nodiscard]] explicit operator bool() const noexcept + { + return !ok(); + } + }; + + struct ShortenRequest { + std::string target_url; + std::string custom_key; + std::int64_t expires_at_unix_seconds{0}; + }; + + struct ShortenResult { + std::string short_url; + std::string key; + std::int64_t expires_at_unix_seconds{0}; + Error error; + + [[nodiscard]] bool ok() const noexcept + { + return error.ok() && !short_url.empty(); + } + + [[nodiscard]] explicit operator bool() const noexcept + { + return ok(); + } + }; + + enum class HealthStatus : std::uint32_t { + unknown = 0, + healthy, + degraded, + unhealthy, + }; + + struct Health { + HealthStatus status{HealthStatus::unknown}; + std::string message; + }; + + struct ResolveRequest { + std::string key; + }; + + struct ResolveResult { + std::string target_url; + std::int64_t expires_at_unix_seconds{0}; + Error error; + + [[nodiscard]] bool ok() const noexcept + { + return error.ok() && !target_url.empty(); + } + + [[nodiscard]] explicit operator bool() const noexcept + { + return ok(); + } + }; + + class IShortener : public Service::IService + { + public: + + ~IShortener() override = default; + + [[nodiscard]] std::string_view service_name() const final + { + return kServiceId; + } + + [[nodiscard]] virtual std::uint32_t service_version() const noexcept + { + return kServiceVersion; + } + + [[nodiscard]] virtual std::string_view + provider_id() const noexcept = 0; + + [[nodiscard]] virtual Health health() const = 0; + + [[nodiscard]] virtual ShortenResult + shorten(const ShortenRequest& request) = 0; + + [[nodiscard]] virtual bool supports_resolve() const noexcept + { + return false; + } + + [[nodiscard]] virtual ResolveResult resolve(const ResolveRequest&) + { + return { + .target_url = {}, + .expires_at_unix_seconds = 0, + .error = + { + .code = ErrorCode::unsupported, + .message = + "this shortener does not support resolution", + }, + }; + } + }; + +} // namespace Void::ShortUrl::V1 + +namespace Void::ShortUrl +{ + using V1::Error; + using V1::ErrorCode; + using V1::Health; + using V1::HealthStatus; + using V1::IShortener; + using V1::ResolveRequest; + using V1::ResolveResult; + using V1::ShortenRequest; + using V1::ShortenResult; + + inline constexpr auto kServiceId = V1::kServiceId; + inline constexpr auto kServiceVersion = V1::kServiceVersion; +} // namespace Void::ShortUrl diff --git a/include/Void/Time/Bench.hpp b/include/Void/Time/Bench.hpp index 156c7fb..8e22e5e 100644 --- a/include/Void/Time/Bench.hpp +++ b/include/Void/Time/Bench.hpp @@ -103,7 +103,10 @@ template inline void do_not_optimize(T& val) noexcept { #if defined(__GNUC__) || defined(__clang__) - asm volatile("" : "+r,m"(val) : : "memory"); + // A memory operand works for every object type and remains accepted by + // GCC 16, which rejects the old mixed "+r,m" alternative constraint for + // some scalar instantiations. + asm volatile("" : "+m"(val) : : "memory"); #else volatile T* p = &val; (void)*p; @@ -114,7 +117,7 @@ template inline void do_not_optimize(const T& val) noexcept { #if defined(__GNUC__) || defined(__clang__) - asm volatile("" : : "r,m"(val) : "memory"); + asm volatile("" : : "m"(val) : "memory"); #else volatile const T* p = &val; (void)*p; diff --git a/src/Net/module.cmake b/src/Net/module.cmake index 5d5a196..5cffbd2 100644 --- a/src/Net/module.cmake +++ b/src/Net/module.cmake @@ -2,6 +2,8 @@ void_add_module(Net INTERNAL_DEPS Functional Text EXTERNAL_DEPS Boost::headers + Boost::beast + Boost::asio Boost::url OpenSSL::SSL OpenSSL::Crypto diff --git a/src/Plugin/Manager.cpp b/src/Plugin/Manager.cpp index 58adfe9..346bda8 100644 --- a/src/Plugin/Manager.cpp +++ b/src/Plugin/Manager.cpp @@ -78,6 +78,19 @@ namespace Void::Plugin return m_pin->info; } + void* PluginHandle::raw_symbol(const char* symbol) const noexcept + { +#ifdef VOID_HAS_DLOPEN + if (!m_pin || m_pin->handle == nullptr || symbol == nullptr) { + return nullptr; + } + return dlsym(m_pin->handle, symbol); +#else + (void)symbol; + return nullptr; +#endif + } + // ── loading helpers ─────────────────────────────────────────────────── namespace @@ -589,25 +602,7 @@ namespace Void::Plugin void* PluginManager::raw_symbol(std::string_view name, const char* symbol) const { -#ifdef VOID_HAS_DLOPEN - std::shared_ptr inst; - { - std::lock_guard lock(m_mutex); - auto* entry = find(name); - if (entry == nullptr) { - return nullptr; - } - inst = entry->current.load(std::memory_order_acquire); - } - if (!inst || inst->handle == nullptr) { - return nullptr; - } - return dlsym(inst->handle, symbol); -#else - (void)name; - (void)symbol; - return nullptr; -#endif + return acquire(name).raw_symbol(symbol); } } // namespace Void::Plugin diff --git a/src/ShortUrl/module.cmake b/src/ShortUrl/module.cmake new file mode 100644 index 0000000..5fa098f --- /dev/null +++ b/src/ShortUrl/module.cmake @@ -0,0 +1,3 @@ +void_add_module(ShortUrl + INTERNAL_DEPS Service +) diff --git a/src/Stacktrace/Stacktrace.cpp b/src/Stacktrace/Stacktrace.cpp index 12eda59..8247581 100644 --- a/src/Stacktrace/Stacktrace.cpp +++ b/src/Stacktrace/Stacktrace.cpp @@ -7,7 +7,6 @@ #include #include -#define BOOST_STACKTRACE_USE_BACKTRACE #include #include diff --git a/src/Stacktrace/module.cmake b/src/Stacktrace/module.cmake index cf84d46..90ba0bd 100644 --- a/src/Stacktrace/module.cmake +++ b/src/Stacktrace/module.cmake @@ -1,7 +1,17 @@ +if(WIN32 AND NOT CYGWIN) + set(_void_stacktrace_target Boost::stacktrace_windbg) +else() + set(_void_stacktrace_target Boost::stacktrace_addr2line) +endif() + void_add_module(Stacktrace INTERNAL_DEPS Functional - EXTERNAL_DEPS Boost::stacktrace_backtrace - DEPS_WIN32 dbghelp + EXTERNAL_DEPS ${_void_stacktrace_target} DEPS_UNIX dl OPTIONS_UNIX -g -fno-omit-frame-pointer ) + +if(BUILD_SHARED_LIBS) + target_compile_definitions(Void_Stacktrace + PRIVATE BOOST_STACKTRACE_DYN_LINK) +endif() diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index f3b86a4..b381b8f 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -80,6 +80,16 @@ if(_all_generated) endif() endforeach() + # A few fixtures construct archives and signatures through the upstream C + # APIs directly. Those are test implementation dependencies, not part of + # the public interface of Void's shared modules. + if(TARGET LibArchive::LibArchive) + target_link_libraries(VoidTests PRIVATE LibArchive::LibArchive) + endif() + if(TARGET OpenSSL::Crypto) + target_link_libraries(VoidTests PRIVATE OpenSSL::Crypto) + endif() + add_test(NAME VoidTests COMMAND VoidTests) add_test(NAME VoidInstalledComponentConsumers diff --git a/tests/internal/FsmServiceHotReload.cpp b/tests/internal/FsmServiceHotReload.cpp index ee88c51..8404c27 100644 --- a/tests/internal/FsmServiceHotReload.cpp +++ b/tests/internal/FsmServiceHotReload.cpp @@ -10,7 +10,10 @@ #include #include +#include #include +#include +#include #include #include #include @@ -147,4 +150,89 @@ Void::Testing::Test internal_service_reload_migrates_and_swaps() Void::Testing::expect_eq(v2->accumulate(0), 40); // state migrated } +// A validator rejection during the automatic reload callback must preserve +// the last accepted service instead of publishing the rejected candidate. +Void::Testing::Test plugin_service_reload_validation_preserves_last_good() +{ + Void::FileSystem::TempDir tmp{"void_svcplugin_validate"}; + const auto so = tmp.path() / "calc.so"; + std::filesystem::copy_file(VOID_SERVICE_V1_PATH, so); + + Void::Service::ServiceRegistry registry; + Void::Plugin::PluginManager plugins; + Void::Testing::expect(plugins.load(so).has_value()); + + Void::Service::PluginServiceBinding binding{ + plugins, registry, "CalcPlugin", + [](const std::shared_ptr& service) { + return service->version() == 1; + }}; + Void::Testing::expect(binding.bind()); + binding.enable_hot_reload(); + + install(VOID_SERVICE_V2_PATH, so); + Void::Testing::expect(plugins.reload("CalcPlugin").has_value()); + + auto service = registry.get(); + Void::Testing::expect(service != nullptr); + Void::Testing::expect_eq(service->version(), 1); +} + +// PluginManager intentionally invokes a copied callback list outside its +// mutex. Destroying a binding after that copy must make its callback inert. +Void::Testing::Test plugin_service_callback_is_safe_after_binding_destruction() +{ + Void::FileSystem::TempDir tmp{"void_svcplugin_lifetime"}; + const auto so = tmp.path() / "calc.so"; + std::filesystem::copy_file(VOID_SERVICE_V1_PATH, so); + + Void::Service::ServiceRegistry registry; + Void::Plugin::PluginManager plugins; + Void::Testing::expect(plugins.load(so).has_value()); + + std::mutex gateMutex; + std::condition_variable gateChanged; + bool callbackEntered = false; + bool releaseCallback = false; + const auto blocker = plugins.on_reloaded([&](std::string_view) { + std::unique_lock lock{gateMutex}; + callbackEntered = true; + gateChanged.notify_all(); + gateChanged.wait(lock, [&] { return releaseCallback; }); + }); + + auto binding = + std::make_unique>( + plugins, registry, "CalcPlugin"); + Void::Testing::expect(binding->bind()); + binding->enable_hot_reload(); + + install(VOID_SERVICE_V2_PATH, so); + std::atomic reloadSucceeded{false}; + std::thread reloader{[&] { + reloadSucceeded.store(plugins.reload("CalcPlugin").has_value(), + std::memory_order_release); + }}; + bool callbackWasObserved = false; + { + std::unique_lock lock{gateMutex}; + callbackWasObserved = gateChanged.wait_for( + lock, std::chrono::seconds{5}, [&] { return callbackEntered; }); + } + binding.reset(); + { + std::lock_guard lock{gateMutex}; + releaseCallback = true; + } + gateChanged.notify_all(); + reloader.join(); + plugins.remove_on_reloaded(blocker); + Void::Testing::expect(callbackWasObserved); + Void::Testing::expect(reloadSucceeded.load(std::memory_order_acquire)); + + auto service = registry.get(); + Void::Testing::expect(service != nullptr); + Void::Testing::expect_eq(service->version(), 1); +} + #endif // service plugins available diff --git a/tests/package/External/CMakeLists.txt b/tests/package/External/CMakeLists.txt new file mode 100644 index 0000000..49f64b1 --- /dev/null +++ b/tests/package/External/CMakeLists.txt @@ -0,0 +1,20 @@ +cmake_minimum_required(VERSION 4.0) +project(VoidExternalConsumer LANGUAGES CXX) + +find_package(Void CONFIG REQUIRED COMPONENTS + Net + Security + Sqlite + Stacktrace +) + +add_executable(void_external_consumer main.cpp) +target_link_libraries(void_external_consumer PRIVATE + Void::Net + Void::Security + Void::Sqlite + Void::Stacktrace +) + +enable_testing() +add_test(NAME VoidExternalConsumer COMMAND void_external_consumer) diff --git a/tests/package/External/main.cpp b/tests/package/External/main.cpp new file mode 100644 index 0000000..3c77660 --- /dev/null +++ b/tests/package/External/main.cpp @@ -0,0 +1,19 @@ +#include +#include +#include +#include + +#include + +int main() +{ + const auto url = Void::Net::Url::parse("https://example.invalid/path"); + const auto token = Void::Security::hash_token("void-consumer-token"); + auto database = Void::Sqlite::Database::open(":memory:"); + const auto frames = Void::Stacktrace::capture_stacktrace(0, 1); + + return url && url->target == "/path" && token && !token->empty() && + database && frames.size() <= 1 + ? 0 + : 1; +} diff --git a/tests/package/InstalledComponents.cmake b/tests/package/InstalledComponents.cmake index a42b8bd..23f439d 100644 --- a/tests/package/InstalledComponents.cmake +++ b/tests/package/InstalledComponents.cmake @@ -54,3 +54,8 @@ run_consumer(Audited -DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE -DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE -DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE) + +# Compiled shared modules keep their third-party implementation dependencies +# private, but every installed runtime library must remain linkable and +# executable from a clean consumer project. +run_consumer(External) diff --git a/tests/standalone/Log/Fields.cpp b/tests/standalone/Log/Fields.cpp index b12e043..a8bf6b2 100644 --- a/tests/standalone/Log/Fields.cpp +++ b/tests/standalone/Log/Fields.cpp @@ -38,7 +38,7 @@ Void::Testing::Test field_scope_nests() FieldScope a{"a", "1"}; { - FieldScope b{{{"b", "2"}, {"c", "3"}}}; + FieldScope b{{"b", "2"}, {"c", "3"}}; log.info("two scopes"); } log.info("one scope"); diff --git a/tests/standalone/ShortUrl/ShortUrl.cpp b/tests/standalone/ShortUrl/ShortUrl.cpp new file mode 100644 index 0000000..faae9ae --- /dev/null +++ b/tests/standalone/ShortUrl/ShortUrl.cpp @@ -0,0 +1,58 @@ +#include +#include +#include + +#include +#include + +namespace +{ + class Shortener final : public Void::ShortUrl::IShortener + { + public: + + [[nodiscard]] std::string_view provider_id() const noexcept override + { + return "test"; + } + + [[nodiscard]] Void::ShortUrl::Health health() const override + { + return {.status = Void::ShortUrl::HealthStatus::healthy}; + } + + [[nodiscard]] Void::ShortUrl::ShortenResult + shorten(const Void::ShortUrl::ShortenRequest& request) override + { + return { + .short_url = "https://sho.rt/s/Ab3dE5fG7h", + .key = "Ab3dE5fG7h", + .expires_at_unix_seconds = request.expires_at_unix_seconds, + }; + } + }; +} // namespace + +Void::Testing::Test short_url_service_contract() +{ + Shortener shortener; + Void::Testing::expect_eq(shortener.service_name(), + Void::ShortUrl::kServiceId); + Void::Testing::expect_eq(shortener.service_version(), std::uint32_t{1}); + Void::Testing::expect_eq(shortener.provider_id(), std::string_view{"test"}); + Void::Testing::expect_eq(shortener.health().status, + Void::ShortUrl::HealthStatus::healthy); + + auto result = shortener.shorten({.target_url = "https://example.com/a"}); + Void::Testing::expect(result.ok()); + Void::Testing::expect_eq(result.key, std::string{"Ab3dE5fG7h"}); +} + +Void::Testing::Test short_url_resolution_is_optional() +{ + Shortener shortener; + auto result = shortener.resolve({.key = "Ab3dE5fG7h"}); + Void::Testing::expect(!result.ok()); + Void::Testing::expect_eq(result.error.code, + Void::ShortUrl::ErrorCode::unsupported); +}