diff --git a/.github/workflows/dmq_latest.yml b/.github/workflows/dmq_latest.yml new file mode 100644 index 0000000..009cc01 --- /dev/null +++ b/.github/workflows/dmq_latest.yml @@ -0,0 +1,36 @@ +name: DelegateMQ latest + +# Builds and tests against DelegateMQ's latest code instead of the pinned +# release (DMQ_GIT_TAG in CMakeLists.txt), so a DelegateMQ change that would +# break this wrapper shows up before the next DelegateMQ release. It only +# reports: pull requests are checked by the pinned-release workflows. + +on: + schedule: + - cron: '0 6 * * 1' # Mondays, 06:00 UTC + workflow_dispatch: + inputs: + dmq_ref: + description: 'DelegateMQ branch or tag to build against' + required: false + default: 'master' + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v7 + + - name: Install libcurl + run: sudo apt-get update && sudo apt-get install -y libcurl4-openssl-dev + + - name: Configure CMake + run: cmake -S . -B build -DDMQ_GIT_TAG=${{ github.event.inputs.dmq_ref || 'master' }} + + - name: Build + run: cmake --build build + + - name: Run Async-HTTPApp + run: ./build/Async-HTTPApp diff --git a/CMakeLists.txt b/CMakeLists.txt index a16550f..7e92c8e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,10 +1,15 @@ # Example CMake command line to create project build files: # -# cmake -B Build . -# cmake -B Build . -DCMAKE_TOOLCHAIN_FILE=/scripts/buildsystems/vcpkg.cmake +# cmake -B build . +# cmake -B build . -DCMAKE_TOOLCHAIN_FILE=/scripts/buildsystems/vcpkg.cmake +# +# DelegateMQ is fetched from GitHub at the release tag DMQ_GIT_TAG when CMake +# configures. To build against a local DelegateMQ checkout instead, add +# -DFETCHCONTENT_SOURCE_DIR_DELEGATEMQ=. To configure again without +# network access, add -DFETCHCONTENT_FULLY_DISCONNECTED=ON. # Specify the minimum CMake version required -cmake_minimum_required(VERSION 3.10) +cmake_minimum_required(VERSION 3.16) # Project name and language project(Async-HTTP VERSION 1.0 LANGUAGES C CXX) @@ -15,7 +20,18 @@ set (DMQ_UTIL "ON") set (DMQ_THREAD "DMQ_THREAD_STDLIB") set (DMQ_SERIALIZE "DMQ_SERIALIZE_NONE") set (DMQ_TRANSPORT "DMQ_TRANSPORT_NONE") -include("${CMAKE_SOURCE_DIR}/DelegateMQ/DelegateMQ.cmake") + +# DelegateMQ release to build against +set(DMQ_GIT_TAG "v2.4.1" CACHE STRING "DelegateMQ release tag (or branch) to fetch") + +include(FetchContent) +FetchContent_Declare( + delegatemq + GIT_REPOSITORY https://github.com/DelegateMQ/DelegateMQ.git + GIT_TAG ${DMQ_GIT_TAG} + GIT_SHALLOW TRUE +) +FetchContent_MakeAvailable(delegatemq) # Set C++ standard set(CMAKE_CXX_STANDARD 17) @@ -27,23 +43,14 @@ find_package(CURL REQUIRED) # Collect all .cpp and *.h source files in the current directory file(GLOB SOURCES "*.cpp" "*.h") -# Collect DelegateMQ predef source files -list(APPEND SOURCES ${DMQ_PORT_SOURCES}) - -# Organize delegate source files within IDE (Visual Studio) -source_group("Delegate Files" FILES ${DMQ_LIB_SOURCES}) -source_group("Port Files" FILES ${DMQ_PORT_ONLY_SOURCES}) -source_group("Extras Files" FILES ${DMQ_EXTRAS_SOURCES}) - # Add subdirectories to include path include_directories( - ${DMQ_ROOT_DIR} HTTP UnitTest ) # Add an executable target -add_executable(Async-HTTPApp ${SOURCES} ${DMQ_LIB_SOURCES}) +add_executable(Async-HTTPApp ${SOURCES}) # Add subdirectories to build add_subdirectory(HTTP) diff --git a/DelegateMQ/Common.cmake b/DelegateMQ/Common.cmake deleted file mode 100644 index b66815b..0000000 --- a/DelegateMQ/Common.cmake +++ /dev/null @@ -1,40 +0,0 @@ -# C++17 minimum. A newer standard the including project already chose (e.g. -# set(CMAKE_CXX_STANDARD 20) before including DelegateMQ.cmake) is kept; an -# older one is raised to 17, which DelegateMQ needs. 98 is listed explicitly -# because it compares as greater than 17. -if(NOT DEFINED CMAKE_CXX_STANDARD OR CMAKE_CXX_STANDARD MATCHES "^(98|11|14)$") - set(CMAKE_CXX_STANDARD 17) - set(CMAKE_CXX_STANDARD_REQUIRED True) -endif() - -# Global silence for MSVC deprecation warnings (Standard for latest compilers) -if (MSVC) - # /utf-8 travels with the dmq_add_library() target too (DelegateMQ headers - # are UTF-8); /MP is a build-speed choice left to the including project. - list(APPEND DMQ_COMPILE_OPTIONS "/utf-8") - if(NOT DMQ_NO_GLOBAL_DEFINITIONS) - add_compile_options("/utf-8") - add_compile_options("/MP") - endif() - set(DMQ_STRICT_FLAGS "/W4" "/WX" "/analyze" "/analyze:external-" "/permissive-" "/Zc:__cplusplus" "/Zc:inline") - dmq_compile_definitions(_SILENCE_STDEXT_ARR_ITERS_DEPRECATION_WARNING) - dmq_compile_definitions(_SILENCE_ALL_MS_EXT_DEPRECATION_WARNINGS) - - # Fix for spdlog bundled fmt in C++20 mode. Kept directory-wide only: these - # change iterator checking for everything they reach, so the - # dmq_add_library() target carries them only when DMQ_LOG pulls in spdlog. - if(NOT DMQ_NO_GLOBAL_DEFINITIONS) - add_compile_definitions(FMT_USE_ITERATOR_TRAITS=1) - add_compile_definitions(FMT_MSVC_CRT_ITERATORS=0) - add_compile_definitions(_SECURE_SCL=0) - endif() - if(DMQ_LOG STREQUAL "ON") - list(APPEND DMQ_COMPILE_DEFINITIONS FMT_USE_ITERATOR_TRAITS=1 FMT_MSVC_CRT_ITERATORS=0 _SECURE_SCL=0) - endif() -else() - # Add -rdynamic to ensure function names are available in stack traces on Linux - set(DMQ_STRICT_FLAGS "-Wall" "-Wextra" "-Werror" "-Wpedantic" "-Wconversion" "-Wshadow" "-rdynamic") -endif() - - - diff --git a/DelegateMQ/Defaults.cmake b/DelegateMQ/Defaults.cmake deleted file mode 100644 index 84df6e2..0000000 --- a/DelegateMQ/Defaults.cmake +++ /dev/null @@ -1,127 +0,0 @@ -# DelegateMQ Defaults -# -# This module auto-selects default DelegateMQ build options based on the target platform. -# Options can be overridden by setting the variables before including DelegateMQ.cmake. - -# Forget the defaults an earlier include in this scope (or a parent's) filled -# in, so a second configuration recomputes them from its own options, e.g. -# DMQ_DATABUS from a new DMQ_THREAD. A value the caller set, or changed since, -# is kept. -foreach(_dmq_var IN LISTS _DMQ_AUTO_DEFAULTS) - if("${${_dmq_var}}" STREQUAL "${_DMQ_AUTO_VALUE_${_dmq_var}}") - unset(${_dmq_var}) - endif() -endforeach() -set(_DMQ_AUTO_DEFAULTS "") - -# --- Threading Defaults --- -if(NOT DEFINED DMQ_THREAD) - list(APPEND _DMQ_AUTO_DEFAULTS DMQ_THREAD) - if(WIN32 OR UNIX) - set(DMQ_THREAD "DMQ_THREAD_STDLIB") - elseif(FREERTOS OR FREE_RTOS) - set(DMQ_THREAD "DMQ_THREAD_FREERTOS") - elseif(THREADX) - set(DMQ_THREAD "DMQ_THREAD_THREADX") - elseif(ZEPHYR) - set(DMQ_THREAD "DMQ_THREAD_ZEPHYR") - elseif(CMSIS_RTOS2) - set(DMQ_THREAD "DMQ_THREAD_CMSIS_RTOS2") - elseif(NUTTX) - set(DMQ_THREAD "DMQ_THREAD_NUTTX") - else() - set(DMQ_THREAD "DMQ_THREAD_NONE") - endif() -endif() - -# --- Transport Defaults --- -if(NOT DEFINED DMQ_TRANSPORT) - list(APPEND _DMQ_AUTO_DEFAULTS DMQ_TRANSPORT) - if(WIN32) - set(DMQ_TRANSPORT "DMQ_TRANSPORT_WIN32_UDP") - elseif(UNIX AND NOT APPLE) - set(DMQ_TRANSPORT "DMQ_TRANSPORT_LINUX_UDP") - else() - set(DMQ_TRANSPORT "DMQ_TRANSPORT_NONE") - endif() -endif() - -# --- Serialization Defaults --- -if(NOT DEFINED DMQ_SERIALIZE) - list(APPEND _DMQ_AUTO_DEFAULTS DMQ_SERIALIZE) - if(WIN32 OR UNIX) - set(DMQ_SERIALIZE "DMQ_SERIALIZE_SERIALIZE") - else() - set(DMQ_SERIALIZE "DMQ_SERIALIZE_NONE") - endif() -endif() - -# --- Utility Class Defaults --- -if(NOT DEFINED DMQ_UTIL) - list(APPEND _DMQ_AUTO_DEFAULTS DMQ_UTIL) - set(DMQ_UTIL "ON") -endif() - -# --- DataBus Defaults --- -# Keyed off DMQ_THREAD (the actual target), not WIN32/UNIX (the host doing -# the compiling) -- DMQ_THREAD is already resolved above, and every RTOS -# simulator sample (freertos-linux, threadx-linux, zephyr-linux) compiles -# with a host GCC on a UNIX box despite targeting an embedded thread port, -# which used to default DMQ_DATABUS on for them too. DataBus's -# NetworkConnect.h reaches for the host's own BSD socket headers -# unconditionally on Linux/macOS/Windows, which both wastes flash on a real -# embedded build and can conflict outright with a target's own native -# network stack headers (e.g. Zephyr's redefining -# sockaddr_in et al.) if a sample also pulls those in directly. RTOS/bare- -# metal targets that genuinely want DataBus (e.g. databus-freertos/server) -# already opt in explicitly by setting DMQ_DATABUS "ON" themselves. -# -# This exclusion list must stay in sync with DelegateSelect.h's -# DMQ_THREAD_IS_EMBEDDED_RTOS macro (FreeRTOS/ThreadX/Zephyr/CMSIS-RTOS2/ -# NuttX) -- adding a new DMQ_THREAD_* port there means adding it here too. -# DMQ_THREAD_NONE (bare metal) is excluded as well: there is no host to -# speak of. -if(NOT DEFINED DMQ_DATABUS) - list(APPEND _DMQ_AUTO_DEFAULTS DMQ_DATABUS) - if(DMQ_THREAD STREQUAL "DMQ_THREAD_FREERTOS" OR DMQ_THREAD STREQUAL "DMQ_THREAD_THREADX" OR - DMQ_THREAD STREQUAL "DMQ_THREAD_ZEPHYR" OR DMQ_THREAD STREQUAL "DMQ_THREAD_CMSIS_RTOS2" OR - DMQ_THREAD STREQUAL "DMQ_THREAD_NUTTX" OR - DMQ_THREAD STREQUAL "DMQ_THREAD_NONE") - set(DMQ_DATABUS "OFF") - else() - set(DMQ_DATABUS "ON") - endif() -endif() - -# --- DataBus Tools Defaults --- -if(NOT DEFINED DMQ_DATABUS_TOOLS) - list(APPEND _DMQ_AUTO_DEFAULTS DMQ_DATABUS_TOOLS) - if(DMQ_DATABUS STREQUAL "ON" AND (WIN32 OR UNIX)) - set(DMQ_DATABUS_TOOLS "ON") - else() - set(DMQ_DATABUS_TOOLS "OFF") - endif() -endif() - -# --- Allocator Defaults --- -if(NOT DEFINED DMQ_ALLOCATOR) - list(APPEND _DMQ_AUTO_DEFAULTS DMQ_ALLOCATOR) - set(DMQ_ALLOCATOR "OFF") -endif() - -# --- Assert Defaults --- -if(NOT DEFINED DMQ_ASSERTS) - list(APPEND _DMQ_AUTO_DEFAULTS DMQ_ASSERTS) - set(DMQ_ASSERTS "OFF") -endif() - -# --- Logging Defaults --- -if(NOT DEFINED DMQ_LOG) - list(APPEND _DMQ_AUTO_DEFAULTS DMQ_LOG) - set(DMQ_LOG "OFF") -endif() - -# Remember what was filled in for the next include (see top of file) -foreach(_dmq_var IN LISTS _DMQ_AUTO_DEFAULTS) - set(_DMQ_AUTO_VALUE_${_dmq_var} "${${_dmq_var}}") -endforeach() diff --git a/DelegateMQ/DelegateMQ.cmake b/DelegateMQ/DelegateMQ.cmake deleted file mode 100644 index 92e007a..0000000 --- a/DelegateMQ/DelegateMQ.cmake +++ /dev/null @@ -1,99 +0,0 @@ -# DelegateMQ cmake module -# -# This module sets the following variables in your project: -# -# DMQ_INCLUDE_DIR - the directory containing DelegateMQ headers. -# DMQ_LIB_SOURCES - the core DelegateMQ delegate library files. -# DMQ_PORT_SOURCES - the predefined supporting source code files -# based on the DMQ build options. -# -# Set DMQ build options: -# -# # Optional: Set DMQ build options to override defaults. -# set(DMQ_THREAD "DMQ_THREAD_STDLIB") -# include("${CMAKE_SOURCE_DIR}/src/delegate-mq/DelegateMQ.cmake") -# -# Use variables to build: -# -# # Collect DelegateMQ port/extras source files -# list(APPEND SOURCES ${DMQ_PORT_SOURCES}) -# -# # Add include directory -# include_directories(${DMQ_INCLUDE_DIR}) -# -# Or build a library target that carries the options with it: -# -# dmq_add_library(dmq) -# target_link_libraries(my_app PRIVATE dmq) -# -# DMQ_COMPILE_DEFINITIONS, DMQ_COMPILE_OPTIONS, DMQ_EXTERNAL_INCLUDE_DIRS and -# DMQ_LINK_LIBRARIES hold that target's usage requirements. Definitions are -# also applied directory-wide (add_compile_definitions) unless -# DMQ_NO_GLOBAL_DEFINITIONS is set before the include. -# -# DMQ_USER_CONFIG - optional user config header name (e.g. "DelegateMQConfig.h") -# DMQ_USER_CONFIG_DIR - optional directory holding it, added to the target's includes - -macro(check _file) - if(NOT EXISTS "${_file}") - message(FATAL_ERROR "File or directory ${_file} referenced by variable ${_var} does not exist!") - endif() -endmacro() - -macro(set_and_check _var _file) - set(${_var} "${_file}") - check("${_file}") -endmacro() - -# Reset per include so each configuration in one build tree starts clean. -set(DMQ_COMPILE_DEFINITIONS "") -set(DMQ_COMPILE_OPTIONS "") - -set_and_check(DMQ_ROOT_DIR "${CMAKE_CURRENT_LIST_DIR}") -set_and_check(DMQ_INCLUDE_DIR "${DMQ_ROOT_DIR}") - -# DMQ_DEPS_DIR: third-party repos fetched by 01_fetch_repos.py -check("${DMQ_ROOT_DIR}/DepsDir.cmake") -include ("${DMQ_ROOT_DIR}/DepsDir.cmake") - -check("${DMQ_ROOT_DIR}/Defaults.cmake") -include ("${DMQ_ROOT_DIR}/Defaults.cmake") - -check("${DMQ_ROOT_DIR}/Macros.cmake") -include ("${DMQ_ROOT_DIR}/Macros.cmake") - -check("${DMQ_ROOT_DIR}/Common.cmake") -include ("${DMQ_ROOT_DIR}/Common.cmake") - -check("${DMQ_ROOT_DIR}/Port.cmake") -include ("${DMQ_ROOT_DIR}/Port.cmake") - -check("${DMQ_ROOT_DIR}/External.cmake") -include ("${DMQ_ROOT_DIR}/External.cmake") - -if(DMQ_USER_CONFIG) - # Accept the name with or without surrounding quotes (-DDMQ_USER_CONFIG=\"x.h\") - string(REGEX REPLACE "^\"(.*)\"$" "\\1" _dmq_user_config "${DMQ_USER_CONFIG}") - dmq_compile_definitions(DMQ_USER_CONFIG="${_dmq_user_config}") -endif() - -if(DMQ_FORCE_OPTIMIZE_DEBUG) - dmq_compile_definitions(DMQ_FORCE_OPTIMIZE_DEBUG) -endif() - -# New option (Default OFF) -option(DMQ_STRICT "Enable strict DelegateMQ compiler warnings and errors" OFF) - -if (DMQ_STRICT) - message(STATUS "DelegateMQ: Strict build enabled (${DMQ_STRICT_FLAGS})") - - # Apply strict compile flags only to DelegateMQ source files - set_source_files_properties(${DMQ_LIB_SOURCES} ${DMQ_PORT_SOURCES} PROPERTIES COMPILE_OPTIONS "${DMQ_STRICT_FLAGS}") - - # On MSVC, different warning levels cause a PCH mismatch error (C4652). - # We disable PCH for these specific files to allow strict checking without affecting the whole target. - if (MSVC) - set_source_files_properties(${DMQ_LIB_SOURCES} ${DMQ_PORT_SOURCES} PROPERTIES COMPILE_FLAGS "/Y-") - endif() -endif() - diff --git a/DelegateMQ/DelegateMQ.h b/DelegateMQ/DelegateMQ.h deleted file mode 100644 index ccabfc8..0000000 --- a/DelegateMQ/DelegateMQ.h +++ /dev/null @@ -1,297 +0,0 @@ -#ifndef _DELEGATE_MQ_H -#define _DELEGATE_MQ_H - -// Delegate.h -// @see https://github.com/DelegateMQ/DelegateMQ -// David Lafreniere, 2025. - -/// @file DelegateMQ.h -/// @brief A single-include header for the complete DelegateMQ library functionality. -/// -/// @details -/// DelegateMQ is a robust C++ delegate library that enables invoking any callable function -/// (synchronously or asynchronously) on a specific user-defined thread of control. It also -/// supports remote function invocation over any transport protocol. -/// -/// **Key Features:** -/// * **Universal Target Support:** Binds to free functions, class member functions, static functions, -/// lambdas, and `std::function`. -/// * **Any Signature:** Handles any function signature with any number of arguments or return values. -/// * **Argument Safety:** Supports all argument types (value, pointer, pointer-to-pointer, reference) -/// and safely marshals them across thread boundaries for asynchronous calls. -/// * **Thread Control:** Unlike `std::async` (which uses a random thread pool), DelegateMQ executes -/// the target function on a *specific* destination thread you control. -/// * **Remote Invocation:** Capable of serializing arguments and invoking functions across network -/// boundaries (UDP, TCP, ZeroMQ, etc.). -/// -/// **Delegate Capabilities:** -/// A delegate instance behaves like a first-class object: -/// * **Copyable:** Can be copied freely. -/// * **Comparable:** Supports equality checks against other delegates or `nullptr`. -/// * **Assignable:** Can be reassigned at runtime. -/// * **Callable:** Invoked via `operator()`. -/// -/// **Common Use Cases:** -/// * Asynchronous Method Invocation (AMI) on specific worker threads. -/// * Publish / Subscribe (Observer) patterns. -/// * Anonymous, thread-safe asynchronous callbacks. -/// * Event-Driven Programming architectures. -/// * Thread-Safe Asynchronous APIs. -/// * Active Object design patterns. -/// -/// **Asynchronous Safety:** -/// Asynchronous variants automatically copy argument data into the event queue. This provides true -/// 'fire and forget' functionality, ensuring that out-of-scope stack variables in the caller -/// do not cause data races or corruption in the target thread. -/// -/// **Error Handling:** -/// The `Async` and `AsyncWait` variants may throw `std::bad_alloc` if heap allocation fails during -/// invocation. Alternatively, defining `DMQ_ASSERTS` switches error handling to assertions. -/// All other delegate functions are `noexcept`. -/// -/// **Documentation & Source:** -/// * Repository: https://github.com/DelegateMQ/DelegateMQ -/// * See `README.md`, `DETAILS.md`, and `EXAMPLES.md` for comprehensive guides. - -// ----------------------------------------------------------------------------- -// 0. Platform Configuration -// ----------------------------------------------------------------------------- -#if defined(_WIN32) || defined(_WIN64) - #ifndef WIN32_LEAN_AND_MEAN - #define WIN32_LEAN_AND_MEAN - #endif - #ifndef NOMINMAX - #define NOMINMAX - #endif -#endif - -// ----------------------------------------------------------------------------- -// 1. Core Non-Thread-Safe Delegates -// (Always available: Bare Metal, FreeRTOS, Windows, Linux) -// ----------------------------------------------------------------------------- -#include "delegate/Delegate.h" -#include "delegate/DelegateRemote.h" -#include "delegate/MulticastDelegate.h" -#include "delegate/UnicastDelegate.h" -#include "delegate/Signal.h" - -// ----------------------------------------------------------------------------- -// 2. Thread-Safe Wrappers (Mutex Only) -// ----------------------------------------------------------------------------- -// - FreeRTOS: Uses FreeRTOSRecursiveMutex -// - Bare Metal: Uses NullMutex -// - StdLib: Uses std::recursive_mutex -// Valid for any platform where a Mutex is defined in DelegateOpt.h -#if defined(DMQ_THREAD_STDLIB) || \ - defined(DMQ_THREAD_WIN32) || \ - defined(DMQ_THREAD_POSIX) || \ - defined(DMQ_THREAD_FREERTOS) || \ - defined(DMQ_THREAD_THREADX) || \ - defined(DMQ_THREAD_ZEPHYR) || \ - defined(DMQ_THREAD_CMSIS_RTOS2) || \ - defined(DMQ_THREAD_NUTTX) || \ - defined(DMQ_THREAD_QT) || \ - defined(DMQ_THREAD_NONE) - #include "delegate/MulticastDelegateSafe.h" - #include "delegate/UnicastDelegateSafe.h" -#endif - -// ----------------------------------------------------------------------------- -// 3. Asynchronous "Fire and Forget" Delegates -// ----------------------------------------------------------------------------- -// - FreeRTOS: OK -// - Bare Metal: OK (Requires you to implement IThread wrapper for Event Loop) -// - StdLib / Win32: OK -// Valid for any platform that implements the IThread interface -#if defined(DMQ_THREAD_STDLIB) || \ - defined(DMQ_THREAD_WIN32) || \ - defined(DMQ_THREAD_POSIX) || \ - defined(DMQ_THREAD_FREERTOS) || \ - defined(DMQ_THREAD_THREADX) || \ - defined(DMQ_THREAD_ZEPHYR) || \ - defined(DMQ_THREAD_CMSIS_RTOS2) || \ - defined(DMQ_THREAD_NUTTX) || \ - defined(DMQ_THREAD_QT) - #include "delegate/DelegateAsync.h" -#endif - -// ----------------------------------------------------------------------------- -// 4. Asynchronous "Blocking" Delegates (Wait for Result) -// ----------------------------------------------------------------------------- -// Depends on Semaphore/Mutex and C++17 (std::optional). -// Valid for StdLib/Win32 (Windows/Linux), Qt, ThreadX, FreeRTOS (if C++17 -// enabled), Zephyr, and CMSIS-RTOS2 -- the latter two via their native -// k_sem/osSemaphore-backed dmq::Semaphore, not the generic condvar+mutex -// implementation. DMQ_HAS_SEMAPHORE (DelegateOpt.h) is defined for exactly -// this set of ports, so it's used directly here instead of hand-copying the -// port list again. -#if defined(DMQ_HAS_SEMAPHORE) - #include "delegate/DelegateAsyncWait.h" -#endif - -#if defined(DMQ_THREAD_STDLIB) - #include "port/os/stdlib/StdlibThread.h" - #include "port/os/common/ThreadMsg.h" -#elif defined(DMQ_THREAD_WIN32) - #include "port/os/win32/Win32Thread.h" - #include "port/os/common/ThreadMsg.h" -#elif defined(DMQ_THREAD_POSIX) - #include "port/os/posix/PosixThread.h" - #include "port/os/common/ThreadMsg.h" -#elif defined(DMQ_THREAD_FREERTOS) - #include "port/os/freertos/FreeRTOSThread.h" - #include "port/os/common/ThreadMsg.h" -#elif defined(DMQ_THREAD_THREADX) - #include "port/os/threadx/ThreadXThread.h" - #include "port/os/common/ThreadMsg.h" -#elif defined(DMQ_THREAD_ZEPHYR) - #include "port/os/zephyr/ZephyrThread.h" - #include "port/os/common/ThreadMsg.h" -#elif defined(DMQ_THREAD_CMSIS_RTOS2) - #include "port/os/cmsis-rtos2/CmsisRtos2Thread.h" - #include "port/os/common/ThreadMsg.h" -#elif defined(DMQ_THREAD_NUTTX) - #include "port/os/nuttx/NuttXThread.h" - #include "port/os/common/ThreadMsg.h" -#elif defined(DMQ_THREAD_QT) - #include "port/os/qt/QtThread.h" - #include "port/os/common/ThreadMsg.h" -#elif defined(DMQ_THREAD_NONE) - // Bare metal: User must implement their own polling/interrupt logic -#else - #warning "Thread implementation not found." - #define DMQ_THREAD_NONE -#endif - -#if defined(DMQ_SERIALIZE_MSGPACK) - #include "port/serialize/msgpack/MsgpackSerializer.h" -#elif defined(DMQ_SERIALIZE_CEREAL) - #include "port/serialize/cereal/CerealSerializer.h" -#elif defined(DMQ_SERIALIZE_BITSERY) - #include "port/serialize/bitsery/BitserySerializer.h" -#elif defined(DMQ_SERIALIZE_RAPIDJSON) - #include "port/serialize/rapidjson/RapidJsonSerializer.h" -#elif defined(DMQ_SERIALIZE_SERIALIZE) - #include "port/serialize/serialize/DmqSerializer.h" -#elif defined(DMQ_SERIALIZE_NONE) - // Create a custom application-specific serializer -#else - #warning "Serialize implementation not found." -#endif - -#if defined(DMQ_TRANSPORT_ZEROMQ) - #include "extras/dispatcher/Dispatcher.h" - #include "port/transport/zeromq/ZeroMqTransport.h" -#elif defined(DMQ_TRANSPORT_NNG) - #include "extras/dispatcher/Dispatcher.h" - #include "port/transport/nng/NngTransport.h" -#elif defined(DMQ_TRANSPORT_WIN32_PIPE) - #include "extras/dispatcher/Dispatcher.h" - #include "port/transport/win32-pipe/Win32PipeTransport.h" -#elif defined(DMQ_TRANSPORT_WIN32_UDP) - #include "extras/dispatcher/Dispatcher.h" - #include "port/transport/win32-udp/Win32UdpTransport.h" - #include "port/transport/win32-udp/MulticastTransport.h" -#elif defined(DMQ_TRANSPORT_WIN32_TCP) - #include "extras/dispatcher/Dispatcher.h" - #include "port/transport/win32-tcp/Win32TcpTransport.h" -#elif defined(DMQ_TRANSPORT_LINUX_UDP) - #include "extras/dispatcher/Dispatcher.h" - #include "port/transport/linux-udp/LinuxUdpTransport.h" - #include "port/transport/linux-udp/MulticastTransport.h" -#elif defined(DMQ_TRANSPORT_LINUX_UDS) - #include "extras/dispatcher/Dispatcher.h" - #include "port/transport/linux-uds/LinuxUdsTransport.h" -#elif defined(DMQ_TRANSPORT_LINUX_TCP) - #include "extras/dispatcher/Dispatcher.h" - #include "port/transport/linux-tcp/LinuxTcpTransport.h" -#elif defined(DMQ_TRANSPORT_MQTT) - #include "extras/dispatcher/Dispatcher.h" - #include "port/transport/mqtt/MqttTransport.h" -#elif defined(DMQ_TRANSPORT_SERIAL_PORT) - #include "extras/dispatcher/Dispatcher.h" - #include "port/transport/serial/SerialTransport.h" -#elif defined(DMQ_TRANSPORT_ARM_LWIP_UDP) - #include "extras/dispatcher/Dispatcher.h" - #include "port/transport/arm-lwip-udp/ArmLwipUdpTransport.h" -#elif defined(DMQ_TRANSPORT_ARM_LWIP_NETCONN_UDP) - #include "extras/dispatcher/Dispatcher.h" - #include "port/transport/arm-lwip-netconn-udp/ArmLwipNetconnUdpTransport.h" -#elif defined(DMQ_TRANSPORT_THREADX_UDP) - #include "extras/dispatcher/Dispatcher.h" - #include "port/transport/netx-udp/NetXUdpTransport.h" -#elif defined(DMQ_TRANSPORT_STM32_UART) - #include "extras/dispatcher/Dispatcher.h" - #include "port/transport/stm32-uart/Stm32UartTransport.h" -#elif defined(DMQ_TRANSPORT_ZEPHYR_UDP) - #include "extras/dispatcher/Dispatcher.h" - #include "port/transport/zephyr-udp/ZephyrUdpTransport.h" -#elif defined(DMQ_TRANSPORT_NONE) - // No built-in transport. Include the interface and dispatcher so application code - // can implement a custom ITransport and use RemoteChannel with a mock or stub. - #include "extras/dispatcher/Dispatcher.h" - #include "port/transport/common/ITransport.h" -#else - #warning "Transport implementation not found." -#endif - -// Include RemoteChannel whenever Dispatcher.h has been included (all transport -// configurations including NONE, where a mock ITransport can be supplied). -// RemoteChannel aggregates dispatcher, serializer, and stream into one object, -// mirroring how Thread aggregates async delegate wiring behind a single IThread. -#if defined(DMQ_TRANSPORT_ZEROMQ) || defined(DMQ_TRANSPORT_NNG) || \ - defined(DMQ_TRANSPORT_WIN32_PIPE) || defined(DMQ_TRANSPORT_WIN32_UDP) || \ - defined(DMQ_TRANSPORT_WIN32_TCP) || defined(DMQ_TRANSPORT_LINUX_UDP) || \ - defined(DMQ_TRANSPORT_LINUX_TCP) || defined(DMQ_TRANSPORT_LINUX_UDS) || \ - defined(DMQ_TRANSPORT_MQTT) || \ - defined(DMQ_TRANSPORT_SERIAL_PORT) || defined(DMQ_TRANSPORT_ARM_LWIP_UDP) || \ - defined(DMQ_TRANSPORT_ARM_LWIP_NETCONN_UDP) || defined(DMQ_TRANSPORT_THREADX_UDP) || \ - defined(DMQ_TRANSPORT_STM32_UART) || defined(DMQ_TRANSPORT_ZEPHYR_UDP) || \ - defined(DMQ_TRANSPORT_NONE) - #include "extras/dispatcher/RemoteChannel.h" -#endif - -#include "extras/util/Fault.h" -#include "extras/util/ClockHelper.h" - -// Timer only needs dmq::Clock/dmq::CriticalSection (both of which the -// bare-metal port -- BareMetalClock.h/BareMetalCriticalSection.h -- provides -// specifically so Timer::ProcessTimers() can be driven from a hardware ISR -// with no RTOS at all, e.g. a SysTick_Handler; see BareMetalCriticalSection.h's -// own doc comment). It has no dependency on dmq::os::Thread, so it's -// available even under DMQ_THREAD_NONE. -#include "extras/util/Timer.h" - -// TimerDelegate/AsyncInvoke/TransportMonitor/ThreadMonitor/RetryMonitor/ -// ReliableTransport/RemoteDispatcher all take or operate on a dmq::IThread& -// (RetryMonitor/ReliableTransport indirectly, via TransportMonitor), which -// doesn't exist under DMQ_THREAD_NONE. -// RetryMonitor/ReliableTransport are listed explicitly here as first-class -// extras/util components usable directly with Participant/DataBus, independent -// of RemoteDispatcher -- the old NetworkEngine used to pull both in as a side -// effect of its own per-transport #include block, which any DelegateMQ.h -// consumer (not just RPC users) could end up silently depending on. That -// implicit path is gone now that RemoteDispatcher itself no longer knows about -// ReliableTransport (only RetryMonitor, for AttachRetryMonitor()'s signature), -// so both are pulled in explicitly instead. RemoteDispatcher itself no longer -// depends on which transport (if any) is selected -- it only ever sees -// dmq::transport::ITransport -- so unlike the old NetworkEngine it needs no -// DMQ_TRANSPORT_* guard here. -#if !defined(DMQ_THREAD_NONE) - #include "extras/util/TimerDelegate.h" - #include "extras/util/AsyncInvoke.h" - #include "extras/util/TransportMonitor.h" - #include "extras/util/ThreadMonitor.h" - #include "extras/util/RetryMonitor.h" - #include "extras/util/ReliableTransport.h" - #include "extras/rpc/RemoteDispatcher.h" -#endif - -#if defined(DMQ_DATABUS) - #include "extras/databus/DataBus.h" - #include "extras/databus/Participant.h" - #include "extras/databus/DeadlineSubscription.h" -#endif - - -#endif diff --git a/DelegateMQ/DepsDir.cmake b/DelegateMQ/DepsDir.cmake deleted file mode 100644 index 8ff2fef..0000000 --- a/DelegateMQ/DepsDir.cmake +++ /dev/null @@ -1,25 +0,0 @@ -# DepsDir.cmake -# Resolves DMQ_DEPS_DIR: the directory holding the third-party repos fetched by -# 01_fetch_repos.py (zeromq, nng, mqtt, msgpack-c, FreeRTOS, ftxui, ...). -# -# Order: -# 1. -DDMQ_DEPS_DIR= on the cmake command line -# 2. DMQ_DEPS_DIR environment variable -# 3. /external (the default, gitignored) -# -# Included by DelegateMQ.cmake. Build files that need a dependency before -# including DelegateMQ.cmake can include this file directly. -# -# No include_guard: CMake variables are directory-scoped, so a project that -# includes DelegateMQ.cmake from several subdirectories needs DMQ_DEPS_DIR set -# in each of them. - -if(NOT DMQ_DEPS_DIR AND DEFINED ENV{DMQ_DEPS_DIR}) - set(DMQ_DEPS_DIR "$ENV{DMQ_DEPS_DIR}") -endif() - -if(NOT DMQ_DEPS_DIR) - set(DMQ_DEPS_DIR "${CMAKE_CURRENT_LIST_DIR}/../../external") -endif() - -get_filename_component(DMQ_DEPS_DIR "${DMQ_DEPS_DIR}" ABSOLUTE) diff --git a/DelegateMQ/External.cmake b/DelegateMQ/External.cmake deleted file mode 100644 index 2c197dd..0000000 --- a/DelegateMQ/External.cmake +++ /dev/null @@ -1,459 +0,0 @@ -include(CMakeFindDependencyMacro) - -# Previously, this checked if "${_var}" (the variable name) existed as a file. -# Now it correctly checks "${_file}" (the actual path). -macro(set_and_check _var _file) - set(${_var} "${_file}") - if(NOT EXISTS "${_file}") - message(FATAL_ERROR "File or directory ${_file} referenced by variable ${_var} does not exist!") - endif() -endmacro() - -# Outputs below are only set for the selected ports; clear what an earlier -# include in this scope (or a parent's) may have left. -foreach(_dmq_var FREERTOS_SOURCES FREERTOS_LIBRARIES THREADX_LIBRARIES LWIP_SOURCES NETX_SOURCES) - set(${_dmq_var} "") -endforeach() - -# --------------------------------------------------------------------------- -# ZeroMQ library package -# --------------------------------------------------------------------------- -if(DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_ZEROMQ") - set(ZMQ_ROOT "${DMQ_DEPS_DIR}/zeromq/install") - list(APPEND CMAKE_PREFIX_PATH "${ZMQ_ROOT}") - - find_package(ZeroMQ CONFIG REQUIRED) - - if (ZeroMQ_FOUND) - message(STATUS "ZeroMQ found: ${ZeroMQ_VERSION}") - if(TARGET libzmq-static AND NOT TARGET libzmq) - add_library(libzmq ALIAS libzmq-static) - endif() - dmq_compile_definitions(ZMQ_STATIC) - else() - message(FATAL_ERROR "ZeroMQ not found in ${ZMQ_ROOT}") - endif() -endif() - -# --------------------------------------------------------------------------- -# NNG library -# --------------------------------------------------------------------------- -if(DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_NNG") - if(CMAKE_SYSTEM_NAME STREQUAL "Windows") - # Fixed: Point to the 'install' folder where headers actually live after build - set_and_check(NNG_INCLUDE_DIR "${DMQ_DEPS_DIR}/nng/install/include") - set_and_check(NNG_LIBRARY_DIR "${DMQ_DEPS_DIR}/nng/install/lib") - elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux") - # The copy 02_build_libs.py installs under DMQ_DEPS_DIR, as on Windows. - # Set -DDMQ_NNG_PREFIX= to use another install (e.g. /usr/local). - if(DMQ_NNG_PREFIX) - set(_dmq_nng_prefix "${DMQ_NNG_PREFIX}") - else() - set(_dmq_nng_prefix "${DMQ_DEPS_DIR}/nng/install") - endif() - set_and_check(NNG_INCLUDE_DIR "${_dmq_nng_prefix}/include") - if(EXISTS "${_dmq_nng_prefix}/lib64" AND NOT EXISTS "${_dmq_nng_prefix}/lib") - set_and_check(NNG_LIBRARY_DIR "${_dmq_nng_prefix}/lib64") # some distros' GNUInstallDirs - else() - set_and_check(NNG_LIBRARY_DIR "${_dmq_nng_prefix}/lib") - endif() - endif() -endif() - -# --------------------------------------------------------------------------- -# MQTT C library -# --------------------------------------------------------------------------- -if(DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_MQTT") - # Define root relative to DelegateMQ source - set(MQTT_ROOT "${DMQ_DEPS_DIR}/mqtt") - - if(CMAKE_SYSTEM_NAME STREQUAL "Windows") - # 1. Headers - # Note: If 'install' step wasn't run, headers might be in "${MQTT_ROOT}/src" - set_and_check(MQTT_INCLUDE_DIR "${MQTT_ROOT}/install/include") - - # 2. Library (Lib) Directory (for linking) - # Point to build/src where the .lib files are generated - set(MQTT_LIBRARY_DIR "${MQTT_ROOT}/build/src") - - # 3. Binary (DLL) Directory (for runtime copy) - # Point to build/src where the .dll files are generated - set(MQTT_BINARY_DIR "${MQTT_ROOT}/build/src") - - # Fallback for manual definition if needed - set(MQTT_LIBRARY - "${MQTT_LIBRARY_DIR}/paho-mqtt3c.lib" - "ws2_32" "Rpcrt4" "Crypt32" - ) - elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux") - # The copy 02_build_libs.py installs under DMQ_DEPS_DIR, as on Windows. - # Set -DDMQ_MQTT_PREFIX= to use another install (e.g. /usr/local). - if(DMQ_MQTT_PREFIX) - set(_dmq_mqtt_prefix "${DMQ_MQTT_PREFIX}") - else() - set(_dmq_mqtt_prefix "${MQTT_ROOT}/install") - endif() - set_and_check(MQTT_INCLUDE_DIR "${_dmq_mqtt_prefix}/include") - if(EXISTS "${_dmq_mqtt_prefix}/lib64" AND NOT EXISTS "${_dmq_mqtt_prefix}/lib") - set(MQTT_LIBRARY_DIR "${_dmq_mqtt_prefix}/lib64") # some distros' GNUInstallDirs - else() - set(MQTT_LIBRARY_DIR "${_dmq_mqtt_prefix}/lib") - endif() - set_and_check(MQTT_LIBRARY "${MQTT_LIBRARY_DIR}/libpaho-mqtt3c.so") - set(MQTT_BINARY_DIR "${_dmq_mqtt_prefix}/bin") # used only for the Windows DLL copy - endif() -endif() - -# --------------------------------------------------------------------------- -# libserialport library -# --------------------------------------------------------------------------- -if(DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_SERIAL_PORT") - set(SERIALPORT_ROOT "${DMQ_DEPS_DIR}/libserialport") - - if(CMAKE_SYSTEM_NAME STREQUAL "Windows") - # 1. Header: Found in the root of the source folder (libserialport.h) - set_and_check(SERIALPORT_INCLUDE_DIR "${SERIALPORT_ROOT}") - - # 2. Library: Found in the Visual Studio build output folder - # Note: Change 'Debug' to 'Release' if building in Release mode - set_and_check(SERIALPORT_LIBRARY_DIR "${SERIALPORT_ROOT}/x64/Debug") - - elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux") - # 1. Header: Found in the root of the source folder - set_and_check(SERIALPORT_INCLUDE_DIR "${SERIALPORT_ROOT}") - - # 2. Library: Found in the local build directory - # Standard Autotools builds (./configure && make) place .so files in the hidden .libs/ directory - if(EXISTS "${SERIALPORT_ROOT}/.libs") - set_and_check(SERIALPORT_LIBRARY_DIR "${SERIALPORT_ROOT}/.libs") - else() - # Fallback: Check root if built differently - set_and_check(SERIALPORT_LIBRARY_DIR "${SERIALPORT_ROOT}") - endif() - endif() -endif() - -# --------------------------------------------------------------------------- -# lwIP library (For ARM/Embedded) -# --------------------------------------------------------------------------- -if(DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_ARM_LWIP_UDP" OR DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_ARM_LWIP_NETCONN_UDP") - - # Adjust this path if your lwIP root is different - set(LWIP_ROOT "${DMQ_DEPS_DIR}/lwip") - - # lwIP requires 3 main include directories for the socket API - set_and_check(LWIP_INCLUDE_DIR_1 "${LWIP_ROOT}/src/include") - set_and_check(LWIP_INCLUDE_DIR_2 "${LWIP_ROOT}/src/include/ipv4") - - # Often required for lwipopts.h or arch/cc.h. - # NOTE: You may need to customize this depending on where your project keeps 'lwipopts.h' - set(LWIP_INCLUDE_DIR_3 "${LWIP_ROOT}/contrib/ports/unix/port/include") - - set(LWIP_INCLUDE_DIRS - "${LWIP_INCLUDE_DIR_1}" - "${LWIP_INCLUDE_DIR_2}" - "${LWIP_INCLUDE_DIR_3}" - ) - - # Collect core lwIP sources - file(GLOB_RECURSE LWIP_SOURCES - "${LWIP_ROOT}/src/core/*.c" - "${LWIP_ROOT}/src/api/*.c" - "${LWIP_ROOT}/src/netif/*.c" - ) -endif() - -# --------------------------------------------------------------------------- -# NetX / NetX Duo library (For ThreadX) -# --------------------------------------------------------------------------- -if(DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_THREADX_UDP") - # Adjust this path to your NetX / NetX Duo root - set(NETX_ROOT "${DMQ_DEPS_DIR}/netxduo") - - # Verify root - set_and_check(NETX_INCLUDE_DIR "${NETX_ROOT}/common/inc") - - # Collect common sources - file(GLOB NETX_SOURCES - "${NETX_ROOT}/common/src/*.c" - "${NETX_ROOT}/common/inc/*.h" - ) - - # Note: Architecture-specific ports usually handled by your main ThreadX build system -endif() - -# --------------------------------------------------------------------------- -# MessagePack -# --------------------------------------------------------------------------- -if(DMQ_SERIALIZE STREQUAL "DMQ_SERIALIZE_MSGPACK") - dmq_compile_definitions(MSGPACK_NO_BOOST) - set_and_check(MSGPACK_INCLUDE_DIR "${DMQ_DEPS_DIR}/msgpack-c/include") -endif() - -# --------------------------------------------------------------------------- -# Cereal -# --------------------------------------------------------------------------- -if(DMQ_SERIALIZE STREQUAL "DMQ_SERIALIZE_CEREAL") - set_and_check(CEREAL_INCLUDE_DIR "${DMQ_DEPS_DIR}/cereal/include") -endif() - -# --------------------------------------------------------------------------- -# Bitsery -# --------------------------------------------------------------------------- -if(DMQ_SERIALIZE STREQUAL "DMQ_SERIALIZE_BITSERY") - set_and_check(BITSERY_INCLUDE_DIR "${DMQ_DEPS_DIR}/bitsery/include") -endif() - -# --------------------------------------------------------------------------- -# RapidJSON -# --------------------------------------------------------------------------- -if(DMQ_SERIALIZE STREQUAL "DMQ_SERIALIZE_RAPIDJSON") - set_and_check(RAPIDJSON_INCLUDE_DIR "${DMQ_DEPS_DIR}/rapidjson/include") - - # Globally silence C++17 std::iterator warnings on RapidJSON library - if(MSVC) - dmq_compile_definitions(_SILENCE_CXX17_ITERATOR_BASE_CLASS_DEPRECATION_WARNING) - endif() -endif() - -# --------------------------------------------------------------------------- -# FreeRTOS -# --------------------------------------------------------------------------- -if(DMQ_THREAD STREQUAL "DMQ_THREAD_FREERTOS") - set_and_check(FREERTOS_ROOT_DIR "${DMQ_DEPS_DIR}/FreeRTOS") - - file(GLOB FREERTOS_SOURCES - "${FREERTOS_ROOT_DIR}/*.c" - "${FREERTOS_ROOT_DIR}/include/*.h" - ) - - # A cross-compiled hardware target selects its own port (e.g. - # set(FREERTOS_PORT_DIR "GCC/ARM_CM4F")) before including DelegateMQ.cmake; - # otherwise the host simulator port is chosen. - if(DEFINED FREERTOS_PORT_DIR) - # Caller-selected port - elseif(WIN32) - set(FREERTOS_PORT_DIR "MSVC-MingW") - elseif(APPLE) - set(FREERTOS_PORT_DIR "ThirdParty/GCC/Posix") - elseif(UNIX) - set(FREERTOS_PORT_DIR "ThirdParty/GCC/Posix") - else() - message(FATAL_ERROR "DelegateMQ: Unsupported OS for FreeRTOS simulation. " - "For a hardware target, set FREERTOS_PORT_DIR (e.g. GCC/ARM_CM4F).") - endif() - - if(NOT DEFINED FREERTOS_HEAP) - set(FREERTOS_HEAP "heap_5") - endif() - - list(APPEND FREERTOS_SOURCES - "${FREERTOS_ROOT_DIR}/portable/${FREERTOS_PORT_DIR}/port.c" - "${FREERTOS_ROOT_DIR}/portable/MemMang/${FREERTOS_HEAP}.c" - ) - - if(UNIX AND NOT APPLE AND FREERTOS_PORT_DIR STREQUAL "ThirdParty/GCC/Posix") - file(GLOB POSIX_UTILS "${FREERTOS_ROOT_DIR}/portable/${FREERTOS_PORT_DIR}/utils/*.c") - list(APPEND FREERTOS_SOURCES ${POSIX_UTILS}) - set(FREERTOS_LIBRARIES pthread rt) - endif() -endif() - -# --------------------------------------------------------------------------- -# ThreadX -# --------------------------------------------------------------------------- -if(DMQ_THREAD STREQUAL "DMQ_THREAD_THREADX") - set_and_check(THREADX_ROOT_DIR "${DMQ_DEPS_DIR}/threadx") - - # ThreadX ships its own top-level CMakeLists.txt, which builds a real - # "azrtos::threadx" target from THREADX_ARCH / THREADX_TOOLCHAIN. We link - # against that instead of hand-globbing sources (unlike the FreeRTOS case - # above, which has no such CMake integration). - # - # Deliberately NOT using ThreadX's own cmake/linux.cmake toolchain file: - # it forces -fno-exceptions -fno-rtti build-wide, which would fight the - # desktop exception-based error path (DelegateOpt.h auto-switches to - # DMQ_ASSERTS only when the compiler itself lacks exception support). - if(UNIX AND NOT APPLE) - if(NOT DEFINED THREADX_ARCH) - set(THREADX_ARCH "linux") - endif() - if(NOT DEFINED THREADX_TOOLCHAIN) - set(THREADX_TOOLCHAIN "gnu") - endif() - - # Guard against add_subdirectory() being reached more than once in the - # same top-level CMake project -- e.g. two executables (Cellutron's - # controller and safety nodes) each including DelegateMQ.cmake with - # DMQ_THREAD_THREADX. The "threadx" target, once created, is visible - # project-wide, so every caller after the first just reuses it; without - # this guard the second add_subdirectory() call fails outright (CMake - # refuses to bind the same source directory to a second binary - # directory, and a plain unique-binary-dir fix would still collide on - # the "threadx" target name itself). - if(NOT TARGET threadx) - add_subdirectory("${THREADX_ROOT_DIR}" "${CMAKE_BINARY_DIR}/threadx_build") - endif() - - # ThreadX's own ports/linux/gnu/CMakeLists.txt unconditionally adds - # -DTX_LINUX_DEBUG_ENABLE as a PUBLIC compile definition on the - # "threadx" target. That macro wraps every TX_DISABLE/TX_RESTORE - # kernel-wide (see tx_port.h) in a call to _tx_linux_debug_entry_insert(), - # which serializes through one global mutex (_tx_linux_mutex) -- a real - # risk under genuine multi-thread contention. Stripped here rather - # than patching the vendored ThreadX source, so 01_fetch_repos.py can - # still pull a clean, unmodified ThreadX tree. - # - # Not a fix for the threadx-linux two-worker-thread deadlock (see - # example/sample-projects/threadx-linux/DelegateThreadsTests.cpp) -- - # that hang reproduces identically with this macro stripped, still - # blocked on _tx_linux_mutex via plain _tx_thread_interrupt_control(). - # ThreadX's CMakeLists.txt passes both defines as one combined string - # ("-D_GNU_SOURCE -DTX_LINUX_DEBUG_ENABLE"), not as separate list - # items, so a targeted list(REMOVE_ITEM) on COMPILE_DEFINITIONS can't - # match it. -U processes in command-line order after -D, so append it - # as a compile option instead of trying to edit the define out. - if(TARGET threadx) - target_compile_options(threadx PUBLIC "-UTX_LINUX_DEBUG_ENABLE") - endif() - - # The Linux/GNU port implements ThreadX scheduling on top of POSIX - # threads (pthread_create per tx_thread_create, signals for suspend). - find_package(Threads REQUIRED) - set(THREADX_LIBRARIES azrtos::threadx Threads::Threads) - else() - message(WARNING "DelegateMQ: No ThreadX simulation port configured for this host platform.") - endif() -endif() - -# --------------------------------------------------------------------------- -# Zephyr -# --------------------------------------------------------------------------- -if(DMQ_THREAD STREQUAL "DMQ_THREAD_ZEPHYR") - # Zephyr is a build system, not just a library. - # We typically do NOT manually glob source files here. - # The application's main CMakeLists.txt must call `find_package(Zephyr)` - # (before including DelegateMQ.cmake), which sets up the include paths - # and kernel linking automatically -- unlike ThreadX/FreeRTOS, Zephyr - # isn't vendored as a plain sibling directory; its location is a west - # workspace found via the ZEPHYR_BASE environment variable that - # find_package(Zephyr) itself sets. Sanity-check against that instead - # of assuming a "${DMQ_DEPS_DIR}/zephyr" clone that doesn't apply here. - if(NOT DEFINED ENV{ZEPHYR_BASE}) - message(WARNING "DelegateMQ: DMQ_THREAD_ZEPHYR is set, but ZEPHYR_BASE " - "is not defined -- ensure find_package(Zephyr) ran " - "before including DelegateMQ.cmake.") - endif() - - # Do NOT glob sources. Zephyr builds itself. -endif() - -# --------------------------------------------------------------------------- -# CMSIS-RTOS2 -# --------------------------------------------------------------------------- -if(DMQ_THREAD STREQUAL "DMQ_THREAD_CMSIS_RTOS2") - # CMSIS is usually provided by the IDE (Keil/IAR) or a silicon vendor pack (STM32Cube). - # We do NOT glob sources here by default. - # Users must ensure the 'cmsis_os2.h' path is in their include path. -endif() - -# --------------------------------------------------------------------------- -# NuttX -# --------------------------------------------------------------------------- -if(DMQ_THREAD STREQUAL "DMQ_THREAD_NUTTX") - # Like Zephyr, NuttX is a build system, not just a library -- an - # application is normally built as a NuttX "app" from inside a NuttX - # source tree (nuttx + apps repos), using NuttX's own Make-based - # (or, on recent versions, CMake-based) build, which already supplies - # the cross-toolchain and POSIX-compatible include paths (pthread.h, - # mqueue.h, semaphore.h, nuttx/irq.h, etc.) that this port's headers - # need. DelegateMQ.cmake does not vendor or fetch NuttX itself; the - # including project's build must already be running under a NuttX - # toolchain (or the `sim` simulation target) before this file is hit. - # - # Do NOT glob NuttX kernel sources here -- only DelegateMQ's own - # port/os/nuttx/*.cpp adapter files, already collected via - # Port.cmake's THREAD_SOURCES glob. -endif() - -# --------------------------------------------------------------------------- -# Qt Framework -# --------------------------------------------------------------------------- -if(DMQ_THREAD STREQUAL "DMQ_THREAD_QT") - # DMQ_THREAD_QT and the port/os/qt sources come from Port.cmake. - - # Find the Qt packages (Core is usually sufficient for QThread) - find_package(Qt6 COMPONENTS Core REQUIRED) - # Or Qt5: find_package(Qt5 COMPONENTS Core REQUIRED) - - # Important: Enable CMAKE_AUTOMOC for the Qt Meta-Object system - # (needed for signals/slots in Thread.h) - set(CMAKE_AUTOMOC ON) - - # Link Qt6::Core to your target (dmq_add_library() targets link it already): - # target_link_libraries(YourApp PRIVATE Qt6::Core) -endif() - -# --------------------------------------------------------------------------- -# spdlog -# --------------------------------------------------------------------------- -if (DMQ_LOG STREQUAL "ON") - set_and_check(SPDLOG_INCLUDE_DIR "${DMQ_DEPS_DIR}/spdlog/include") -endif() - -# --------------------------------------------------------------------------- -# Usage requirements for dmq_add_library(): third-party headers the selected -# ports include, and libraries resolvable here. Transports whose library is -# located by the application (NNG, MQTT, libserialport) are linked by the -# application itself; their include directories are still carried. -# --------------------------------------------------------------------------- -# Each entry is gated on its own option, not on whether the variable is set: -# an earlier include in this scope may have left another port's paths behind. -set(DMQ_EXTERNAL_INCLUDE_DIRS "") -if(DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_ZEROMQ") - list(APPEND DMQ_EXTERNAL_INCLUDE_DIRS ${ZeroMQ_INCLUDE_DIR}) -elseif(DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_NNG") - list(APPEND DMQ_EXTERNAL_INCLUDE_DIRS ${NNG_INCLUDE_DIR}) -elseif(DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_MQTT") - list(APPEND DMQ_EXTERNAL_INCLUDE_DIRS ${MQTT_INCLUDE_DIR}) -elseif(DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_SERIAL_PORT") - list(APPEND DMQ_EXTERNAL_INCLUDE_DIRS ${SERIALPORT_INCLUDE_DIR}) -elseif(DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_ARM_LWIP_UDP" OR DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_ARM_LWIP_NETCONN_UDP") - list(APPEND DMQ_EXTERNAL_INCLUDE_DIRS ${LWIP_INCLUDE_DIRS}) -elseif(DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_THREADX_UDP") - list(APPEND DMQ_EXTERNAL_INCLUDE_DIRS ${NETX_INCLUDE_DIR}) -endif() -if(DMQ_SERIALIZE STREQUAL "DMQ_SERIALIZE_MSGPACK") - list(APPEND DMQ_EXTERNAL_INCLUDE_DIRS ${MSGPACK_INCLUDE_DIR}) -elseif(DMQ_SERIALIZE STREQUAL "DMQ_SERIALIZE_CEREAL") - list(APPEND DMQ_EXTERNAL_INCLUDE_DIRS ${CEREAL_INCLUDE_DIR}) -elseif(DMQ_SERIALIZE STREQUAL "DMQ_SERIALIZE_BITSERY") - list(APPEND DMQ_EXTERNAL_INCLUDE_DIRS ${BITSERY_INCLUDE_DIR}) -elseif(DMQ_SERIALIZE STREQUAL "DMQ_SERIALIZE_RAPIDJSON") - list(APPEND DMQ_EXTERNAL_INCLUDE_DIRS ${RAPIDJSON_INCLUDE_DIR}) -endif() -if(DMQ_LOG STREQUAL "ON") - list(APPEND DMQ_EXTERNAL_INCLUDE_DIRS ${SPDLOG_INCLUDE_DIR}) -endif() -# FreeRTOS kernel headers only. The kernel sources (FREERTOS_SOURCES) build -# against the application's FreeRTOSConfig.h and stay in the application. -if(DMQ_THREAD STREQUAL "DMQ_THREAD_FREERTOS") - list(APPEND DMQ_EXTERNAL_INCLUDE_DIRS - "${FREERTOS_ROOT_DIR}/include" - "${FREERTOS_ROOT_DIR}/portable/${FREERTOS_PORT_DIR}") -endif() - -set(DMQ_LINK_LIBRARIES "") -if(DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_ZEROMQ" AND TARGET libzmq) - list(APPEND DMQ_LINK_LIBRARIES libzmq) -endif() -if(DMQ_THREAD STREQUAL "DMQ_THREAD_FREERTOS") - list(APPEND DMQ_LINK_LIBRARIES ${FREERTOS_LIBRARIES}) -elseif(DMQ_THREAD STREQUAL "DMQ_THREAD_THREADX") - list(APPEND DMQ_LINK_LIBRARIES ${THREADX_LIBRARIES}) -elseif(DMQ_THREAD STREQUAL "DMQ_THREAD_QT" AND TARGET Qt6::Core) - list(APPEND DMQ_LINK_LIBRARIES Qt6::Core) -elseif(UNIX AND (DMQ_THREAD STREQUAL "DMQ_THREAD_STDLIB" OR DMQ_THREAD STREQUAL "DMQ_THREAD_POSIX")) - find_package(Threads REQUIRED) - list(APPEND DMQ_LINK_LIBRARIES Threads::Threads) -endif() diff --git a/DelegateMQ/Macros.cmake b/DelegateMQ/Macros.cmake deleted file mode 100644 index a930274..0000000 --- a/DelegateMQ/Macros.cmake +++ /dev/null @@ -1,52 +0,0 @@ -# Function to copy .dll files from vcpkg bin directory to the build output directory -function(copy_files _src_files _dest_dir) - # Copy each DLL file to the build output directory - foreach(FILE ${_src_files}) - add_custom_command(TARGET ${DELEGATE_APP} POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_if_different - ${FILE} # Copy files - ${_dest_dir} # Destination directory - COMMENT "Copying ${FILE} to build output" - ) - endforeach() -endfunction() - -# Record DelegateMQ compile definitions in DMQ_COMPILE_DEFINITIONS (used by -# dmq_add_library) and, unless DMQ_NO_GLOBAL_DEFINITIONS is set, also apply -# them directory-wide the way add_compile_definitions() always has. -macro(dmq_compile_definitions) - list(APPEND DMQ_COMPILE_DEFINITIONS ${ARGN}) - if(NOT DMQ_NO_GLOBAL_DEFINITIONS) - add_compile_definitions(${ARGN}) - endif() -endmacro() - -# dmq_add_library() -# -# Creates a static library target from the port/extras sources selected by the -# current DMQ_* options. Compile definitions, include directories (DelegateMQ, -# DMQ_USER_CONFIG_DIR if set, and enabled third-party headers as SYSTEM) and -# link dependencies are PUBLIC, so a consumer only needs -# target_link_libraries(app PRIVATE ). -# -# Call in the same directory, after including DelegateMQ.cmake. Each call -# captures that include's options, so a build tree with several configurations -# (e.g. a FreeRTOS controller and a stdlib GUI) creates one target per config. -# -# RTOS ports (FreeRTOS, ThreadX, Zephyr, NuttX, CMSIS-RTOS2) compile against the -# application's own RTOS config headers; add those to the target, e.g. -# target_include_directories( PUBLIC path/to/FreeRTOSConfig_dir) -function(dmq_add_library _name) - add_library(${_name} STATIC ${DMQ_PORT_SOURCES} ${DMQ_LIB_SOURCES}) - target_compile_features(${_name} PUBLIC cxx_std_17) - target_compile_definitions(${_name} PUBLIC ${DMQ_COMPILE_DEFINITIONS}) - target_compile_options(${_name} PUBLIC ${DMQ_COMPILE_OPTIONS}) - target_include_directories(${_name} PUBLIC ${DMQ_INCLUDE_DIR} ${DMQ_USER_CONFIG_DIR}) - # SYSTEM: keep third-party header warnings out of DMQ_STRICT and the app's own warning level - target_include_directories(${_name} SYSTEM PUBLIC ${DMQ_EXTERNAL_INCLUDE_DIRS}) - target_link_libraries(${_name} PUBLIC ${DMQ_LINK_LIBRARIES}) - - source_group("DelegateMQ/Delegate Files" FILES ${DMQ_LIB_SOURCES}) - source_group("DelegateMQ/Port Files" FILES ${DMQ_PORT_ONLY_SOURCES}) - source_group("DelegateMQ/Extras Files" FILES ${DMQ_EXTRAS_SOURCES}) -endfunction() diff --git a/DelegateMQ/Port.cmake b/DelegateMQ/Port.cmake deleted file mode 100644 index 12a0369..0000000 --- a/DelegateMQ/Port.cmake +++ /dev/null @@ -1,261 +0,0 @@ -# Port build options - -# Start each include from empty lists: only some branches below set these, so a -# value left by an earlier include in this scope (or a parent's) would leak -# into this configuration. -foreach(_dmq_list THREAD SERIALIZE TRANSPORT OS DISPATCHER ALLOCATOR UTIL RPC FAULT DATABUS) - set(${_dmq_list}_SOURCES "") -endforeach() - -if (DMQ_THREAD STREQUAL "DMQ_THREAD_STDLIB") - dmq_compile_definitions(DMQ_THREAD_STDLIB) - file(GLOB THREAD_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/os/stdlib/*.c*" - "${DMQ_ROOT_DIR}/port/os/stdlib/*.h" - ) -elseif (DMQ_THREAD STREQUAL "DMQ_THREAD_WIN32") - dmq_compile_definitions(DMQ_THREAD_WIN32) - file(GLOB THREAD_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/os/win32/*.c*" - "${DMQ_ROOT_DIR}/port/os/win32/*.h" - ) -elseif (DMQ_THREAD STREQUAL "DMQ_THREAD_POSIX") - dmq_compile_definitions(DMQ_THREAD_POSIX) - file(GLOB THREAD_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/os/posix/*.c*" - "${DMQ_ROOT_DIR}/port/os/posix/*.h" - ) -elseif (DMQ_THREAD STREQUAL "DMQ_THREAD_FREERTOS") - dmq_compile_definitions(DMQ_THREAD_FREERTOS) - file(GLOB THREAD_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/os/freertos/*.c*" - "${DMQ_ROOT_DIR}/port/os/freertos/*.h" - ) -elseif (DMQ_THREAD STREQUAL "DMQ_THREAD_THREADX") - dmq_compile_definitions(DMQ_THREAD_THREADX) - file(GLOB THREAD_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/os/threadx/*.c*" - "${DMQ_ROOT_DIR}/port/os/threadx/*.h" - ) -elseif (DMQ_THREAD STREQUAL "DMQ_THREAD_ZEPHYR") - dmq_compile_definitions(DMQ_THREAD_ZEPHYR) - file(GLOB THREAD_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/os/zephyr/*.c*" - "${DMQ_ROOT_DIR}/port/os/zephyr/*.h" - ) -elseif (DMQ_THREAD STREQUAL "DMQ_THREAD_CMSIS_RTOS2") - dmq_compile_definitions(DMQ_THREAD_CMSIS_RTOS2) - file(GLOB THREAD_SOURCES - "${DMQ_ROOT_DIR}/port/os/cmsis-rtos2/*.c*" - "${DMQ_ROOT_DIR}/port/os/cmsis-rtos2/*.h" - ) -elseif (DMQ_THREAD STREQUAL "DMQ_THREAD_NUTTX") - dmq_compile_definitions(DMQ_THREAD_NUTTX) - file(GLOB THREAD_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/os/nuttx/*.c*" - "${DMQ_ROOT_DIR}/port/os/nuttx/*.h" - ) -elseif (DMQ_THREAD STREQUAL "DMQ_THREAD_QT") - dmq_compile_definitions(DMQ_THREAD_QT) - file(GLOB THREAD_SOURCES - "${DMQ_ROOT_DIR}/port/os/qt/*.c*" - "${DMQ_ROOT_DIR}/port/os/qt/*.h" - ) -elseif (DMQ_THREAD STREQUAL "DMQ_THREAD_NONE") - dmq_compile_definitions(DMQ_THREAD_NONE) -else() - message(FATAL_ERROR "Must set DMQ_THREAD option.") -endif() - -if (DMQ_SERIALIZE STREQUAL "DMQ_SERIALIZE_NONE") - dmq_compile_definitions(DMQ_SERIALIZE_NONE) -elseif (DMQ_SERIALIZE STREQUAL "DMQ_SERIALIZE_SERIALIZE") - dmq_compile_definitions(DMQ_SERIALIZE_SERIALIZE) - file(GLOB SERIALIZE_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/serialize/serialize/*.h") -elseif (DMQ_SERIALIZE STREQUAL "DMQ_SERIALIZE_RAPIDJSON") - dmq_compile_definitions(DMQ_SERIALIZE_RAPIDJSON) - file(GLOB SERIALIZE_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/serialize/rapidjson/*.h") -elseif (DMQ_SERIALIZE STREQUAL "DMQ_SERIALIZE_MSGPACK") - dmq_compile_definitions(DMQ_SERIALIZE_MSGPACK) - file(GLOB SERIALIZE_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/serialize/msgpack/*.h") -elseif (DMQ_SERIALIZE STREQUAL "DMQ_SERIALIZE_CEREAL") - dmq_compile_definitions(DMQ_SERIALIZE_CEREAL) - file(GLOB SERIALIZE_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/serialize/cereal/*.h") -elseif (DMQ_SERIALIZE STREQUAL "DMQ_SERIALIZE_BITSERY") - dmq_compile_definitions(DMQ_SERIALIZE_BITSERY) - file(GLOB SERIALIZE_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/serialize/bitsery/*.h") -else() - message(FATAL_ERROR "Must set DMQ_SERIALIZE option.") -endif() - -if (DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_NONE") - dmq_compile_definitions(DMQ_TRANSPORT_NONE) -elseif (DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_ZEROMQ") - dmq_compile_definitions(DMQ_TRANSPORT_ZEROMQ) - file(GLOB TRANSPORT_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/transport/zeromq/*.h") -elseif (DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_NNG") - dmq_compile_definitions(DMQ_TRANSPORT_NNG) - file(GLOB TRANSPORT_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/transport/nng/*.h") -elseif (DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_MQTT") - dmq_compile_definitions(DMQ_TRANSPORT_MQTT) - file(GLOB TRANSPORT_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/transport/mqtt/*.h") -elseif (DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_WIN32_PIPE") - dmq_compile_definitions(DMQ_TRANSPORT_WIN32_PIPE) - file(GLOB TRANSPORT_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/transport/win32-pipe/*.h") -elseif (DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_WIN32_UDP") - dmq_compile_definitions(DMQ_TRANSPORT_WIN32_UDP) - file(GLOB TRANSPORT_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/transport/win32-udp/*.h") -elseif (DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_WIN32_TCP") - dmq_compile_definitions(DMQ_TRANSPORT_WIN32_TCP) - file(GLOB TRANSPORT_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/transport/win32-tcp/*.h") -elseif (DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_LINUX_UDP") - dmq_compile_definitions(DMQ_TRANSPORT_LINUX_UDP) - file(GLOB TRANSPORT_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/transport/linux-udp/*.h") -elseif (DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_LINUX_UDS") - dmq_compile_definitions(DMQ_TRANSPORT_LINUX_UDS) - file(GLOB TRANSPORT_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/transport/linux-uds/*.h") -elseif (DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_LINUX_TCP") - dmq_compile_definitions(DMQ_TRANSPORT_LINUX_TCP) - file(GLOB TRANSPORT_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/transport/linux-tcp/*.h") -elseif (DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_SERIAL_PORT") - dmq_compile_definitions(DMQ_TRANSPORT_SERIAL_PORT) - file(GLOB TRANSPORT_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/transport/serial/*.h") -elseif (DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_ARM_LWIP_UDP") - dmq_compile_definitions(DMQ_TRANSPORT_ARM_LWIP_UDP) - file(GLOB TRANSPORT_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/transport/arm-lwip-udp/*.h") -elseif (DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_ARM_LWIP_NETCONN_UDP") - dmq_compile_definitions(DMQ_TRANSPORT_ARM_LWIP_NETCONN_UDP) - file(GLOB TRANSPORT_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/transport/arm-lwip-netconn-udp/*.h") -elseif (DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_THREADX_UDP") - dmq_compile_definitions(DMQ_TRANSPORT_THREADX_UDP) - file(GLOB TRANSPORT_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/transport/netx-udp/*.h") -elseif (DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_STM32_UART") - dmq_compile_definitions(DMQ_TRANSPORT_STM32_UART) - file(GLOB TRANSPORT_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/transport/stm32-uart/*.h") -elseif (DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_ZEPHYR_UDP") - dmq_compile_definitions(DMQ_TRANSPORT_ZEPHYR_UDP) - file(GLOB TRANSPORT_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/transport/zephyr-udp/*.h") -else() - message(FATAL_ERROR "Must set DMQ_TRANSPORT option.") -endif() - -file(GLOB DISPATCHER_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/extras/dispatcher/*.h" -) - -if (DMQ_ALLOCATOR STREQUAL "ON") - dmq_compile_definitions(DMQ_ALLOCATOR) - file(GLOB ALLOCATOR_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/extras/allocator/*.c*" - "${DMQ_ROOT_DIR}/extras/allocator/*.h" - ) -endif() - -if (DMQ_UTIL STREQUAL "ON") - if (DMQ_THREAD STREQUAL "DMQ_THREAD_NONE") - # Bare metal: only include utilities with no dmq::os::Thread/IThread - # dependency. Fault.cpp lives in port/fault/ and is always included - # separately. Timer.cpp is included -- it only needs dmq::Clock/ - # dmq::CriticalSection (BareMetalClock.h/BareMetalCriticalSection.h - # exist specifically so Timer::ProcessTimers() can be driven from a - # hardware ISR, e.g. SysTick_Handler, with no RTOS at all -- see - # BareMetalCriticalSection.h's own doc comment). AsyncInvoke.h/ - # TimerDelegate.h/RemoteDispatcher.cpp/ThreadMonitor.cpp all genuinely - # need a real dmq::IThread and stay excluded. - file(GLOB UTIL_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/extras/util/Fault.h" - "${DMQ_ROOT_DIR}/extras/util/Timer.h" - "${DMQ_ROOT_DIR}/extras/util/Timer.cpp" - ) - else() - # OS/RTOS present: Include everything - file(GLOB UTIL_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/extras/util/*.c*" - "${DMQ_ROOT_DIR}/extras/util/*.h" - ) - # RPC sources (RemoteDispatcher/RemoteEndpoint) need a real dmq::IThread, - # same reasoning as the bare-metal exclusion above -- only globbed here. - file(GLOB RPC_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/extras/rpc/*.c*" - "${DMQ_ROOT_DIR}/extras/rpc/*.h" - ) - endif() -endif() - -# Fault handler port — always included; override by filtering Fault.cpp from DMQ_PORT_SOURCES -file(GLOB FAULT_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/fault/Fault.cpp" -) - -if (DMQ_ASSERTS STREQUAL "ON") - dmq_compile_definitions(DMQ_ASSERTS) -endif() - -if (DMQ_LOG STREQUAL "ON") - dmq_compile_definitions(DMQ_LOG) -endif() - -# Port sources: OS/transport/serialization adapters (port/ directory) -set(DMQ_PORT_ONLY_SOURCES "") -list(APPEND DMQ_PORT_ONLY_SOURCES ${TRANSPORT_SOURCES}) -list(APPEND DMQ_PORT_ONLY_SOURCES ${SERIALIZE_SOURCES}) -list(APPEND DMQ_PORT_ONLY_SOURCES ${THREAD_SOURCES}) -list(APPEND DMQ_PORT_ONLY_SOURCES ${OS_SOURCES}) -list(APPEND DMQ_PORT_ONLY_SOURCES ${FAULT_SOURCES}) - -# Extras sources: optional higher-level infrastructure (extras/ directory) -set(DMQ_EXTRAS_SOURCES "") -list(APPEND DMQ_EXTRAS_SOURCES ${DISPATCHER_SOURCES}) -list(APPEND DMQ_EXTRAS_SOURCES ${ALLOCATOR_SOURCES}) -list(APPEND DMQ_EXTRAS_SOURCES ${UTIL_SOURCES}) -list(APPEND DMQ_EXTRAS_SOURCES ${RPC_SOURCES}) - -if (DMQ_DATABUS STREQUAL "ON") - dmq_compile_definitions(DMQ_DATABUS) - file(GLOB DATABUS_SOURCES CONFIGURE_DEPENDS "${DMQ_ROOT_DIR}/extras/databus/*.h") - list(APPEND DMQ_EXTRAS_SOURCES ${DATABUS_SOURCES}) -endif() - -# DelegateSelect.h turns DataBus and its tools on for desktop builds unless -# DMQ_DATABUS_OFF / DMQ_DATABUS_TOOLS_OFF is defined, so an explicit -# set(... "OFF") must be passed on for it to take effect there. A default -# Defaults.cmake filled in is left to DelegateSelect.h, as before. -list(FIND _DMQ_AUTO_DEFAULTS DMQ_DATABUS _dmq_databus_auto) -if (NOT DMQ_DATABUS AND _dmq_databus_auto EQUAL -1) - dmq_compile_definitions(DMQ_DATABUS_OFF) -endif() -list(FIND _DMQ_AUTO_DEFAULTS DMQ_DATABUS_TOOLS _dmq_tools_auto) -if (NOT DMQ_DATABUS_TOOLS AND _dmq_tools_auto EQUAL -1) - dmq_compile_definitions(DMQ_DATABUS_TOOLS_OFF) -endif() - -# Combined list for compilation -set(DMQ_PORT_SOURCES "") -list(APPEND DMQ_PORT_SOURCES ${DMQ_PORT_ONLY_SOURCES}) -list(APPEND DMQ_PORT_SOURCES ${DMQ_EXTRAS_SOURCES}) - -# Collect all DelegateMQ files -file(GLOB DMQ_LIB_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/*.h" - "${DMQ_ROOT_DIR}/delegate/*.h" -) \ No newline at end of file diff --git a/DelegateMQ/delegate/Delegate.h b/DelegateMQ/delegate/Delegate.h deleted file mode 100644 index e7ee3f1..0000000 --- a/DelegateMQ/delegate/Delegate.h +++ /dev/null @@ -1,997 +0,0 @@ -#ifndef _DELEGATE_H -#define _DELEGATE_H - -// Delegate.h -// @see https://github.com/DelegateMQ/DelegateMQ -// David Lafreniere, Aug 2020. - -/// @file -/// @brief Delegate series of classes are used to invoke a function synchronously. -/// @details Delegates support binding to free functions, class instance functions, class -/// static function, and std::function targets. Lambda functions can be bound to a delegate -/// when assigned to a `std::function`. The classes are not thread-safe. -/// -/// Limitations: -/// -/// * Cannot insert `DelegateMember` into an ordered container. e.g. `std::list` ok, -/// `std::set` not ok. -/// -/// * `std::function` compares the function signature type, not the underlying object instance. -/// See `DelegateFunction<>` class for more info. - -#include -#include -#include "DelegateOpt.h" - -/// The delegate library namespace -DMQ_OPTIMIZE_ON - -namespace dmq { - -namespace trait -{ - // Helper trait to check if a type is a reference to a std::shared_ptr - template - struct is_shared_ptr_reference : std::false_type {}; - - template - struct is_shared_ptr_reference&> : std::true_type {}; - - template - struct is_shared_ptr_reference&> : std::true_type {}; - - template - struct is_shared_ptr_reference*> : std::true_type {}; - - template - struct is_shared_ptr_reference*> : std::true_type {}; - - // Helper trait to check if a type is a non-const reference to a std::shared_ptr - template - struct is_non_const_shared_ptr_reference : std::false_type {}; - - template - struct is_non_const_shared_ptr_reference&> : std::true_type {}; - - template - struct is_non_const_shared_ptr_reference*> : std::true_type {}; - - - - // Helper trait to check if a type is a double pointer (e.g., int**) - template - struct is_double_pointer { - // Remove 'const', 'volatile', and references first - using RawT = std::remove_cv_t>; - - static constexpr bool value = - std::is_pointer_v && - std::is_pointer_v>; - }; - - // Helper trait to detect std::function specializations. - template - struct is_std_function : std::false_type {}; - - template - struct is_std_function> : std::true_type {}; - - // Helper trait to check if a type is a callable (lambda, functor) - // but NOT a function pointer or std::function (which have their own MakeDelegate overloads). - template - struct is_callable : std::false_type {}; - - template - struct is_callable::operator())>> : - std::integral_constant> && - !is_std_function>::value> {}; - - // Helper to deduce function signature from a member function pointer (like operator()) - template - struct function_traits; - - template - struct function_traits { - using function_type = RetType(Args...); - }; - - template - struct function_traits { - using function_type = RetType(Args...); - }; -} - -/// @brief Non-template base class for all delegates. -class DelegateBase { -public: - DelegateBase() = default; - virtual ~DelegateBase() noexcept = default; - - /// @brief Compares two delegate objects for equality. - /// @param rhs The delegate object to compare with the current object. - /// @return `true` if the objects are equal, `false` otherwise. - bool operator==(const DelegateBase& rhs) const noexcept { return Equal(rhs); } - - /// @brief Compares two delegate objects for inequality. - /// @param rhs The delegate object to compare with the current object. - /// @return `true` if the objects are not equal, `false` otherwise. - bool operator!=(const DelegateBase& rhs) const { return !Equal(rhs); } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - virtual bool operator==(std::nullptr_t) const noexcept = 0; - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - virtual bool operator!=(std::nullptr_t) const noexcept = 0; - - /// Compares two delegate objects for equality. - /// @return `true` if the objects are equal, `false` otherwise. - virtual bool Equal(const DelegateBase& other) const = 0; - - /// @brief Clone a delegate instance. - /// @details Use Clone() to provide a deep copy using a base pointer. Covariant - /// overloading is used so that a Clone() method return type is a more - /// specific type in the derived class implementations. - /// @return A dynamic copy of this instance created with `operator new()`. - /// @post The caller is responsible for deleting the clone instance. - virtual DelegateBase* Clone() const = 0; - - // Optional fixed block allocator for delegates created on the heap - // using operator new(). See DMQ_ALLOCATOR in DelegateOpt.h and - // ENABLE_ALLOCATOR in CMakeLists.txt. - XALLOCATOR -}; - -template -class Delegate; // Not defined - -/// @brief Template base class for all delegates. -/// @tparam RetType The return type of the bound delegate function. -/// @tparam Args The argument types of the bound delegate function. -template -class Delegate : public DelegateBase { -public: - /// @brief Invoke the bound callable function stored within the - /// delegate instance. - /// @param[in] args The bound function argument(s), if any. - /// @return The bound function return value, if any. - virtual RetType operator()(Args... args) = 0; - - /// @brief Clone an instance of a Delegate instance. - /// @return A new Delegate instance created on the heap. - /// @post The caller is responsible for deleting the instance. - virtual Delegate* Clone() const override = 0; -}; - -template -class DelegateFree; // Not defined - -/// @brief `DelegateFree<>` class synchronously invokes a free target function. -/// @tparam RetType The return type of the bound delegate function. -/// @tparam Args The argument types of the bound delegate function. -template -class DelegateFree : public Delegate { -public: - typedef RetType(*FreeFunc)(Args...); - using ClassType = DelegateFree; - - /// @brief Constructor to create a class instance. - /// @param[in] func The target free function to store. - DelegateFree(FreeFunc func) { Bind(func); } - - /// @brief Copy constructor that creates a copy of the given instance. - /// @details This constructor initializes a new object as a copy of the - /// provided `rhs` (right-hand side) object. The `rhs` object is used to - /// set the state of the new instance. - /// @param[in] rhs The object to copy from. - DelegateFree(const ClassType& rhs) { Assign(rhs); } - - /// @brief Move constructor that transfers ownership of resources. - /// @param[in] rhs The object to move from. - DelegateFree(ClassType&& rhs) noexcept : m_func(rhs.m_func) { rhs.Clear(); } - - /// @brief Default constructor creates an empty delegate. - DelegateFree() = default; - - /// @brief Destructor ensures empty when destroyed. - ~DelegateFree() override { Clear(); } - - /// @brief Bind a free function to the delegate. - /// @details This method associates a free function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] func The free function to bind to the delegate. This function must - /// match the signature of the delegate. - void Bind(FreeFunc func) { m_func = func; } - - /// Compares two ClassType objects using the '<' operator. - /// @param rhs The object to compare with. - /// @return `true` if the current object's value is less than the other object's value, - /// `false` otherwise. - bool operator<(const ClassType& rhs) const { - return m_func < rhs.m_func; - } - - /// @brief Creates a copy of the current object. - /// @details Clones the current instance of the class by creating a new object - /// and copying the state of the current object to it. - /// @return A pointer to a new `ClassType` instance or nullptr if allocation fails. - /// @post The caller is responsible for deleting the clone object and checking for - /// nullptr. - virtual ClassType* Clone() const override { - return new(std::nothrow) ClassType(*this); - } - - /// @brief Assigns the state of one object to another. - /// @details Copy the state from the `rhs` (right-hand side) object to the - /// current object. - /// @param[in] rhs The object whose state is to be copied. - void Assign(const ClassType& rhs) { - m_func = rhs.m_func; - } - - /// @brief Invoke the bound delegate function synchronously. Always safe to call. - /// @param[in] args - the function arguments, if any. - /// @return The bound function return value, if any. If empty delegate - /// default return type returned. - virtual RetType operator()(Args... args) override { - if (Empty()) - return RetType(); - return std::invoke(m_func, std::forward(args)...); - } - - /// @brief Assignment operator that assigns the state of one object to another. - /// @param[in] rhs The object whose state is to be assigned to the current object. - /// @return A reference to the current object. - ClassType& operator=(const ClassType& rhs) { - if (&rhs != this) { - Assign(rhs); - } - return *this; - } - - /// @brief Move assignment operator that transfers ownership of resources. - /// @param[in] rhs The object to move from. - /// @return A reference to the current object. - ClassType& operator=(ClassType&& rhs) noexcept { - if (&rhs != this) { - m_func = rhs.m_func; - rhs.Clear(); - } - return *this; - } - - /// @brief Clear the target function. - virtual void operator=(std::nullptr_t) noexcept { - return Clear(); - } - - /// @brief Compares two delegate objects for equality. - /// @param[in] rhs The `DelegateBase` object to compare with the current object. - /// @return `true` if the two delegate objects are equal, `false` otherwise. - virtual bool Equal(const DelegateBase& rhs) const override { - auto derivedRhs = dynamic_cast(&rhs); - return derivedRhs && - m_func == derivedRhs->m_func; - } - - /// Compares two delegate objects for equality. - /// @return `true` if the objects are equal, `false` otherwise. - bool operator==(const ClassType& rhs) const noexcept { return Equal(rhs); } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - virtual bool operator==(std::nullptr_t) const noexcept override { - return Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - virtual bool operator!=(std::nullptr_t) const noexcept override { - return !Empty(); - } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - friend bool operator==(std::nullptr_t, const ClassType& rhs) noexcept { - return rhs.Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - friend bool operator!=(std::nullptr_t, const ClassType& rhs) noexcept { - return !rhs.Empty(); - } - - /// @brief Check if the delegate is bound to a target function. - /// @return `true` if the delegate has a target function, `false` otherwise. - bool Empty() const noexcept { return !m_func; } - - /// @brief Clear the target function. - /// @post The delegate is empty. - void Clear() noexcept { m_func = nullptr; } - - /// @brief Implicit conversion operator to `bool`. - /// @return `true` if the object is not empty, `false` if the object is empty. - explicit operator bool() const noexcept { return !Empty(); } - -private: - /// @brief Pointer to a free function, representing the bound target function. - FreeFunc m_func = nullptr; -}; - -template -class DelegateMember; // Not defined - -/// @brief `DelegateMember<>` class synchronously invokes a class member target -/// function using a class object pointer or shared pointer. -/// @tparam TClass The class type that contains the member function. -/// @tparam RetType The return type of the bound delegate function. -/// @tparam Args The argument types of the bound delegate function. -template -class DelegateMember : public Delegate { -public: - typedef TClass* ObjectPtr; - typedef std::shared_ptr SharedPtr; - typedef RetType(TClass::* MemberFunc)(Args...); - typedef RetType(TClass::* ConstMemberFunc)(Args...) const; - using ClassType = DelegateMember; - - /// @brief Constructor to create a class instance. - /// @param[in] object The target object pointer to store. - /// @param[in] func The target member function to store. - DelegateMember(SharedPtr object, MemberFunc func) { Bind(object, func); } - - /// @brief Constructor to create a class instance. - /// @param[in] object The target object pointer to store. - /// @param[in] func The target const member function to store. - DelegateMember(SharedPtr object, ConstMemberFunc func) { Bind(object, func); } - - /// @brief Constructor to create a class instance. - /// @param[in] object The target object pointer to store. - /// @param[in] func The target member function to store. - DelegateMember(ObjectPtr object, MemberFunc func) { Bind(object, func); } - - /// @brief Constructor to create a class instance. - /// @param[in] object The target object pointer to store. - /// @param[in] func The target const member function to store. - DelegateMember(ObjectPtr object, ConstMemberFunc func) { Bind(object, func); } - - /// @brief Copy constructor that creates a copy of the given instance. - /// @details This constructor initializes a new object as a copy of the - /// provided `rhs` (right-hand side) object. The `rhs` object is used to - /// set the state of the new instance. - /// @param[in] rhs The object to copy from. - DelegateMember(const ClassType& rhs) { Assign(rhs); } - - /// @brief Move constructor that transfers ownership of resources. - /// @param[in] rhs The object to move from. - DelegateMember(ClassType&& rhs) noexcept : m_object(std::move(rhs.m_object)), m_func(rhs.m_func) { rhs.Clear(); } - - /// @brief Default constructor creates an empty delegate. - DelegateMember() = default; - - /// @brief Destructor ensures empty when destroyed. - ~DelegateMember() override { Clear(); } - - /// @brief Bind a member function to the delegate. - /// @details This method associates a member function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] object The target object instance. - /// @param[in] func The member function to bind to the delegate. This function must - /// match the signature of the delegate. - void Bind(SharedPtr object, MemberFunc func) { - static_assert(!std::is_const::value, "Cannot bind non-const function to const object."); - m_object = object; - m_func = func; - } - - /// @brief Bind a const member function to the delegate. - /// @details This method associates a member function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] object The target object instance. - /// @param[in] func The function to bind to the delegate. The member function to - /// bind to the delegate. This function must match the signature of the delegate. - void Bind(SharedPtr object, ConstMemberFunc func) { - m_object = object; - // Note: Casting ConstMemberFunc to MemberFunc is formally UB when invoked - // through the non-const pointer, but works safely on all mainstream ABIs. - m_func = reinterpret_cast(func); - } - - /// @brief Bind a member function to a raw pointer. - /// @details Wraps the raw object pointer in a `std::shared_ptr` with a no-op - /// deleter, ensuring the delegate references the object without taking ownership - /// or attempting to delete it. The caller must ensure the object outlives the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] object The target object instance (raw pointer). - /// @param[in] func The const member function to bind. - void Bind(ObjectPtr object, MemberFunc func) { - static_assert(!std::is_const::value, "Cannot bind non-const function to const object."); - auto deleter = [](TClass*) {}; // No-op deleter - m_object = std::shared_ptr(object, deleter, ::dmq::stl_allocator>()); // Not deleted when out of scope - m_func = func; - } - - /// @brief Bind a const member function to a raw pointer. - /// @details Wraps the raw object pointer in a `std::shared_ptr` with a no-op - /// deleter, ensuring the delegate references the object without taking ownership - /// or attempting to delete it. The caller must ensure the object outlives the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] object The target object instance (raw pointer). - /// @param[in] func The const member function to bind. - void Bind(ObjectPtr object, ConstMemberFunc func) { - auto deleter = [](TClass*) {}; // No-op deleter - m_object = std::shared_ptr(object, deleter, ::dmq::stl_allocator>()); // Not deleted when out of scope - // Note: Casting ConstMemberFunc to MemberFunc is formally UB when invoked - // through the non-const pointer, but works safely on all mainstream ABIs. - m_func = reinterpret_cast(func); - } - - /// @brief Creates a copy of the current object. - /// @details Clones the current instance of the class by creating a new object - /// and copying the state of the current object to it. - /// @return A pointer to a new `ClassType` instance or nullptr if allocation fails. - /// @post The caller is responsible for deleting the clone object and checking for - /// nullptr. - virtual ClassType* Clone() const override { - return new(std::nothrow) ClassType(*this); - } - - /// @brief Assigns the state of one object to another. - /// @details Copy the state from the `rhs` (right-hand side) object to the - /// current object. - /// @param[in] rhs The object whose state is to be copied. - void Assign(const ClassType& rhs) { - m_object = rhs.m_object; - m_func = rhs.m_func; - } - - /// @brief Invoke the bound delegate function synchronously. Always safe to call. - /// @param[in] args - the function arguments, if any. - /// @return The bound function return value, if any. If empty delegate - /// default return type returned. - virtual RetType operator()(Args... args) override { - if (Empty()) - return RetType(); - - if constexpr (std::is_const::value) - return std::invoke(reinterpret_cast(m_func), m_object, std::forward(args)...); - else - return std::invoke(m_func, m_object, std::forward(args)...); - } - - /// @brief Assignment operator that assigns the state of one object to another. - /// @param[in] rhs The object whose state is to be assigned to the current object. - /// @return A reference to the current object. - ClassType& operator=(const ClassType& rhs) { - if (&rhs != this) { - Assign(rhs); - } - return *this; - } - - /// @brief Move assignment operator that transfers ownership of resources. - /// @param[in] rhs The object to move from. - /// @return A reference to the current object. - ClassType& operator=(ClassType&& rhs) noexcept { - if (&rhs != this) { - m_object = std::move(rhs.m_object); - m_func = rhs.m_func; - rhs.Clear(); - } - return *this; - } - - /// @brief Clear the target function. - virtual void operator=(std::nullptr_t) noexcept { - return Clear(); - } - - /// @brief Compares two delegate objects for equality. - /// @param[in] rhs The `DelegateBase` object to compare with the current object. - /// @return `true` if the two delegate objects are equal, `false` otherwise. - virtual bool Equal(const DelegateBase& rhs) const override { - auto derivedRhs = dynamic_cast(&rhs); - return derivedRhs && - m_func == derivedRhs->m_func && - m_object == derivedRhs->m_object; - } - - /// Compares two delegate objects for equality. - /// @return `true` if the objects are equal, `false` otherwise. - bool operator==(const ClassType& rhs) const noexcept { return Equal(rhs); } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - virtual bool operator==(std::nullptr_t) const noexcept override { - return Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - virtual bool operator!=(std::nullptr_t) const noexcept override { - return !Empty(); - } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - friend bool operator==(std::nullptr_t, const ClassType& rhs) noexcept { - return rhs.Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - friend bool operator!=(std::nullptr_t, const ClassType& rhs) noexcept { - return !rhs.Empty(); - } - - /// @brief Check if the delegate is bound to a target function. - /// @return `true` if the delegate has a target function, `false` otherwise. - bool Empty() const noexcept { return !(m_object && m_func); } - - /// @brief Clear the target function. - /// @post The delegate is empty. - void Clear() noexcept { m_object = nullptr; m_func = nullptr; } - - /// @brief Implicit conversion operator to `bool`. - /// @return `true` if the object is not empty, `false` if the object is empty. - explicit operator bool() const noexcept { return !Empty(); } - -private: - /// Compares two ClassType objects using the '<' operator. - /// @param rhs The object to compare with. - /// @return `true` if the current object's value is less than the other object's value, - /// `false` otherwise. - /// @note Do not call! Not allowed since comparing member function - /// pointers for operator< not allowed in C++. - bool operator<(const ClassType& rhs) const = delete; - - /// Pointer to a class object, representing the bound target instance. - SharedPtr m_object = nullptr; - - /// Pointer to a member function, representing the bound target function. - MemberFunc m_func = nullptr; -}; - -template -class DelegateMemberSp; // Not defined - -/// @brief `DelegateMemberSp<>` class synchronously invokes a class member target -/// function using a weak pointer. -/// @details This class is a "safe" version of DelegateMember. It holds a std::weak_ptr -/// to the target. If the target is destroyed, the callback is silently dropped. -/// @tparam TClass The class type that contains the member function. -/// @tparam RetType The return type of the bound delegate function. -/// @tparam Args The argument types of the bound delegate function. -template -class DelegateMemberSp : public Delegate { -public: - typedef TClass* ObjectPtr; - typedef std::shared_ptr SharedPtr; - typedef std::weak_ptr WeakPtr; - typedef RetType(TClass::* MemberFunc)(Args...); - typedef RetType(TClass::* ConstMemberFunc)(Args...) const; - using ClassType = DelegateMemberSp; - - /// @brief Constructor to create a class instance. - /// @param[in] object The target object pointer to store. - /// @param[in] func The target member function to store. - DelegateMemberSp(SharedPtr object, MemberFunc func) { Bind(object, func); } - - /// @brief Constructor to create a class instance. - /// @param[in] object The target object pointer to store. - /// @param[in] func The target const member function to store. - DelegateMemberSp(SharedPtr object, ConstMemberFunc func) { Bind(object, func); } - - /// @brief Copy constructor. - DelegateMemberSp(const ClassType& rhs) { Assign(rhs); } - - /// @brief Move constructor. - DelegateMemberSp(ClassType&& rhs) noexcept : m_object(std::move(rhs.m_object)), m_func(rhs.m_func) { rhs.Clear(); } - - /// @brief Default constructor. - DelegateMemberSp() = default; - - /// @brief Destructor. - ~DelegateMemberSp() override { Clear(); } - - /// @brief Bind a member function to the delegate. - void Bind(SharedPtr object, MemberFunc func) { - static_assert(!std::is_const::value, "Cannot bind non-const function to const object."); - m_object = object; // Implicit conversion from shared_ptr to weak_ptr - m_func = func; - } - - /// @brief Bind a const member function to the delegate. - void Bind(SharedPtr object, ConstMemberFunc func) { - m_object = object; // Implicit conversion from shared_ptr to weak_ptr - // Note: Casting ConstMemberFunc to MemberFunc is formally UB when invoked - // through the non-const pointer, but works safely on all mainstream ABIs. - m_func = reinterpret_cast(func); - } - - /// @brief Creates a copy of the current object. - virtual ClassType* Clone() const override { - return new(std::nothrow) ClassType(*this); - } - - /// @brief Assigns the state of one object to another. - void Assign(const ClassType& rhs) { - m_object = rhs.m_object; - m_func = rhs.m_func; - } - - /// @brief Invoke the bound delegate function synchronously. - /// @details SAFELY locks the weak pointer. If object is dead, returns default. - virtual RetType operator()(Args... args) override { - // 1. Try to promote weak_ptr to strong shared_ptr - if (auto strongPtr = m_object.lock()) - { - // 2. SUCCESS: Object is alive. Invoke. - if constexpr (std::is_const::value) - return std::invoke(reinterpret_cast(m_func), strongPtr, std::forward(args)...); - else - return std::invoke(m_func, strongPtr, std::forward(args)...); - } - - // 3. FAILURE: Object is dead. Silently ignore. - return RetType(); - } - - /// @brief Assignment operator. - ClassType& operator=(const ClassType& rhs) { - if (&rhs != this) { - Assign(rhs); - } - return *this; - } - - /// @brief Move assignment operator. - ClassType& operator=(ClassType&& rhs) noexcept { - if (&rhs != this) { - m_object = std::move(rhs.m_object); - m_func = rhs.m_func; - rhs.Clear(); - } - return *this; - } - - /// @brief Clear the target function. - virtual void operator=(std::nullptr_t) noexcept { - return Clear(); - } - - /// @brief Compares two delegate objects for equality. - virtual bool Equal(const DelegateBase& rhs) const override { - auto derivedRhs = dynamic_cast(&rhs); - if (!derivedRhs) return false; - - // Compare Weak Pointers by locking them first - auto ptr1 = m_object.lock(); - auto ptr2 = derivedRhs->m_object.lock(); - - return (ptr1 == ptr2) && (m_func == derivedRhs->m_func); - } - - // Standard operator== overloads - bool operator==(const ClassType& rhs) const noexcept { return Equal(rhs); } - virtual bool operator==(std::nullptr_t) const noexcept override { return Empty(); } - virtual bool operator!=(std::nullptr_t) const noexcept override { return !Empty(); } - friend bool operator==(std::nullptr_t, const ClassType& rhs) noexcept { return rhs.Empty(); } - friend bool operator!=(std::nullptr_t, const ClassType& rhs) noexcept { return !rhs.Empty(); } - - /// @brief Check if the delegate is bound and the object is alive. - bool Empty() const noexcept { return m_object.expired() || !m_func; } - - /// @brief Clear the target function. - void Clear() noexcept { m_object.reset(); m_func = nullptr; } - - explicit operator bool() const noexcept { return !Empty(); } - -private: - bool operator<(const ClassType& rhs) const = delete; - - /// Weak pointer to the target object. - WeakPtr m_object; - - /// Pointer to a member function. - MemberFunc m_func = nullptr; -}; - -template -class DelegateFunction; // Not defined - -/// @brief `DelegateFunction<>` class synchronously invokes a `std::function` target function. -/// @details Caution when binding to a `std::function` using this class. `std::function` cannot be -/// compared for equality directly in a meaningful way using `operator==`. Therefore, the delegate -/// library uses `target_type()` for comparison. `target_type()` only compares the types of the -/// stored callable objects, but the not actual instances. The code below shows the issue. -/// -/// `Test t1, t2;` -/// `std::function f1 = std::bind(&Test::Func, &t1, std::placeholders::_1);` -/// `std::function f2 = std::bind(&Test::Func, &t2, std::placeholders::_1);` -/// `MulticastDelegateSafe safe;` -/// `safe += MakeDelegate(f1);` -/// `safe += MakeDelegate(f2);` -/// `safe -= MakeDelegate(f2); // Should remove f2, not f1!` -/// -/// Depending on how usage, this may never be a issue but its worth noting. -/// -/// The other delegate classes has no such limitations and works under all conditions, -/// including comparing two instance functions of the same class. -/// -/// @tparam RetType The return type of the bound delegate function. -/// @tparam Args The argument types of the bound delegate function. -template -class DelegateFunction : public Delegate { -public: - using FunctionType = std::function; - using ClassType = DelegateFunction; - - /// @brief Constructor to create a class instance. - /// @param[in] func The target `std::function` to store. - DelegateFunction(FunctionType func) { Bind(func); } - - /// @brief Copy constructor that creates a copy of the given instance. - /// @details This constructor initializes a new object as a copy of the - /// provided `rhs` (right-hand side) object. The `rhs` object is used to - /// set the state of the new instance. - /// @param[in] rhs The object to copy from. - DelegateFunction(const ClassType& rhs) { Assign(rhs); } - - /// @brief Move constructor that transfers ownership of resources. - /// @param[in] rhs The object to move from. - DelegateFunction(ClassType&& rhs) noexcept : m_func(std::move(rhs.m_func)) { rhs.Clear(); } - - /// @brief Default constructor creates an empty delegate. - DelegateFunction() = default; - - /// @brief Destructor ensures empty when destroyed. - ~DelegateFunction() override { Clear(); } - - /// @brief Bind a member function to the delegate. - /// @details This method associates a member function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] func The `std::function` to bind to the delegate. This function must - /// match the signature of the delegate. - void Bind(FunctionType func) { -#if !defined(__cpp_exceptions) || defined(DMQ_ASSERTS) - // No exceptions: Direct assignment. - // If the STL needs to allocate memory here and fails, - // it will likely abort() internally on embedded systems. - m_func = func; -#else - // Exceptions enabled: Safe to try-catch. - try { - m_func = func; - } - catch (const std::bad_alloc&) { - BAD_ALLOC(); - } -#endif - } - - /// Compares two ClassType objects using the '<' operator. - /// @param rhs The object to compare with. - /// @return `true` if the current object's value is less than the other object's value, - /// `false` otherwise. - bool operator<(const ClassType& rhs) const { - return m_func.template target() < rhs.m_func.template target(); - } - - /// @brief Creates a copy of the current object. - /// @details Clones the current instance of the class by creating a new object - /// and copying the state of the current object to it. - /// @return A pointer to a new `ClassType` instance or nullptr if allocation fails. - /// @post The caller is responsible for deleting the clone object and checking for - /// nullptr. - virtual ClassType* Clone() const override { - return new(std::nothrow) ClassType(*this); - } - - /// @brief Assigns the state of one object to another. - /// @details Copy the state from the `rhs` (right-hand side) object to the - /// current object. - /// @param[in] rhs The object whose state is to be copied. - void Assign(const ClassType& rhs) { - m_func = rhs.m_func; - } - - /// @brief Invoke the bound delegate function synchronously. Always safe to call. - /// @param[in] args - the function arguments, if any. - /// @return The bound function return value, if any. If empty delegate - /// default return type returned. - virtual RetType operator()(Args... args) override { - if (Empty()) - return RetType(); - return m_func(std::forward(args)...); - } - - /// @brief Assignment operator that assigns the state of one object to another. - /// @param[in] rhs The object whose state is to be assigned to the current object. - /// @return A reference to the current object. - ClassType& operator=(const ClassType& rhs) { - if (&rhs != this) { - Assign(rhs); - } - return *this; - } - - /// @brief Move assignment operator that transfers ownership of resources. - /// @param[in] rhs The object to move from. - /// @return A reference to the current object. - ClassType& operator=(ClassType&& rhs) noexcept { - if (&rhs != this) { - m_func = std::move(rhs.m_func); - rhs.Clear(); - } - return *this; - } - - /// @brief Clear the target function. - virtual void operator=(std::nullptr_t) noexcept { - return Clear(); - } - - /// @brief Compares two delegate objects for equality. - /// @param[in] rhs The `DelegateBase` object to compare with the current object. - /// @return `true` if the two delegate objects are equal, `false` otherwise. - virtual bool Equal(const DelegateBase& rhs) const override { - auto derivedRhs = dynamic_cast(&rhs); - if (derivedRhs) { - // If both delegates are empty, they are equal - if (Empty() && derivedRhs->Empty()) - return true; - - if (m_func && derivedRhs->m_func) - return m_func.target_type() == derivedRhs->m_func.target_type(); - - return false; - } - - return false; // Return false if dynamic cast failed - } - - /// Compares two delegate objects for equality. - /// @return `true` if the objects are equal, `false` otherwise. - bool operator==(const ClassType& rhs) const noexcept { return Equal(rhs); } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - virtual bool operator==(std::nullptr_t) const noexcept override { - return Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - virtual bool operator!=(std::nullptr_t) const noexcept override { - return !Empty(); - } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - friend bool operator==(std::nullptr_t, const ClassType& rhs) noexcept { - return rhs.Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - friend bool operator!=(std::nullptr_t, const ClassType& rhs) noexcept { - return !rhs.Empty(); - } - - /// @brief Check if the delegate is bound to a target function. - /// @return `true` if the delegate has a target function, `false` otherwise. - bool Empty() const noexcept { return !m_func; } - - /// @brief Clear the target function. - /// @post The delegate is empty. - void Clear() noexcept { m_func = nullptr; } - - /// @brief Implicit conversion operator to `bool`. - /// @return `true` if the object is not empty, `false` if the object is empty. - explicit operator bool() const noexcept { return !Empty(); } - -private: - /// A std::function instance, representing the bound target function. - FunctionType m_func; -}; - -/// @brief Creates a delegate that binds to a free function. -/// @tparam RetType The return type of the free function. -/// @tparam Args The types of the function arguments. -/// @param[in] func A pointer to the free function to bind to the delegate. -/// @return A `DelegateFree` object bound to the specified free function. -template -auto MakeDelegate(RetType(*func)(Args... args)) { - return DelegateFree(func); -} - -/// @brief Creates a delegate that binds to a non-const member function. -/// @tparam TClass The class type that contains the member function. -/// @tparam RetType The return type of the member function. -/// @tparam Args The types of the function arguments. -/// @param[in] object A pointer to the instance of `TClass` that will be used for the delegate. -/// @param[in] func A pointer to the non-const member function of `TClass` to bind to the delegate. -/// @return A `DelegateMember` object bound to the specified non-const member function. -template -auto MakeDelegate(TClass* object, RetType(TClass::*func)(Args... args)) { - return DelegateMember(object, func); -} - -/// @brief Creates a delegate that binds to a const member function. -/// @tparam TClass The class type that contains the const member function. -/// @tparam RetType The return type of the member function. -/// @tparam Args The types of the function arguments. -/// @param[in] object A pointer to the instance of `TClass` that will be used for the delegate. -/// @param[in] func A pointer to the const member function of `TClass` to bind to the delegate. -/// @return A `DelegateMember` object bound to the specified const member function. -template -auto MakeDelegate(TClass* object, RetType(TClass::*func)(Args... args) const) { - return DelegateMember(object, func); -} - -/// @brief Creates a delegate that binds to a const member function. -/// @tparam TClass The const class type that contains the const member function. -/// @tparam RetType The return type of the member function. -/// @tparam Args The types of the function arguments. -/// @param[in] object A pointer to the instance of `TClass` that will be used for the delegate. -/// @param[in] func A pointer to the non-const member function of `TClass` to bind to the delegate. -/// @return A `DelegateMember` object bound to the specified non-const member function. -template -auto MakeDelegate(const TClass* object, RetType(TClass::* func)(Args... args) const) { - return DelegateMember(object, func); -} - -/// @brief Creates a delegate that binds to a non-const member function with a shared pointer to the object. -/// @tparam TClass The class type that contains the member function. -/// @tparam RetType The return type of the member function. -/// @tparam Args The types of the function arguments. -/// @param[in] object A shared pointer to the instance of `TClass` that will be used for the delegate. -/// @param[in] func A pointer to the non-const member function of `TClass` to bind to the delegate. -/// @return A `DelegateMember` shared pointer bound to the specified non-const member function. -template -auto MakeDelegate(std::shared_ptr object, RetType(TClass::* func)(Args... args)) { - return DelegateMemberSp(object, func); -} - -/// @brief Creates a delegate that binds to a const member function with a shared pointer to the object. -/// @tparam TClass The class type that contains the member function. -/// @tparam RetType The return type of the member function. -/// @tparam Args The types of the function arguments. -/// @param[in] object A shared pointer to the instance of `TClass` that will be used for the delegate. -/// @param[in] func A pointer to the const member function of `TClass` to bind to the delegate. -/// @return A `DelegateMember` shared pointer bound to the specified const member function. -template -auto MakeDelegate(std::shared_ptr object, RetType(TClass::* func)(Args... args) const) { - return DelegateMemberSp(object, func); -} - -/// @brief Creates a delegate that binds to a `std::function`. -/// @tparam RetType The return type of the `std::function`. -/// @tparam Args The types of the function arguments. -/// @param[in] func The `std::function` to bind to the delegate. -/// @return A `DelegateFunction` object bound to the specified `std::function`. -template -auto MakeDelegate(std::function func) { - return DelegateFunction(func); -} - -/// @brief Creates a delegate that binds to a raw lambda or functor. -/// @tparam F The lambda or functor type. -/// @param[in] func The lambda or functor to bind. -/// @return A `DelegateFunction` object bound to the specified lambda or functor. -template ::value>> -auto MakeDelegate(F&& func) { - // Deduce the signature from the operator() - using Sig = typename trait::function_traits::operator())>::function_type; - return DelegateFunction(std::forward(func)); -} - -} - -DMQ_OPTIMIZE_OFF - -#endif diff --git a/DelegateMQ/delegate/DelegateAsync.h b/DelegateMQ/delegate/DelegateAsync.h deleted file mode 100644 index e9bc4f3..0000000 --- a/DelegateMQ/delegate/DelegateAsync.h +++ /dev/null @@ -1,1230 +0,0 @@ -#ifndef _DELEGATE_ASYNC_H -#define _DELEGATE_ASYNC_H - -// DelegateAsync.h -// @see https://github.com/DelegateMQ/DelegateMQ -// David Lafreniere, Aug 2020. - -/// @file -/// @brief Delegate "`Async`" series of classes used to invoke a function asynchronously. -/// -/// @details The classes are not thread safe. Invoking a function asynchronously requires -/// sending a clone of the object to the destination thread message queue. The destination -/// thread calls `Invoke()` to invoke the target function. -/// -/// A `IThread` implementation is required to serialize and dispatch an async delegate onto -/// a destination thread of control. -/// -/// Argument data is created on the heap using `operator new` for transport thought a thread -/// message queue. An optional fixed-block allocator is available. See `DMQ_ALLOCATOR`. -/// -/// `RetType operator()(Args... args)` - called by the source thread to initiate the async -/// function call. May throw `std::bad_alloc` if dynamic storage allocation fails and `DMQ_ASSERTS` -/// is not defined. Clone() may also throw `std::bad_alloc` unless `DMQ_ASSERTS`. All other delegate -/// class functions do not throw exceptions. -/// -/// `void Invoke(std::shared_ptr msg)` - called by the destination -/// thread to invoke the target function. The destination thread must not call any other -/// delegate instance functions. -/// -/// Limitations: -/// -/// * The target function return value is not valid after invoke since the delegate does -/// not wait for the target function to be called. -/// -/// * Cannot use a `void*` as a target function argument. -/// -/// * Cannot use rvalue reference (T&&) as a target function argument. -/// -/// * Cannot insert `DelegateMemberAsync` into an ordered container. e.g. `std::list` ok, -/// `std::set` not ok. -/// -/// * `std::function` compares the function signature type, not the underlying object instance. -/// See `DelegateFunction<>` class for more info. -/// -/// Code within `` and `` is updated using src_dup.py. Manually update -/// the code within the `DelegateFreeAsync` `common_code` tags, then run the script to -/// propagate to the remaining delegate classes to simplify code maintenance. -/// -/// `python src_dup.py DelegateAsync.h` - -#include "Delegate.h" -#include "IThread.h" -#include "IInvoker.h" -#include -#include - -DMQ_OPTIMIZE_ON - -namespace dmq { - -/// @brief Stores all function arguments suitable for non-blocking asynchronous calls. -/// By-value arguments are stored in the message itself; the data behind reference and -/// pointer arguments is copied to the heap, so it outlives the caller's stack. -/// @tparam Args The argument types of the bound delegate function. -template -class DelegateAsyncMsg : public DelegateMsg -{ -public: - /// Constructor - /// @param[in] invoker - the invoker instance - /// @param[in] priority - the delegate message priority - /// @param[in] args - a parameter pack of all target function arguments - /// @throws std::bad_alloc If a heap copy of a reference or pointer argument fails and DMQ_ASSERTS not defined. - DelegateAsyncMsg(std::shared_ptr invoker, Priority priority, Args... args) : DelegateMsg(invoker, priority), - m_args{ store_async_arg(m_heapMem, std::forward(args))... } { - } - - /// Delete the default constructor - DelegateAsyncMsg() = delete; - - /// Delete the copy constructor - DelegateAsyncMsg(const DelegateAsyncMsg&) = delete; - - /// Delete the copy assignment operator - DelegateAsyncMsg& operator=(const DelegateAsyncMsg&) = delete; - - /// Delete the move constructor and move assignment - DelegateAsyncMsg(DelegateAsyncMsg&&) = delete; - DelegateAsyncMsg& operator=(DelegateAsyncMsg&&) = delete; - - virtual ~DelegateAsyncMsg() = default; - - /// Get all function arguments that were created on the heap - /// @return A tuple of all function arguments - std::tuple& GetArgs() { return m_args; } - -private: - /// A list of heap allocated argument memory blocks - xlist> m_heapMem; - - /// The arguments: by-value ones held here, reference/pointer ones referring to - /// heap copies owned by `m_heapMem`. Declared after `m_heapMem`, so it is - /// constructed after it and destroyed before it. - std::tuple m_args; -}; - -namespace detail { - -/// @brief Non-template holder for a `DelegateXAsync<...>` instance's dispatch state -/// (destination thread, message priority). None of this depends on the bound function's -/// signature or target class, so every `DelegateFreeAsync`/`DelegateMemberAsync`/ -/// `DelegateMemberAsyncSp`/`DelegateFunctionAsync` instantiation composes this one -/// definition instead of each generating its own copy of the same two fields plus their -/// Assign()/Equal()/move-ctor plumbing. -class AsyncDispatchState { -public: - IThread* GetThread() const noexcept { return m_thread; } - void SetThread(IThread* thread) noexcept { m_thread = thread; } - Priority GetPriority() const noexcept { return m_priority; } - void SetPriority(Priority priority) noexcept { m_priority = priority; } - - bool Equal(const AsyncDispatchState& rhs) const noexcept { - return m_thread == rhs.m_thread && m_priority == rhs.m_priority; - } - -private: - IThread* m_thread = nullptr; - Priority m_priority = Priority::NORMAL; -}; - -/// @brief Builds the heap-copied argument message and dispatches it to `thread`. -/// @details Templated only on `Args...`, not on the owning delegate's target-object or -/// return type, so this single instantiation is shared by every `DelegateXAsync<...>` -/// signature that takes the same arguments, instead of each owning class generating its -/// own copy of this logic. -/// @param[in] invoker The already-cloned delegate to invoke on the destination thread, -/// type-erased through `IThreadInvoker`. -/// @param[in] thread The destination thread, or `nullptr` if unbound. -/// @param[in] priority The message priority. -/// @param[in] args The function arguments, if any. -template -void DispatchAsync(std::shared_ptr invoker, IThread* thread, Priority priority, Args&&... args) { - // Create a new message instance for sending to the destination thread. Erase to - // the non-templated DelegateMsg base BEFORE constructing the shared_ptr (rather - // than xmake_shared>) so the shared_ptr control block - // is not templated on Args... -- one control-block type is then shared across - // every DelegateAsync signature instead of duplicated per signature. - auto* rawMsg = new(std::nothrow) DelegateAsyncMsg(std::move(invoker), priority, std::forward(args)...); - if (!rawMsg) - BAD_ALLOC(); - DelegateMsg* msgBase = rawMsg; - std::shared_ptr msg(msgBase, std::default_delete(), dmq::stl_allocator()); - - if (thread) { - // Dispatch message onto the callback destination thread. Invoke() - // will be called by the destintation thread. - bool success = thread->DispatchDelegate(msg); - if (!success) { - LOG_ERROR("DelegateAsync dispatch failed"); - } - } -} - -} // namespace detail - -template -class DelegateFreeAsync; // Not defined - -/// @brief `DelegateFreeAsync<>` class asynchronously invokes a free target function. -/// @tparam RetType The return type of the bound delegate function. -/// @tparam Args The argument types of the bound delegate function. -template -class DelegateFreeAsync : public DelegateFree, public IThreadInvoker { -public: - typedef RetType(*FreeFunc)(Args...); - using ClassType = DelegateFreeAsync; - using BaseType = DelegateFree; - - static_assert(!(std::disjunction_v...>), - "Non-const std::shared_ptr reference/pointer arguments are not allowed"); - - /// @brief Constructor to create a class instance. - /// @param[in] func The target free function to store. - /// @param[in] thread The execution thread to invoke `func`. - DelegateFreeAsync(FreeFunc func, IThread& thread) : - BaseType(func) { - Bind(func, thread); - } - - /// @brief Copy constructor that creates a copy of the given instance. - /// @details This constructor initializes a new object as a copy of the - /// provided `rhs` (right-hand side) object. The `rhs` object is used to - /// set the state of the new instance. - /// @param[in] rhs The object to copy from. - DelegateFreeAsync(const ClassType& rhs) : - BaseType(rhs) { - Assign(rhs); - } - - /// @brief Move constructor that transfers ownership of resources. - /// @param[in] rhs The object to move from. - DelegateFreeAsync(ClassType&& rhs) noexcept : - BaseType(std::move(rhs)), m_state(rhs.m_state) { - rhs.Clear(); - } - - DelegateFreeAsync() = default; - - /// @brief Bind a free function to the delegate. - /// @details This method associates a free function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] func The free function to bind to the delegate. This function must - /// match the signature of the delegate. - /// @param[in] thread The execution thread to invoke `func`. - void Bind(FreeFunc func, IThread& thread) { - m_state.SetThread(&thread); - BaseType::Bind(func); - } - - // - - /// @brief Assigns the state of one object to another. - /// @details Copy the state from the `rhs` (right-hand side) object to the - /// current object. - /// @param[in] rhs The object whose state is to be copied. - void Assign(const ClassType& rhs) { - m_state = rhs.m_state; - BaseType::Assign(rhs); - } - /// @brief Creates a copy of the current object. - /// @details Clones the current instance of the class by creating a new object - /// and copying the state of the current object to it. - /// @return A pointer to a new `ClassType` instance or nullptr if allocation fails. - /// @post The caller is responsible for deleting the clone object and checking for - /// nullptr. - virtual ClassType* Clone() const override { - return new(std::nothrow) ClassType(*this); - } - - /// @brief Assignment operator that assigns the state of one object to another. - /// @param[in] rhs The object whose state is to be assigned to the current object. - /// @return A reference to the current object. - ClassType& operator=(const ClassType& rhs) { - if (&rhs != this) { - BaseType::operator=(rhs); - Assign(rhs); - } - return *this; - } - - /// @brief Move assignment operator that transfers ownership of resources. - /// @param[in] rhs The object to move from. - /// @return A reference to the current object. - ClassType& operator=(ClassType&& rhs) noexcept { - if (&rhs != this) { - BaseType::operator=(std::move(rhs)); - m_state = rhs.m_state; // Use the resource - rhs.Clear(); - } - return *this; - } - - /// @brief Clear the target function. - virtual void operator=(std::nullptr_t) noexcept override { - return this->Clear(); - } - - /// @brief Compares two delegate objects for equality. - /// @param[in] rhs The `DelegateBase` object to compare with the current object. - /// @return `true` if the two delegate objects are equal, `false` otherwise. - virtual bool Equal(const DelegateBase& rhs) const override { - auto derivedRhs = dynamic_cast(&rhs); - return derivedRhs && - m_state.Equal(derivedRhs->m_state) && - BaseType::Equal(rhs); - } - - /// Compares two delegate objects for equality. - /// @return `true` if the objects are equal, `false` otherwise. - bool operator==(const ClassType& rhs) const noexcept { return Equal(rhs); } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - virtual bool operator==(std::nullptr_t) const noexcept override { - return this->Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - virtual bool operator!=(std::nullptr_t) const noexcept override { - return !this->Empty(); - } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - friend bool operator==(std::nullptr_t, const ClassType& rhs) noexcept { - return rhs.Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - friend bool operator!=(std::nullptr_t, const ClassType& rhs) noexcept { - return !rhs.Empty(); - } - - /// @brief Invoke the bound delegate function asynchronously. Called by the source thread. - /// @details Invoke delegate function asynchronously and do not wait for return value. - /// This function is called by the source thread. Dispatches the delegate data into the - /// destination thread message queue. `Invoke()` must be called by the destination - /// thread to invoke the target function. Always safe to call. - /// - /// The `DelegateAsyncMsg` duplicates and copies the function arguments into heap memory. - /// The source thread is not required to place function arguments into the heap. The delegate - /// library performs all necessary heap and argument coping for the caller. Ensure complex - /// argument data types can be safely copied by creating a copy constructor if necessary. - /// @param[in] args The function arguments, if any. - /// @return A default return value. The return value is *not* returned from the - /// target function. Do not use the return value. - /// @post Do not use the return value as its not valid. - /// @throws std::bad_alloc If dynamic memory allocation fails and DMQ_ASSERTS not defined. - virtual RetType operator()(Args... args) override { - if (this->Empty()) - return RetType(); - - // Create a clone instance of this delegate. Erase to the non-templated - // IThreadInvoker interface BEFORE constructing the shared_ptr (rather than - // xmake_shared) so the shared_ptr control block is not templated - // on RetType/Args... -- one control-block type is then shared across every - // DelegateAsync kind and signature instead of duplicated per signature. - ClassType* rawClone = this->Clone(); - if (!rawClone) - BAD_ALLOC(); - IThreadInvoker* invokerBase = rawClone; - std::shared_ptr delegate(invokerBase, std::default_delete(), dmq::stl_allocator()); - - detail::DispatchAsync(delegate, m_state.GetThread(), m_state.GetPriority(), std::forward(args)...); - - // Do not wait for destination thread return value from async function call - return RetType(); - } - - /// @brief Invoke delegate function asynchronously. Do not wait for return value. - /// Called by the source thread. Always safe to call. - /// @param[in] args The function arguments, if any. - void AsyncInvoke(Args... args) { - operator()(std::forward(args)...); - } - - /// @brief Invoke the delegate function on the destination thread. Called by the - /// destintation thread. - /// @details Each source thread call to `operator()` generate a call to `Invoke()` - /// on the destination thread. Unlike `DelegateAsyncWait`, a lock is not required between - /// source and destination `delegateMsg` access because the source thread is not waiting - /// for the function call to complete. - /// @param[in] msg The delegate message created and sent within `operator()(Args... args)`. - /// @return `true` if target function invoked; `false` if error. - virtual bool Invoke(std::shared_ptr msg) override { - // Typecast the base pointer to back correct derived to instance - auto delegateMsg = std::dynamic_pointer_cast>(msg); - if (delegateMsg == nullptr) - return false; - - // Call the target with the message's stored arguments: a qualified, non-virtual - // call, so there is no copy of the argument tuple and no virtual hop back through - // operator(). Each argument is forwarded as declared: by-value arguments are moved - // out of the message (each message is invoked exactly once), references bind to - // the stored copies. - std::apply([this](auto&... args) { this->BaseType::operator()(std::forward(args)...); }, - delegateMsg->GetArgs()); - return true; - } - - /// @brief Get the destination thread that the target function is invoked on. - /// @return The target thread. - IThread* GetThread() const noexcept { return m_state.GetThread(); } - - /// @brief Get the delegate message priority - /// @return Delegate message priority - Priority GetPriority() const noexcept { return m_state.GetPriority(); } - void SetPriority(Priority priority) noexcept { m_state.SetPriority(priority); } - -private: - /// Destination thread and message priority. Not templated on Sig/TClass — see - /// `detail::AsyncDispatchState`. - detail::AsyncDispatchState m_state; - - // -}; - -template -class DelegateMemberAsync; // Not defined - -/// @brief `DelegateMemberAsync<>` class asynchronously invokes a class member target function. -/// @tparam TClass The class type that contains the member function. -/// @tparam RetType The return type of the bound delegate function. -/// @tparam Args The argument types of the bound delegate function. -template -class DelegateMemberAsync : public DelegateMember, public IThreadInvoker { -public: - typedef TClass* ObjectPtr; - typedef std::shared_ptr SharedPtr; - typedef RetType(TClass::* MemberFunc)(Args...); - typedef RetType(TClass::* ConstMemberFunc)(Args...) const; - using ClassType = DelegateMemberAsync; - using BaseType = DelegateMember; - - static_assert(!(std::disjunction_v...>), - "Non-const std::shared_ptr reference/pointer arguments are not allowed"); - - /// @brief Constructor to create a class instance. - /// @param[in] object The target object pointer to store. - /// @param[in] func The target member function to store. - /// @param[in] thread The execution thread to invoke `func`. - DelegateMemberAsync(SharedPtr object, MemberFunc func, IThread& thread) : BaseType(object, func) { - Bind(object, func, thread); - } - - /// @brief Constructor to create a class instance. - /// @param[in] object The target object pointer to store. - /// @param[in] func The target const member function to store. - /// @param[in] thread The execution thread to invoke `func`. - DelegateMemberAsync(SharedPtr object, ConstMemberFunc func, IThread& thread) : BaseType(object, func) { - Bind(object, func, thread); - } - - /// @brief Constructor to create a class instance. - /// @param[in] object The target object pointer to store. - /// @param[in] func The target member function to store. - /// @param[in] thread The execution thread to invoke `func`. - DelegateMemberAsync(ObjectPtr object, MemberFunc func, IThread& thread) : BaseType(object, func) { - Bind(object, func, thread); - } - - /// @brief Constructor to create a class instance. - /// @param[in] object The target object pointer to store. - /// @param[in] func The target const member function to store. - /// @param[in] thread The execution thread to invoke `func`. - DelegateMemberAsync(ObjectPtr object, ConstMemberFunc func, IThread& thread) : BaseType(object, func) { - Bind(object, func, thread); - } - - /// @brief Copy constructor that creates a copy of the given instance. - /// @details This constructor initializes a new object as a copy of the - /// provided `rhs` (right-hand side) object. The `rhs` object is used to - /// set the state of the new instance. - /// @param[in] rhs The object to copy from. - DelegateMemberAsync(const ClassType& rhs) : - BaseType(rhs) { - Assign(rhs); - } - - /// @brief Move constructor that transfers ownership of resources. - /// @param[in] rhs The object to move from. - DelegateMemberAsync(ClassType&& rhs) noexcept : - BaseType(std::move(rhs)), m_state(rhs.m_state) { - rhs.Clear(); - } - - DelegateMemberAsync() = default; - - /// @brief Bind a member function to the delegate. - /// @details This method associates a member function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] object The target object instance. - /// @param[in] func The function to bind to the delegate. This function must match - /// the signature of the delegate. - /// @param[in] thread The execution thread to invoke `func`. - void Bind(SharedPtr object, MemberFunc func, IThread& thread) { - m_state.SetThread(&thread); - BaseType::Bind(object, func); - } - - /// @brief Bind a const member function to the delegate. - /// @details This method associates a member function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] object The target object instance. - /// @param[in] func The member function to bind to the delegate. This function must - /// match the signature of the delegate. - /// @param[in] thread The execution thread to invoke `func`. - void Bind(SharedPtr object, ConstMemberFunc func, IThread& thread) { - m_state.SetThread(&thread); - BaseType::Bind(object, func); - } - - /// @brief Bind a member function to the delegate. - /// @details This method associates a member function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] object The target object instance. - /// @param[in] func The function to bind to the delegate. This function must match - /// the signature of the delegate. - /// @param[in] thread The execution thread to invoke `func`. - void Bind(ObjectPtr object, MemberFunc func, IThread& thread) { - m_state.SetThread(&thread); - BaseType::Bind(object, func); - } - - /// @brief Bind a const member function to the delegate. - /// @details This method associates a member function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] object The target object instance. - /// @param[in] func The member function to bind to the delegate. This function must - /// match the signature of the delegate. - /// @param[in] thread The execution thread to invoke `func`. - void Bind(ObjectPtr object, ConstMemberFunc func, IThread& thread) { - m_state.SetThread(&thread); - BaseType::Bind(object, func); - } - - // - - /// @brief Assigns the state of one object to another. - /// @details Copy the state from the `rhs` (right-hand side) object to the - /// current object. - /// @param[in] rhs The object whose state is to be copied. - void Assign(const ClassType& rhs) { - m_state = rhs.m_state; - BaseType::Assign(rhs); - } - /// @brief Creates a copy of the current object. - /// @details Clones the current instance of the class by creating a new object - /// and copying the state of the current object to it. - /// @return A pointer to a new `ClassType` instance or nullptr if allocation fails. - /// @post The caller is responsible for deleting the clone object and checking for - /// nullptr. - virtual ClassType* Clone() const override { - return new(std::nothrow) ClassType(*this); - } - - /// @brief Assignment operator that assigns the state of one object to another. - /// @param[in] rhs The object whose state is to be assigned to the current object. - /// @return A reference to the current object. - ClassType& operator=(const ClassType& rhs) { - if (&rhs != this) { - BaseType::operator=(rhs); - Assign(rhs); - } - return *this; - } - - /// @brief Move assignment operator that transfers ownership of resources. - /// @param[in] rhs The object to move from. - /// @return A reference to the current object. - ClassType& operator=(ClassType&& rhs) noexcept { - if (&rhs != this) { - BaseType::operator=(std::move(rhs)); - m_state = rhs.m_state; // Use the resource - rhs.Clear(); - } - return *this; - } - - /// @brief Clear the target function. - virtual void operator=(std::nullptr_t) noexcept override { - return this->Clear(); - } - - /// @brief Compares two delegate objects for equality. - /// @param[in] rhs The `DelegateBase` object to compare with the current object. - /// @return `true` if the two delegate objects are equal, `false` otherwise. - virtual bool Equal(const DelegateBase& rhs) const override { - auto derivedRhs = dynamic_cast(&rhs); - return derivedRhs && - m_state.Equal(derivedRhs->m_state) && - BaseType::Equal(rhs); - } - - /// Compares two delegate objects for equality. - /// @return `true` if the objects are equal, `false` otherwise. - bool operator==(const ClassType& rhs) const noexcept { return Equal(rhs); } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - virtual bool operator==(std::nullptr_t) const noexcept override { - return this->Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - virtual bool operator!=(std::nullptr_t) const noexcept override { - return !this->Empty(); - } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - friend bool operator==(std::nullptr_t, const ClassType& rhs) noexcept { - return rhs.Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - friend bool operator!=(std::nullptr_t, const ClassType& rhs) noexcept { - return !rhs.Empty(); - } - - /// @brief Invoke the bound delegate function asynchronously. Called by the source thread. - /// @details Invoke delegate function asynchronously and do not wait for return value. - /// This function is called by the source thread. Dispatches the delegate data into the - /// destination thread message queue. `Invoke()` must be called by the destination - /// thread to invoke the target function. Always safe to call. - /// - /// The `DelegateAsyncMsg` duplicates and copies the function arguments into heap memory. - /// The source thread is not required to place function arguments into the heap. The delegate - /// library performs all necessary heap and argument coping for the caller. Ensure complex - /// argument data types can be safely copied by creating a copy constructor if necessary. - /// @param[in] args The function arguments, if any. - /// @return A default return value. The return value is *not* returned from the - /// target function. Do not use the return value. - /// @post Do not use the return value as its not valid. - /// @throws std::bad_alloc If dynamic memory allocation fails and DMQ_ASSERTS not defined. - virtual RetType operator()(Args... args) override { - if (this->Empty()) - return RetType(); - - // Create a clone instance of this delegate. Erase to the non-templated - // IThreadInvoker interface BEFORE constructing the shared_ptr (rather than - // xmake_shared) so the shared_ptr control block is not templated - // on RetType/Args... -- one control-block type is then shared across every - // DelegateAsync kind and signature instead of duplicated per signature. - ClassType* rawClone = this->Clone(); - if (!rawClone) - BAD_ALLOC(); - IThreadInvoker* invokerBase = rawClone; - std::shared_ptr delegate(invokerBase, std::default_delete(), dmq::stl_allocator()); - - detail::DispatchAsync(delegate, m_state.GetThread(), m_state.GetPriority(), std::forward(args)...); - - // Do not wait for destination thread return value from async function call - return RetType(); - } - - /// @brief Invoke delegate function asynchronously. Do not wait for return value. - /// Called by the source thread. Always safe to call. - /// @param[in] args The function arguments, if any. - void AsyncInvoke(Args... args) { - operator()(std::forward(args)...); - } - - /// @brief Invoke the delegate function on the destination thread. Called by the - /// destintation thread. - /// @details Each source thread call to `operator()` generate a call to `Invoke()` - /// on the destination thread. Unlike `DelegateAsyncWait`, a lock is not required between - /// source and destination `delegateMsg` access because the source thread is not waiting - /// for the function call to complete. - /// @param[in] msg The delegate message created and sent within `operator()(Args... args)`. - /// @return `true` if target function invoked; `false` if error. - virtual bool Invoke(std::shared_ptr msg) override { - // Typecast the base pointer to back correct derived to instance - auto delegateMsg = std::dynamic_pointer_cast>(msg); - if (delegateMsg == nullptr) - return false; - - // Call the target with the message's stored arguments: a qualified, non-virtual - // call, so there is no copy of the argument tuple and no virtual hop back through - // operator(). Each argument is forwarded as declared: by-value arguments are moved - // out of the message (each message is invoked exactly once), references bind to - // the stored copies. - std::apply([this](auto&... args) { this->BaseType::operator()(std::forward(args)...); }, - delegateMsg->GetArgs()); - return true; - } - - /// @brief Get the destination thread that the target function is invoked on. - /// @return The target thread. - IThread* GetThread() const noexcept { return m_state.GetThread(); } - - /// @brief Get the delegate message priority - /// @return Delegate message priority - Priority GetPriority() const noexcept { return m_state.GetPriority(); } - void SetPriority(Priority priority) noexcept { m_state.SetPriority(priority); } - -private: - /// Destination thread and message priority. Not templated on Sig/TClass — see - /// `detail::AsyncDispatchState`. - detail::AsyncDispatchState m_state; - - // -}; - -template -class DelegateMemberAsyncSp; // Not defined - -/// @brief `DelegateMemberAsyncSp<>` class asynchronously invokes a class member target function -/// using a weak pointer (safe from use-after-free). -/// @tparam TClass The class type that contains the member function. -/// @tparam RetType The return type of the bound delegate function. -/// @tparam Args The argument types of the bound delegate function. -template -class DelegateMemberAsyncSp : public DelegateMemberSp, public IThreadInvoker { -public: - typedef TClass* ObjectPtr; - typedef std::shared_ptr SharedPtr; - typedef RetType(TClass::* MemberFunc)(Args...); - typedef RetType(TClass::* ConstMemberFunc)(Args...) const; - using ClassType = DelegateMemberAsyncSp; - using BaseType = DelegateMemberSp; - - static_assert(!(std::disjunction_v...>), - "Non-const std::shared_ptr reference/pointer arguments are not allowed"); - - DelegateMemberAsyncSp(SharedPtr object, MemberFunc func, IThread& thread) : BaseType(object, func) { - Bind(object, func, thread); - } - - DelegateMemberAsyncSp(SharedPtr object, ConstMemberFunc func, IThread& thread) : BaseType(object, func) { - Bind(object, func, thread); - } - - DelegateMemberAsyncSp(const ClassType& rhs) : BaseType(rhs) { Assign(rhs); } - - DelegateMemberAsyncSp(ClassType&& rhs) noexcept : - BaseType(std::move(rhs)), m_state(rhs.m_state) { - rhs.Clear(); - } - - DelegateMemberAsyncSp() = default; - - void Bind(SharedPtr object, MemberFunc func, IThread& thread) { - m_state.SetThread(&thread); - BaseType::Bind(object, func); - } - - void Bind(SharedPtr object, ConstMemberFunc func, IThread& thread) { - m_state.SetThread(&thread); - BaseType::Bind(object, func); - } - - // - - /// @brief Assigns the state of one object to another. - /// @details Copy the state from the `rhs` (right-hand side) object to the - /// current object. - /// @param[in] rhs The object whose state is to be copied. - void Assign(const ClassType& rhs) { - m_state = rhs.m_state; - BaseType::Assign(rhs); - } - /// @brief Creates a copy of the current object. - /// @details Clones the current instance of the class by creating a new object - /// and copying the state of the current object to it. - /// @return A pointer to a new `ClassType` instance or nullptr if allocation fails. - /// @post The caller is responsible for deleting the clone object and checking for - /// nullptr. - virtual ClassType* Clone() const override { - return new(std::nothrow) ClassType(*this); - } - - /// @brief Assignment operator that assigns the state of one object to another. - /// @param[in] rhs The object whose state is to be assigned to the current object. - /// @return A reference to the current object. - ClassType& operator=(const ClassType& rhs) { - if (&rhs != this) { - BaseType::operator=(rhs); - Assign(rhs); - } - return *this; - } - - /// @brief Move assignment operator that transfers ownership of resources. - /// @param[in] rhs The object to move from. - /// @return A reference to the current object. - ClassType& operator=(ClassType&& rhs) noexcept { - if (&rhs != this) { - BaseType::operator=(std::move(rhs)); - m_state = rhs.m_state; // Use the resource - rhs.Clear(); - } - return *this; - } - - /// @brief Clear the target function. - virtual void operator=(std::nullptr_t) noexcept override { - return this->Clear(); - } - - /// @brief Compares two delegate objects for equality. - /// @param[in] rhs The `DelegateBase` object to compare with the current object. - /// @return `true` if the two delegate objects are equal, `false` otherwise. - virtual bool Equal(const DelegateBase& rhs) const override { - auto derivedRhs = dynamic_cast(&rhs); - return derivedRhs && - m_state.Equal(derivedRhs->m_state) && - BaseType::Equal(rhs); - } - - /// Compares two delegate objects for equality. - /// @return `true` if the objects are equal, `false` otherwise. - bool operator==(const ClassType& rhs) const noexcept { return Equal(rhs); } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - virtual bool operator==(std::nullptr_t) const noexcept override { - return this->Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - virtual bool operator!=(std::nullptr_t) const noexcept override { - return !this->Empty(); - } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - friend bool operator==(std::nullptr_t, const ClassType& rhs) noexcept { - return rhs.Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - friend bool operator!=(std::nullptr_t, const ClassType& rhs) noexcept { - return !rhs.Empty(); - } - - /// @brief Invoke the bound delegate function asynchronously. Called by the source thread. - /// @details Invoke delegate function asynchronously and do not wait for return value. - /// This function is called by the source thread. Dispatches the delegate data into the - /// destination thread message queue. `Invoke()` must be called by the destination - /// thread to invoke the target function. Always safe to call. - /// - /// The `DelegateAsyncMsg` duplicates and copies the function arguments into heap memory. - /// The source thread is not required to place function arguments into the heap. The delegate - /// library performs all necessary heap and argument coping for the caller. Ensure complex - /// argument data types can be safely copied by creating a copy constructor if necessary. - /// @param[in] args The function arguments, if any. - /// @return A default return value. The return value is *not* returned from the - /// target function. Do not use the return value. - /// @post Do not use the return value as its not valid. - /// @throws std::bad_alloc If dynamic memory allocation fails and DMQ_ASSERTS not defined. - virtual RetType operator()(Args... args) override { - if (this->Empty()) - return RetType(); - - // Create a clone instance of this delegate. Erase to the non-templated - // IThreadInvoker interface BEFORE constructing the shared_ptr (rather than - // xmake_shared) so the shared_ptr control block is not templated - // on RetType/Args... -- one control-block type is then shared across every - // DelegateAsync kind and signature instead of duplicated per signature. - ClassType* rawClone = this->Clone(); - if (!rawClone) - BAD_ALLOC(); - IThreadInvoker* invokerBase = rawClone; - std::shared_ptr delegate(invokerBase, std::default_delete(), dmq::stl_allocator()); - - detail::DispatchAsync(delegate, m_state.GetThread(), m_state.GetPriority(), std::forward(args)...); - - // Do not wait for destination thread return value from async function call - return RetType(); - } - - /// @brief Invoke delegate function asynchronously. Do not wait for return value. - /// Called by the source thread. Always safe to call. - /// @param[in] args The function arguments, if any. - void AsyncInvoke(Args... args) { - operator()(std::forward(args)...); - } - - /// @brief Invoke the delegate function on the destination thread. Called by the - /// destintation thread. - /// @details Each source thread call to `operator()` generate a call to `Invoke()` - /// on the destination thread. Unlike `DelegateAsyncWait`, a lock is not required between - /// source and destination `delegateMsg` access because the source thread is not waiting - /// for the function call to complete. - /// @param[in] msg The delegate message created and sent within `operator()(Args... args)`. - /// @return `true` if target function invoked; `false` if error. - virtual bool Invoke(std::shared_ptr msg) override { - // Typecast the base pointer to back correct derived to instance - auto delegateMsg = std::dynamic_pointer_cast>(msg); - if (delegateMsg == nullptr) - return false; - - // Call the target with the message's stored arguments: a qualified, non-virtual - // call, so there is no copy of the argument tuple and no virtual hop back through - // operator(). Each argument is forwarded as declared: by-value arguments are moved - // out of the message (each message is invoked exactly once), references bind to - // the stored copies. - std::apply([this](auto&... args) { this->BaseType::operator()(std::forward(args)...); }, - delegateMsg->GetArgs()); - return true; - } - - /// @brief Get the destination thread that the target function is invoked on. - /// @return The target thread. - IThread* GetThread() const noexcept { return m_state.GetThread(); } - - /// @brief Get the delegate message priority - /// @return Delegate message priority - Priority GetPriority() const noexcept { return m_state.GetPriority(); } - void SetPriority(Priority priority) noexcept { m_state.SetPriority(priority); } - -private: - /// Destination thread and message priority. Not templated on Sig/TClass — see - /// `detail::AsyncDispatchState`. - detail::AsyncDispatchState m_state; - - // -}; - -template -class DelegateFunctionAsync; // Not defined - -/// @brief `DelegateFunctionAsync<>` class asynchronously invokes a `std::function` target function. -/// @details Caution when binding to a `std::function` using this class. `std::function` cannot be -/// compared for equality directly in a meaningful way using `operator==`. Therefore, the delegate -/// library used -/// -/// See `DelegateFunction<>` base class for important usage limitations. -/// -/// @tparam RetType The return type of the bound delegate function. -/// @tparam Args The argument types of the bound delegate function. -template -class DelegateFunctionAsync : public DelegateFunction, public IThreadInvoker { -public: - using FunctionType = std::function; - using ClassType = DelegateFunctionAsync; - using BaseType = DelegateFunction; - - static_assert(!(std::disjunction_v...>), - "Non-const std::shared_ptr reference/pointer arguments are not allowed"); - - /// @brief Constructor to create a class instance. - /// @param[in] func The target `std::function` to store. - /// @param[in] thread The execution thread to invoke `func`. - DelegateFunctionAsync(FunctionType func, IThread& thread) : - BaseType(func) { - Bind(func, thread); - } - - /// @brief Copy constructor that creates a copy of the given instance. - /// @details This constructor initializes a new object as a copy of the - /// provided `rhs` (right-hand side) object. The `rhs` object is used to - /// set the state of the new instance. - /// @param[in] rhs The object to copy from. - DelegateFunctionAsync(const ClassType& rhs) : - BaseType(rhs) { - Assign(rhs); - } - - /// @brief Move constructor that transfers ownership of resources. - /// @param[in] rhs The object to move from. - DelegateFunctionAsync(ClassType&& rhs) noexcept : - BaseType(std::move(rhs)), m_state(rhs.m_state) { - rhs.Clear(); - } - - DelegateFunctionAsync() = default; - - /// @brief Bind a `std::function` to the delegate. - /// @details This method associates a member function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] func The `std::function` to bind to the delegate. This function must match - /// the signature of the delegate. - /// @param[in] thread The execution thread to invoke `func`. - void Bind(FunctionType func, IThread& thread) { - m_state.SetThread(&thread); - BaseType::Bind(func); - } - - // - - /// @brief Assigns the state of one object to another. - /// @details Copy the state from the `rhs` (right-hand side) object to the - /// current object. - /// @param[in] rhs The object whose state is to be copied. - void Assign(const ClassType& rhs) { - m_state = rhs.m_state; - BaseType::Assign(rhs); - } - /// @brief Creates a copy of the current object. - /// @details Clones the current instance of the class by creating a new object - /// and copying the state of the current object to it. - /// @return A pointer to a new `ClassType` instance or nullptr if allocation fails. - /// @post The caller is responsible for deleting the clone object and checking for - /// nullptr. - virtual ClassType* Clone() const override { - return new(std::nothrow) ClassType(*this); - } - - /// @brief Assignment operator that assigns the state of one object to another. - /// @param[in] rhs The object whose state is to be assigned to the current object. - /// @return A reference to the current object. - ClassType& operator=(const ClassType& rhs) { - if (&rhs != this) { - BaseType::operator=(rhs); - Assign(rhs); - } - return *this; - } - - /// @brief Move assignment operator that transfers ownership of resources. - /// @param[in] rhs The object to move from. - /// @return A reference to the current object. - ClassType& operator=(ClassType&& rhs) noexcept { - if (&rhs != this) { - BaseType::operator=(std::move(rhs)); - m_state = rhs.m_state; // Use the resource - rhs.Clear(); - } - return *this; - } - - /// @brief Clear the target function. - virtual void operator=(std::nullptr_t) noexcept override { - return this->Clear(); - } - - /// @brief Compares two delegate objects for equality. - /// @param[in] rhs The `DelegateBase` object to compare with the current object. - /// @return `true` if the two delegate objects are equal, `false` otherwise. - virtual bool Equal(const DelegateBase& rhs) const override { - auto derivedRhs = dynamic_cast(&rhs); - return derivedRhs && - m_state.Equal(derivedRhs->m_state) && - BaseType::Equal(rhs); - } - - /// Compares two delegate objects for equality. - /// @return `true` if the objects are equal, `false` otherwise. - bool operator==(const ClassType& rhs) const noexcept { return Equal(rhs); } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - virtual bool operator==(std::nullptr_t) const noexcept override { - return this->Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - virtual bool operator!=(std::nullptr_t) const noexcept override { - return !this->Empty(); - } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - friend bool operator==(std::nullptr_t, const ClassType& rhs) noexcept { - return rhs.Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - friend bool operator!=(std::nullptr_t, const ClassType& rhs) noexcept { - return !rhs.Empty(); - } - - /// @brief Invoke the bound delegate function asynchronously. Called by the source thread. - /// @details Invoke delegate function asynchronously and do not wait for return value. - /// This function is called by the source thread. Dispatches the delegate data into the - /// destination thread message queue. `Invoke()` must be called by the destination - /// thread to invoke the target function. Always safe to call. - /// - /// The `DelegateAsyncMsg` duplicates and copies the function arguments into heap memory. - /// The source thread is not required to place function arguments into the heap. The delegate - /// library performs all necessary heap and argument coping for the caller. Ensure complex - /// argument data types can be safely copied by creating a copy constructor if necessary. - /// @param[in] args The function arguments, if any. - /// @return A default return value. The return value is *not* returned from the - /// target function. Do not use the return value. - /// @post Do not use the return value as its not valid. - /// @throws std::bad_alloc If dynamic memory allocation fails and DMQ_ASSERTS not defined. - virtual RetType operator()(Args... args) override { - if (this->Empty()) - return RetType(); - - // Create a clone instance of this delegate. Erase to the non-templated - // IThreadInvoker interface BEFORE constructing the shared_ptr (rather than - // xmake_shared) so the shared_ptr control block is not templated - // on RetType/Args... -- one control-block type is then shared across every - // DelegateAsync kind and signature instead of duplicated per signature. - ClassType* rawClone = this->Clone(); - if (!rawClone) - BAD_ALLOC(); - IThreadInvoker* invokerBase = rawClone; - std::shared_ptr delegate(invokerBase, std::default_delete(), dmq::stl_allocator()); - - detail::DispatchAsync(delegate, m_state.GetThread(), m_state.GetPriority(), std::forward(args)...); - - // Do not wait for destination thread return value from async function call - return RetType(); - } - - /// @brief Invoke delegate function asynchronously. Do not wait for return value. - /// Called by the source thread. Always safe to call. - /// @param[in] args The function arguments, if any. - void AsyncInvoke(Args... args) { - operator()(std::forward(args)...); - } - - /// @brief Invoke the delegate function on the destination thread. Called by the - /// destintation thread. - /// @details Each source thread call to `operator()` generate a call to `Invoke()` - /// on the destination thread. Unlike `DelegateAsyncWait`, a lock is not required between - /// source and destination `delegateMsg` access because the source thread is not waiting - /// for the function call to complete. - /// @param[in] msg The delegate message created and sent within `operator()(Args... args)`. - /// @return `true` if target function invoked; `false` if error. - virtual bool Invoke(std::shared_ptr msg) override { - // Typecast the base pointer to back correct derived to instance - auto delegateMsg = std::dynamic_pointer_cast>(msg); - if (delegateMsg == nullptr) - return false; - - // Call the target with the message's stored arguments: a qualified, non-virtual - // call, so there is no copy of the argument tuple and no virtual hop back through - // operator(). Each argument is forwarded as declared: by-value arguments are moved - // out of the message (each message is invoked exactly once), references bind to - // the stored copies. - std::apply([this](auto&... args) { this->BaseType::operator()(std::forward(args)...); }, - delegateMsg->GetArgs()); - return true; - } - - /// @brief Get the destination thread that the target function is invoked on. - /// @return The target thread. - IThread* GetThread() const noexcept { return m_state.GetThread(); } - - /// @brief Get the delegate message priority - /// @return Delegate message priority - Priority GetPriority() const noexcept { return m_state.GetPriority(); } - void SetPriority(Priority priority) noexcept { m_state.SetPriority(priority); } - -private: - /// Destination thread and message priority. Not templated on Sig/TClass — see - /// `detail::AsyncDispatchState`. - detail::AsyncDispatchState m_state; - - // -}; - -/// @brief Creates an asynchronous delegate that binds to a free function. -/// @tparam RetType The return type of the free function. -/// @tparam Args The types of the function arguments. -/// @param[in] func A pointer to the free function to bind to the delegate. -/// @param[in] thread The `IThread` on which the function will be invoked asynchronously. -/// @return A `DelegateFreeAsync` object bound to the specified free function and thread. -template -auto MakeDelegate(RetType(*func)(Args... args), IThread& thread) { - return DelegateFreeAsync(func, thread); -} - -/// @brief Creates an asynchronous delegate that binds to a non-const member function. -/// @tparam TClass The class type that contains the member function. -/// @tparam RetType The return type of the member function. -/// @tparam Args The types of the function arguments. -/// @param[in] object A pointer to the instance of `TClass` that will be used for the delegate. -/// @param[in] func A pointer to the non-const member function of `TClass` to bind to the delegate. -/// @param[in] thread The `IThread` on which the function will be invoked asynchronously. -/// @return A `DelegateMemberAsync` object bound to the specified non-const member function and thread. -template -auto MakeDelegate(TClass* object, RetType(TClass::* func)(Args... args), IThread& thread) { - return DelegateMemberAsync(object, func, thread); -} - -/// @brief Creates an asynchronous delegate that binds to a const member function. -/// @tparam TClass The class type that contains the const member function. -/// @tparam RetType The return type of the member function. -/// @tparam Args The types of the function arguments. -/// @param[in] object A pointer to the instance of `TClass` that will be used for the delegate. -/// @param[in] func A pointer to the const member function of `TClass` to bind to the delegate. -/// @param[in] thread The `IThread` on which the function will be invoked asynchronously. -/// @return A `DelegateMemberAsync` object bound to the specified const member function and thread. -template -auto MakeDelegate(TClass* object, RetType(TClass::* func)(Args... args) const, IThread& thread) { - return DelegateMemberAsync(object, func, thread); -} - -/// @brief Creates a delegate that binds to a const member function. -/// @tparam TClass The const class type that contains the const member function. -/// @tparam RetType The return type of the member function. -/// @tparam Args The types of the function arguments. -/// @param[in] object A pointer to the instance of `TClass` that will be used for the delegate. -/// @param[in] func A pointer to the non-const member function of `TClass` to bind to the delegate. -/// @param[in] thread The `IThread` on which the function will be invoked asynchronously. -/// @return A `DelegateMemberAsync` object bound to the specified non-const member function. -template -auto MakeDelegate(const TClass* object, RetType(TClass::* func)(Args... args) const, IThread& thread) { - return DelegateMemberAsync(object, func, thread); -} - -/// @brief Creates an asynchronous delegate that binds to a non-const member function using a shared pointer. -/// @tparam TClass The class type that contains the member function. -/// @tparam RetType The return type of the member function. -/// @tparam Args The types of the function arguments. -/// @param[in] object A shared pointer to the instance of `TClass` that will be used for the delegate. -/// @param[in] func A pointer to the non-const member function of `TClass` to bind to the delegate. -/// @param[in] thread The `IThread` on which the function will be invoked asynchronously. -/// @return A `DelegateMemberAsyncSp` (SAFE) bound to the specified non-const member function and thread. -template -auto MakeDelegate(std::shared_ptr object, RetVal(TClass::* func)(Args... args), IThread& thread) { - return DelegateMemberAsyncSp(object, func, thread); -} - - -/// @brief Creates an asynchronous delegate that binds to a const member function using a shared pointer. -/// @tparam TClass The class type that contains the member function. -/// @tparam RetVal The return type of the member function. -/// @tparam Args The types of the function arguments. -/// @param[in] object A shared pointer to the instance of `TClass` that will be used for the delegate. -/// @param[in] func A pointer to the const member function of `TClass` to bind to the delegate. -/// @param[in] thread The `IThread` on which the function will be invoked asynchronously. -/// @return A `DelegateMemberAsyncSp` (SAFE) bound to the specified const member function and thread. -template -auto MakeDelegate(std::shared_ptr object, RetVal(TClass::* func)(Args... args) const, IThread& thread) { - return DelegateMemberAsyncSp(object, func, thread); -} - -/// @brief Creates an asynchronous delegate that binds to a `std::function`. -/// @tparam RetType The return type of the `std::function`. -/// @tparam Args The types of the function arguments. -/// @param[in] func The `std::function` to bind to the delegate. -/// @param[in] thread The `IThread` on which the function will be invoked asynchronously. -/// @return A `DelegateFunctionAsync` object bound to the specified `std::function` and thread. -template -auto MakeDelegate(std::function func, IThread& thread) { - return DelegateFunctionAsync(func, thread); -} - -/// @brief Creates an asynchronous delegate that binds to a raw lambda or functor. -/// @tparam F The lambda or functor type. -/// @param[in] func The lambda or functor to bind. -/// @param[in] thread The `IThread` on which the function will be invoked asynchronously. -/// @return A `DelegateFunctionAsync` object bound to the specified lambda or functor and thread. -template ::value>> -auto MakeDelegate(F&& func, IThread& thread) { - using Sig = typename trait::function_traits::operator())>::function_type; - return DelegateFunctionAsync(std::forward(func), thread); -} - -} - -DMQ_OPTIMIZE_OFF - -#endif \ No newline at end of file diff --git a/DelegateMQ/delegate/DelegateAsyncWait.h b/DelegateMQ/delegate/DelegateAsyncWait.h deleted file mode 100644 index 0a85dc4..0000000 --- a/DelegateMQ/delegate/DelegateAsyncWait.h +++ /dev/null @@ -1,1891 +0,0 @@ -#ifndef _DELEGATE_ASYNC_WAIT_H -#define _DELEGATE_ASYNC_WAIT_H - -#include "DelegateOpt.h" -#ifdef DMQ_HAS_SEMAPHORE - -// DelegateAsyncWait.h -// @see https://github.com/DelegateMQ/DelegateMQ -// David Lafreniere, Aug 2020. - -/// @file -/// @brief Delegate "`AsyncWait`" series of classes used to invoke a function asynchronously and -/// block waiting for completion by the target thread. -/// -/// @details Asynchronous delegate that invokes the target function on the specified thread of control -/// and waits for the function to be executed or a timeout occurs. Use IsSuccess() to determine if -/// asynchronous call succeeded before using the return value and outgoing argument values. -/// -/// A `IThread` implementation is required to serialize and dispatch an async delegate onto -/// a destination thread of control. -/// -/// Delegate "`AsyncWait`" series of classes used to invoke a function asynchronously and wait for -/// completion by the destination target thread. Invoking a function asynchronously requires making -/// a clone of the object to be sent to the destination thread message queue. The destination thread -/// calls `Invoke()` to invoke the target function. The source thread blocks on a semaphore -/// waiting for the destination thread to complete the function invoke. If the caller timeout expires, -/// the target function is not invoked. -/// -/// The `m_lock` mutex is used to protect shared state data between the source and destination -/// threads using the two thread-safe functions below: -/// -/// `RetType operator()(Args... args)` - called by the source thread to initiate the async -/// function call. May throw `std::bad_alloc` if dynamic storage allocation fails and `DMQ_ASSERTS` -/// is not defined. Clone() also may throw `std::bad_alloc` unless 'DMQ_ASSERTS'. All other delegate -/// class functions do not throw exceptions. -/// -/// `void Invoke(std::shared_ptr msg)` - called by the destination -/// thread to invoke the target function. The destination thread must not call any other -/// delegate instance functions. -/// -/// Limitations: -/// -/// * Cannot use rvalue reference (T&&) as a target function argument. -/// -/// * The target function cannot return a `std::unique_ptr` since `AsyncWait` destination -/// target thread stores the return value (`m_retVal`) for later use by the calling source thread. -/// -/// * Cannot insert `DelegateMemberAsyncWait` into an ordered container. e.g. `std::list` ok, -/// `std::set` not ok. -/// -/// * `std::function` compares the function signature type, not the underlying object instance. -/// See `DelegateFunction<>` class for more info. -/// -/// Code within `` and `` is updated using src_dup.py. Manually update -/// the code within the `DelegateFreeAsyncWait` `common_code` tags, then run the script to -/// propagate to the remaining delegate classes to simplify code maintenance. -/// -/// `python src_dup.py DelegateAsyncWait.h` - -#include "Delegate.h" -#include "Semaphore.h" -#include "IThread.h" -#include "IInvoker.h" -#include -#include -#include -#include - -DMQ_OPTIMIZE_ON - -namespace dmq { - -// 1000 Hours (approx 41 days). -// Safe "infinite" wait that prevents integer overflow when added to current time -// on systems with nanosecond clock resolution (Linux/Windows). -constexpr auto WAIT_INFINITE = std::chrono::hours(1000); - -/// @brief Stores all function arguments suitable for blocking asynchronous calls. -/// Argument data is not stored in the heap. -/// @tparam Args The target function arguments. -template -class DelegateAsyncWaitMsg : public DelegateMsg -{ -public: - /// Constructor - /// @param[in] invoker - the invoker instance - /// @param[in] priority - the delegate message priority - /// @param[in] args - a parameter pack of all target function arguments - DelegateAsyncWaitMsg(std::shared_ptr invoker, Priority priority, Args... args) : DelegateMsg(invoker, priority), - m_args(std::forward(args)...) {} - - /// Delete the default constructor - DelegateAsyncWaitMsg() = delete; - - /// Delete the copy constructor - DelegateAsyncWaitMsg(const DelegateAsyncWaitMsg&) = delete; - - /// Delete the copy assignment operator - DelegateAsyncWaitMsg& operator=(const DelegateAsyncWaitMsg&) = delete; - - /// Delete the move constructor and move assignment - DelegateAsyncWaitMsg(DelegateAsyncWaitMsg&&) = delete; - DelegateAsyncWaitMsg& operator=(DelegateAsyncWaitMsg&&) = delete; - - virtual ~DelegateAsyncWaitMsg() = default; - - /// Release the blocked sender without invoking: its wait ends with the invoke - /// not succeeded (GetInvokeSucceeded() stays false), so the call reports failure. - void Cancel() override { m_sema.Signal(); } - - /// Get all function arguments - /// @return A tuple of all function arguments - std::tuple& GetArgs() { return m_args; } - - /// Get the semaphore used to signal the sending thread that the receiving - /// thread has invoked the target function. - /// @return The semaphore reference. - Semaphore& GetSema() { return m_sema; } - - /// Get a mutex shared between sender and receiver threads. - /// @return The lock reference. - Mutex& GetLock() { return m_lock; } - - /// True if the sending thread is waiting for the receiver thread to call the function. - /// False if the sending thread delegate timeout occurred and is not waiting. - /// @return `true` if the sending thread is waiting for the receiving thread to complete - /// the target function invoke. - bool GetInvokerWaiting() { return m_invokerWaiting; } - - /// Set to true when source thread is waiting for destination thread to complete the - /// function call. - /// @param[in] invokerWaiting The status of the invoker waiting flag. - void SetInvokerWaiting(bool invokerWaiting) { m_invokerWaiting = invokerWaiting; } - - /// True if the destination thread's target function invoke completed without an - /// exception propagating out of it. False if the target function threw (or hasn't - /// been invoked yet). Distinct from the source thread's semaphore wait succeeding: - /// the semaphore is always signaled on scope exit from `Invoke()`, including via an - /// exception, so this flag is what lets the source thread tell the two cases apart. - /// @return `true` if the target function invoke completed successfully. - bool GetInvokeSucceeded() { return m_invokeSucceeded; } - - /// Set to true by the destination thread immediately after the target function - /// invoke returns without throwing. - /// @param[in] invokeSucceeded The status of the invoke-succeeded flag. - void SetInvokeSucceeded(bool invokeSucceeded) { m_invokeSucceeded = invokeSucceeded; } - -private: - /// A tuple with each function argument element - std::tuple m_args; - - /// Semaphore to signal waiting thread - Semaphore m_sema; - - /// Lock to protect shared data - Mutex m_lock; - - /// True if source thread is waiting for destination thread invoke to complete - bool m_invokerWaiting = false; - - /// True once the destination thread's target function invoke has completed - /// without an exception propagating out of it - bool m_invokeSucceeded = false; -}; - -namespace detail { - -/// @brief Lock guarding every `DelegateXAsyncWait` instance's last-call result. -/// @details One lock shared by all instances rather than one per instance: each call -/// clones its delegate, and on RTOS ports a `dmq::Mutex` is a kernel object, so a -/// per-instance lock would create one on every call. It is held only to copy one -/// result in or out. Intentionally never destroyed (same as `Timer::GetLock()`), so a -/// delegate destroyed during static destruction can still use it. -inline RecursiveMutex& AsyncWaitResultLock() { - static RecursiveMutex* lock = new(std::nothrow) RecursiveMutex(); - if (!lock) - BAD_ALLOC(); - return *lock; -} - -/// @brief Non-template holder for a `DelegateXAsyncWait<...>` instance's dispatch state -/// (destination thread, message priority, timeout, and whether the last async call -/// succeeded). The last call's return value is stored, typed, on the owning delegate. -/// None of this depends on the bound function's signature or target class, so every -/// `DelegateFreeAsyncWait`/`DelegateMemberAsyncWait`/`DelegateMemberAsyncWaitSp`/ -/// `DelegateFunctionAsyncWait` instantiation composes this one definition instead of each -/// generating its own copy of these five fields plus their Assign()/Equal()/move-ctor -/// plumbing. -class AsyncWaitDispatchState { -public: - AsyncWaitDispatchState() = default; - - /// A copy takes the dispatch settings but not the last-call result. - AsyncWaitDispatchState(const AsyncWaitDispatchState& rhs) noexcept - : m_thread(rhs.m_thread), m_priority(rhs.m_priority), m_timeout(rhs.m_timeout) {} - - AsyncWaitDispatchState& operator=(const AsyncWaitDispatchState& rhs) noexcept { - if (this != &rhs) { - m_thread = rhs.m_thread; - m_priority = rhs.m_priority; - m_timeout = rhs.m_timeout; - ResetResult(); - } - return *this; - } - - IThread* GetThread() const noexcept { return m_thread; } - void SetThread(IThread* thread) noexcept { m_thread = thread; } - Priority GetPriority() const noexcept { return m_priority; } - void SetPriority(Priority priority) noexcept { m_priority = priority; } - Duration GetTimeout() const noexcept { return m_timeout; } - void SetTimeout(Duration timeout) noexcept { m_timeout = timeout; } - - bool IsSuccess() const noexcept { - const dmq::LockGuard lock(AsyncWaitResultLock()); - return m_success; - } - - /// Reset the last call's success flag. - void ResetResult() noexcept { - const dmq::LockGuard lock(AsyncWaitResultLock()); - m_success = false; - } - - /// Record whether the last call succeeded. - void SetSuccess(bool success) noexcept { - const dmq::LockGuard lock(AsyncWaitResultLock()); - m_success = success; - } - - bool Equal(const AsyncWaitDispatchState& rhs) const noexcept { - return m_thread == rhs.m_thread && m_priority == rhs.m_priority && m_timeout == rhs.m_timeout; - } - -private: - IThread* m_thread = nullptr; - Priority m_priority = Priority::NORMAL; - Duration m_timeout = WAIT_INFINITE; - bool m_success = false; -}; - -/// @brief Builds the argument message, dispatches it to `thread`, and waits (up to -/// `timeout`) for the destination thread to signal completion. -/// @details Templated only on `Args...`, not on the owning delegate's target-object or -/// return type, so this single instantiation is shared by every `DelegateXAsyncWait<...>` -/// signature that takes the same arguments, instead of each owning class generating its -/// own copy of this logic. -/// @param[in] invoker The already-cloned delegate to invoke on the destination thread, -/// type-erased through `IThreadInvoker`. -/// @param[in] thread The destination thread, or `nullptr` if unbound. -/// @param[in] priority The message priority. -/// @param[in] timeout How long to wait for the destination thread to invoke the function. -/// @param[in] args The function arguments, if any. -/// @return `true` if the destination thread invoked the target function and the invoke -/// completed without an exception propagating out of it; `false` otherwise. A call that -/// had already started when `timeout` expired is waited for and counts as success. -/// The caller is responsible for pulling the return value off its own cloned delegate -/// (written there by `Invoke()` on the destination thread) when this returns `true`. -template -bool DispatchAsyncWait(std::shared_ptr invoker, IThread* thread, Priority priority, - Duration timeout, Args&&... args) { - // Create a new message instance for sending to the destination thread. Erase to - // the non-templated DelegateMsg base BEFORE constructing the shared_ptr (rather - // than xmake_shared>) so the shared_ptr control - // block is not templated on Args... -- one control-block type is then shared - // across every DelegateAsyncWait signature instead of duplicated per signature. - // `rawMsg` stays valid for the whole function (kept alive by `msg`) and is used - // for every access specific to the concrete DelegateAsyncWaitMsg type; - // `msg` itself is only needed, as the erased base, for DispatchDelegate(). - auto* rawMsg = new(std::nothrow) DelegateAsyncWaitMsg(std::move(invoker), priority, std::forward(args)...); - if (!rawMsg) - BAD_ALLOC(); - DelegateMsg* msgBase = rawMsg; - std::shared_ptr msg(msgBase, std::default_delete(), dmq::stl_allocator()); - rawMsg->SetInvokerWaiting(true); - - if (thread) { - // Dispatch message onto the callback destination thread. Invoke() - // will be called by the destination thread. - if (thread->DispatchDelegate(msg)) { - // Wait for destination thread to execute the delegate function and get return value - // Its result isn't needed: GetInvokeSucceeded() below is the answer. - (void)rawMsg->GetSema().Wait(timeout); - } - } - - // Single lock: read the result and clear InvokerWaiting atomically. Invoke() - // holds this lock for the whole target call, so once it's acquired the call has - // either completed or will never run (InvokerWaiting is cleared below). - const dmq::LockGuard lock(rawMsg->GetLock()); - // Success means the target call completed without throwing -- including a call - // that was already running when the timeout expired (the lock above waited for - // it). The semaphore is signaled even when the target threw or the message was - // cancelled, so the wait succeeding doesn't mean the call succeeded. - bool success = rawMsg->GetInvokeSucceeded(); - // Set flag that source is not waiting anymore - rawMsg->SetInvokerWaiting(false); - return success; -} - -} // namespace detail - -template -class DelegateFreeAsyncWait; // Not defined - -/// @brief `DelegateFreeAsyncWait<>` class asynchronously block invokes a free target function. -/// @tparam RetType The return type of the bound delegate function. -/// @tparam Args The argument types of the bound delegate function. -template -class DelegateFreeAsyncWait : public DelegateFree, public IThreadInvoker { -public: - typedef RetType(*FreeFunc)(Args...); - using ClassType = DelegateFreeAsyncWait; - using BaseType = DelegateFree; - - static_assert(!(std::disjunction_v...>), - "Non-const std::shared_ptr reference/pointer arguments are not allowed"); - - /// @brief Constructor to create a class instance. - /// @param[in] func The target free function to store. - /// @param[in] thread The execution thread to invoke `func`. - /// @param[in] timeout The calling thread timeout for destination thread to - /// invoke the target function. - DelegateFreeAsyncWait(FreeFunc func, IThread& thread, Duration timeout = WAIT_INFINITE) : - BaseType(func) { - Bind(func, thread, timeout); - } - - /// @brief Copy constructor that creates a copy of the given instance. - /// @details This constructor initializes a new object as a copy of the - /// provided `rhs` (right-hand side) object. The `rhs` object is used to - /// set the state of the new instance. - /// @param[in] rhs The object to copy from. - DelegateFreeAsyncWait(const ClassType& rhs) : - BaseType(rhs) { - Assign(rhs); - } - - /// @brief Move constructor that transfers ownership of resources. - /// @param[in] rhs The object to move from. - DelegateFreeAsyncWait(ClassType&& rhs) noexcept : - BaseType(std::move(rhs)), m_state(rhs.m_state) { - rhs.Clear(); - } - - DelegateFreeAsyncWait() = default; - - /// @brief Bind a free function to the delegate. - /// @details This method associates a free function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] func The free function to bind to the delegate. This function must - /// match the signature of the delegate. - /// @param[in] thread The execution thread to invoke `func`. - /// @param[in] timeout The calling thread timeout for destination thread to - /// invoke the target function. - void Bind(FreeFunc func, IThread& thread, Duration timeout = WAIT_INFINITE) { - m_state.SetThread(&thread); - m_state.SetTimeout(timeout); - BaseType::Bind(func); - } - - // - - /// @brief Assigns the state of one object to another. - /// @details Copy the state from the `rhs` (right-hand side) object to the - /// current object. - /// @param[in] rhs The object whose state is to be copied. - void Assign(const ClassType& rhs) { - m_state = rhs.m_state; - m_retVal.reset(); - BaseType::Assign(rhs); - } - - /// @brief Creates a copy of the current object. - /// @details Clones the current instance of the class by creating a new object - /// and copying the state of the current object to it. - /// @return A pointer to a new `ClassType` instance or nullptr if allocation fails. - /// @post The caller is responsible for deleting the clone object and checking for - /// nullptr. - virtual ClassType* Clone() const override { - return new(std::nothrow) ClassType(*this); - } - - /// @brief Assignment operator that assigns the state of one object to another. - /// @param[in] rhs The object whose state is to be assigned to the current object. - /// @return A reference to the current object. - ClassType& operator=(const ClassType& rhs) { - if (&rhs != this) { - BaseType::operator=(rhs); - Assign(rhs); - } - return *this; - } - - /// @brief Move assignment operator that transfers ownership of resources. - /// @param[in] rhs The object to move from. - /// @return A reference to the current object. - ClassType& operator=(ClassType&& rhs) noexcept { - if (&rhs != this) { - BaseType::operator=(std::move(rhs)); - m_state = rhs.m_state; // Use the resource - m_retVal.reset(); - rhs.Clear(); - } - return *this; - } - - /// @brief Clear the target function. - virtual void operator=(std::nullptr_t) noexcept override { - return this->Clear(); - } - - /// @brief Compares two delegate objects for equality. - /// @param[in] rhs The `DelegateBase` object to compare with the current object. - /// @return `true` if the two delegate objects are equal, `false` otherwise. - virtual bool Equal(const DelegateBase& rhs) const override { - auto derivedRhs = dynamic_cast(&rhs); - return derivedRhs && - m_state.Equal(derivedRhs->m_state) && - BaseType::Equal(rhs); - } - - /// Compares two delegate objects for equality. - /// @return `true` if the objects are equal, `false` otherwise. - bool operator==(const ClassType& rhs) const noexcept { return Equal(rhs); } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - virtual bool operator==(std::nullptr_t) const noexcept override { - return this->Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - virtual bool operator!=(std::nullptr_t) const noexcept override { - return !this->Empty(); - } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - friend bool operator==(std::nullptr_t, const ClassType& rhs) noexcept { - return rhs.Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - friend bool operator!=(std::nullptr_t, const ClassType& rhs) noexcept { - return !rhs.Empty(); - } - - /// @brief Invoke delegate function asynchronously and block for function return value. - /// Called by the source thread. - /// @details Invoke delegate function asynchronously and wait for the return value. - /// This function is called by the source thread. Dispatches the delegate data into the - /// destination thread message queue. `Invoke()` must be called by the destination - /// thread to invoke the target function. Always safe to call. - /// - /// If the destination thread invokes the function within `m_timeout`, the return - /// value is obtained from the destination thread function call. If `m_timeout` expires - /// before the destination thread starts the call, the target function is not invoked - /// and a default return value is returned. If the call has already started when - /// `m_timeout` expires, the caller waits for it to finish and gets its return value. - /// Use `IsSuccess()` to check for success before using the return value. Alternatively, - /// use `AsyncInvoke()` and check the `std::optional` return value. - /// - /// The `DelegateAsyncWaitMsg` does not duplicate and copy the function arguments into heap - /// memory. The source thread waits on the destintation thread to complete, therefore argument - /// data is shared between the source and destination threads and simultaneous access is prevented - /// using a mutex. - /// @param[in] args The function arguments, if any. - /// @return The bound function return value, if any. Use `IsSuccess()` to determine if - /// the return value is valid before use. - virtual RetType operator()(Args... args) override { - // The result lives in locals, so concurrent callers sharing this instance - // (e.g. one Signal emitted from two threads) each get their own return value. - std::optional retVal; - bool success = DispatchWait(retVal, std::forward(args)...); - SetLastResult(success, retVal); - - if constexpr (std::is_void::value == false) { - return success ? TakeRet(retVal) : RetType(); - } - } - - /// @brief Invoke delegate function asynchronously and block for function return value. - /// Called by the source thread. Always safe to call, including concurrently. - /// @param[in] args The function arguments, if any. - /// @return The bound function return value stored withing `std::optional`. Use - /// `has_value()` to check if the the return value is valid. `value()` contains - /// the target function return value. - auto AsyncInvoke(Args... args) { - std::optional retVal; - bool success = DispatchWait(retVal, std::forward(args)...); - SetLastResult(success, retVal); - - if constexpr (std::is_void::value == true) { - return success ? std::optional(true) : std::optional(); - } else { - return success ? std::optional(TakeRet(retVal)) : std::optional(); - } - } - - /// @brief Invoke the delegate function on the destination thread. Called by the - /// destination thread. - /// @details Each source thread call to `operator()` generate a call to `Invoke()` - /// on the destination thread. A lock is used to protect source and destination thread shared - /// data. A semaphore is used to signal the source thread when the destination thread - /// completes the target function call. - /// - /// If source thread timeout expires and before the destination thread invokes the - /// target function, the target function is not called. - /// @param[in] msg The delegate message created and sent within `operator()(Args... args)`. - /// @return `true` if target function invoked or timeout expired; `false` if error. - virtual bool Invoke(std::shared_ptr msg) override { - static_assert(!(is_unique_ptr::value), "std::unique_ptr return value not allowed"); - - // Typecast the base pointer to back correct derived to instance - auto delegateMsg = std::dynamic_pointer_cast>(msg); - if (delegateMsg == nullptr) - return false; - - // Protect data shared between source and destination threads - const dmq::LockGuard lock(delegateMsg->GetLock()); - - // Is the source thread waiting for the target function invoke to complete? - if (delegateMsg->GetInvokerWaiting()) { - // Signals the source thread when this scope exits, including via an exception - // propagating out of the target function invoke below. Without this, a target - // function that throws would leave the source thread blocked until timeout. - struct SemaSignalGuard { - Semaphore& sema; - ~SemaSignalGuard() { sema.Signal(); } - } semaSignalGuard{ delegateMsg->GetSema() }; - - // Does target function have a void return value? - if constexpr (std::is_void::value == true) { - // Call the target with the message's stored arguments: a qualified, non-virtual - // call, so there is no copy of the argument tuple and no virtual hop back through - // operator(). Each argument is forwarded as declared: by-value arguments are moved - // out of the message (each message is invoked exactly once), references bind to - // the stored copies. - std::apply([this](auto&... args) { this->BaseType::operator()(std::forward(args)...); }, - delegateMsg->GetArgs()); - } else { - // As above, and keep the return value (in this clone's typed slot). - m_retVal.emplace(std::apply( - [this](auto&... args) -> RetType { return this->BaseType::operator()(std::forward(args)...); }, - delegateMsg->GetArgs())); - } - - // Only reached if the std::apply() call above did not throw - delegateMsg->SetInvokeSucceeded(true); - } - return true; - } - - /// Returns `true` if the last asynchronous call on this delegate succeeded. - /// @return `true` if the target asynchronous function call succeeded. `false` if - /// the timeout expired before the target function could be invoked. - /// @note If several threads call this delegate concurrently, this reports whichever - /// call finished last. Use `AsyncInvoke()`'s return value to get each call's own result. - bool IsSuccess() noexcept { return m_state.IsSuccess(); } - - /// Get the asynchronous function return value of the last call on this delegate. - /// @return The destination thread target function return value - /// @note Same caveat as `IsSuccess()` for concurrent callers. - RetType GetRetVal() noexcept { - if constexpr (std::is_void::value == false) { - std::optional copy; - { - const dmq::LockGuard lock(detail::AsyncWaitResultLock()); - copy = m_retVal; - } - return TakeRet(copy); - } - } - ///@brief Get the destination thread that the target function is invoked on. - // @return The target thread. - IThread* GetThread() noexcept { return m_state.GetThread(); } - - /// @brief Get the delegate message priority - /// @return Delegate message priority - Priority GetPriority() const noexcept { return m_state.GetPriority(); } - void SetPriority(Priority priority) noexcept { m_state.SetPriority(priority); } - -private: - /// Return value storage type (std::optional can't hold void). - using RetStorage = std::conditional_t::value, bool, std::decay_t>; - - /// Dispatch to the destination thread and wait (up to the timeout) for the call. - /// @param[out] retVal The target function's return value, set when this returns `true`. - /// @return `true` if the target function was invoked and completed. - bool DispatchWait(std::optional& retVal, Args&&... args) { - if (this->Empty()) - return false; - - // Create a clone instance of this delegate. Erase to the non-templated - // IThreadInvoker interface BEFORE constructing the shared_ptr (rather than - // xmake_shared) so the shared_ptr control block is not templated - // on RetType/Args... -- one control-block type is then shared across every - // DelegateAsyncWait kind and signature instead of duplicated per signature. - // `rawClone` stays valid for the whole function (kept alive by `delegate`) - // and is used below to read back the clone's own result state. - ClassType* rawClone = this->Clone(); - if (!rawClone) - BAD_ALLOC(); - IThreadInvoker* invokerBase = rawClone; - std::shared_ptr delegate(invokerBase, std::default_delete(), dmq::stl_allocator()); - - bool success = detail::DispatchAsyncWait(delegate, m_state.GetThread(), m_state.GetPriority(), - m_state.GetTimeout(), std::forward(args)...); - if (success) { - // Invoke() (running as the clone, on the destination thread) wrote the - // target function's return value into the clone's own m_retVal. - retVal = std::move(rawClone->m_retVal); - } - return success; - } - - /// Move the value out of `v`, or return a default value if it holds none. - static RetType TakeRet(std::optional& v) noexcept { - if (v) return std::move(*v); -#if defined(DMQ_ASSERTS) - DMQ_ASSERT(); // no result stored (e.g. GetRetVal() before any successful call) -#endif - return RetType(); - } - - /// Record a call's result as this delegate's last result, for IsSuccess()/GetRetVal(). - void SetLastResult(bool success, const std::optional& retVal) { - const dmq::LockGuard lock(detail::AsyncWaitResultLock()); - m_state.SetSuccess(success); - m_retVal = retVal; - } - - /// Destination thread, message priority, timeout, and whether the last async call - /// succeeded. Not templated on Sig/TClass — see `detail::AsyncWaitDispatchState`. - detail::AsyncWaitDispatchState m_state; - - /// Return value, typed so a large return type needs no heap allocation (std::any - /// put anything over its small buffer on the global heap). On the per-call clone: - /// that call's result, written by Invoke() on the destination thread and read by - /// the caller after the message lock. On the caller's delegate: the last call's - /// result for GetRetVal(), guarded by detail::AsyncWaitResultLock(). - std::optional m_retVal; - - // -}; - -template -class DelegateMemberAsyncWait; // Not defined - -/// @brief `DelegateMemberAsyncWait<>` class asynchronously block invokes a class member target function. -/// @tparam TClass The class type that contains the member function. -/// @tparam RetType The return type of the bound delegate function. -/// @tparam Args The argument types of the bound delegate function. -template -class DelegateMemberAsyncWait : public DelegateMember, public IThreadInvoker { -public: - typedef TClass* ObjectPtr; - typedef std::shared_ptr SharedPtr; - typedef RetType(TClass::* MemberFunc)(Args...); - typedef RetType(TClass::* ConstMemberFunc)(Args...) const; - using ClassType = DelegateMemberAsyncWait; - using BaseType = DelegateMember; - - static_assert(!(std::disjunction_v...>), - "Non-const std::shared_ptr reference/pointer arguments are not allowed"); - - /// @brief Constructor to create a class instance. - /// @param[in] object The target object pointer to store. - /// @param[in] func The target member function to store. - /// @param[in] thread The execution thread to invoke `func`. - /// @param[in] timeout The calling thread timeout for destination thread to - /// invoke the target function. - DelegateMemberAsyncWait(SharedPtr object, MemberFunc func, IThread& thread, Duration timeout = WAIT_INFINITE) : - BaseType(object, func) { - Bind(object, func, thread, timeout); - } - - /// @brief Constructor to create a class instance. - /// @param[in] object The target object pointer to store. - /// @param[in] func The target const member function to store. - /// @param[in] thread The execution thread to invoke `func`. - /// @param[in] timeout The calling thread timeout for destination thread to - /// invoke the target function. - DelegateMemberAsyncWait(SharedPtr object, ConstMemberFunc func, IThread& thread, Duration timeout) : - BaseType(object, func) { - Bind(object, func, thread, timeout); - } - - /// @brief Constructor to create a class instance. - /// @param[in] object The target object pointer to store. - /// @param[in] func The target member function to store. - /// @param[in] thread The execution thread to invoke `func`. - /// @param[in] timeout The calling thread timeout for destination thread to - /// invoke the target function. - DelegateMemberAsyncWait(ObjectPtr object, MemberFunc func, IThread& thread, Duration timeout = WAIT_INFINITE) : - BaseType(object, func) { - Bind(object, func, thread, timeout); - } - - /// @brief Constructor to create a class instance. - /// @param[in] object The target object pointer to store. - /// @param[in] func The target const member function to store. - /// @param[in] thread The execution thread to invoke `func`. - /// @param[in] timeout The calling thread timeout for destination thread to - /// invoke the target function. - DelegateMemberAsyncWait(ObjectPtr object, ConstMemberFunc func, IThread& thread, Duration timeout) : - BaseType(object, func) { - Bind(object, func, thread, timeout); - } - - /// @brief Copy constructor that creates a copy of the given instance. - /// @details This constructor initializes a new object as a copy of the - /// provided `rhs` (right-hand side) object. The `rhs` object is used to - /// set the state of the new instance. - /// @param[in] rhs The object to copy from. - DelegateMemberAsyncWait(const ClassType& rhs) : - BaseType(rhs) { - Assign(rhs); - } - - /// @brief Move constructor that transfers ownership of resources. - /// @param[in] rhs The object to move from. - DelegateMemberAsyncWait(ClassType&& rhs) noexcept : - BaseType(std::move(rhs)), m_state(rhs.m_state) { - rhs.Clear(); - } - - DelegateMemberAsyncWait() = default; - - /// @brief Bind a member function to the delegate. - /// @details This method associates a member function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] object The target object instance. - /// @param[in] func The function to bind to the delegate. This function must match - /// the signature of the delegate. - /// @param[in] thread The execution thread to invoke `func`. - /// @param[in] timeout The calling thread timeout for destination thread to - /// invoke the target function. - void Bind(SharedPtr object, MemberFunc func, IThread& thread, Duration timeout = WAIT_INFINITE) { - m_state.SetThread(&thread); - m_state.SetTimeout(timeout); - BaseType::Bind(object, func); - } - - /// @brief Bind a const member function to the delegate. - /// @details This method associates a member function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] object The target object instance. - /// @param[in] func The member function to bind to the delegate. This function must - /// match the signature of the delegate. - /// @param[in] thread The execution thread to invoke `func`. - /// @param[in] timeout The calling thread timeout for destination thread to - /// invoke the target function. - void Bind(SharedPtr object, ConstMemberFunc func, IThread& thread, Duration timeout = WAIT_INFINITE) { - m_state.SetThread(&thread); - m_state.SetTimeout(timeout); - BaseType::Bind(object, func); - } - - /// @brief Bind a member function to the delegate. - /// @details This method associates a member function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] object The target object instance. - /// @param[in] func The function to bind to the delegate. This function must match - /// the signature of the delegate. - /// @param[in] thread The execution thread to invoke `func`. - /// @param[in] timeout The calling thread timeout for destination thread to - /// invoke the target function. - void Bind(ObjectPtr object, MemberFunc func, IThread& thread, Duration timeout = WAIT_INFINITE) { - m_state.SetThread(&thread); - m_state.SetTimeout(timeout); - BaseType::Bind(object, func); - } - - /// @brief Bind a const member function to the delegate. - /// @details This method associates a member function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] object The target object instance. - /// @param[in] func The member function to bind to the delegate. This function must - /// match the signature of the delegate. - /// @param[in] thread The execution thread to invoke `func`. - /// @param[in] timeout The calling thread timeout for destination thread to - /// invoke the target function. - void Bind(ObjectPtr object, ConstMemberFunc func, IThread& thread, Duration timeout = WAIT_INFINITE) { - m_state.SetThread(&thread); - m_state.SetTimeout(timeout); - BaseType::Bind(object, func); - } - - // - - /// @brief Assigns the state of one object to another. - /// @details Copy the state from the `rhs` (right-hand side) object to the - /// current object. - /// @param[in] rhs The object whose state is to be copied. - void Assign(const ClassType& rhs) { - m_state = rhs.m_state; - m_retVal.reset(); - BaseType::Assign(rhs); - } - - /// @brief Creates a copy of the current object. - /// @details Clones the current instance of the class by creating a new object - /// and copying the state of the current object to it. - /// @return A pointer to a new `ClassType` instance or nullptr if allocation fails. - /// @post The caller is responsible for deleting the clone object and checking for - /// nullptr. - virtual ClassType* Clone() const override { - return new(std::nothrow) ClassType(*this); - } - - /// @brief Assignment operator that assigns the state of one object to another. - /// @param[in] rhs The object whose state is to be assigned to the current object. - /// @return A reference to the current object. - ClassType& operator=(const ClassType& rhs) { - if (&rhs != this) { - BaseType::operator=(rhs); - Assign(rhs); - } - return *this; - } - - /// @brief Move assignment operator that transfers ownership of resources. - /// @param[in] rhs The object to move from. - /// @return A reference to the current object. - ClassType& operator=(ClassType&& rhs) noexcept { - if (&rhs != this) { - BaseType::operator=(std::move(rhs)); - m_state = rhs.m_state; // Use the resource - m_retVal.reset(); - rhs.Clear(); - } - return *this; - } - - /// @brief Clear the target function. - virtual void operator=(std::nullptr_t) noexcept override { - return this->Clear(); - } - - /// @brief Compares two delegate objects for equality. - /// @param[in] rhs The `DelegateBase` object to compare with the current object. - /// @return `true` if the two delegate objects are equal, `false` otherwise. - virtual bool Equal(const DelegateBase& rhs) const override { - auto derivedRhs = dynamic_cast(&rhs); - return derivedRhs && - m_state.Equal(derivedRhs->m_state) && - BaseType::Equal(rhs); - } - - /// Compares two delegate objects for equality. - /// @return `true` if the objects are equal, `false` otherwise. - bool operator==(const ClassType& rhs) const noexcept { return Equal(rhs); } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - virtual bool operator==(std::nullptr_t) const noexcept override { - return this->Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - virtual bool operator!=(std::nullptr_t) const noexcept override { - return !this->Empty(); - } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - friend bool operator==(std::nullptr_t, const ClassType& rhs) noexcept { - return rhs.Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - friend bool operator!=(std::nullptr_t, const ClassType& rhs) noexcept { - return !rhs.Empty(); - } - - /// @brief Invoke delegate function asynchronously and block for function return value. - /// Called by the source thread. - /// @details Invoke delegate function asynchronously and wait for the return value. - /// This function is called by the source thread. Dispatches the delegate data into the - /// destination thread message queue. `Invoke()` must be called by the destination - /// thread to invoke the target function. Always safe to call. - /// - /// If the destination thread invokes the function within `m_timeout`, the return - /// value is obtained from the destination thread function call. If `m_timeout` expires - /// before the destination thread starts the call, the target function is not invoked - /// and a default return value is returned. If the call has already started when - /// `m_timeout` expires, the caller waits for it to finish and gets its return value. - /// Use `IsSuccess()` to check for success before using the return value. Alternatively, - /// use `AsyncInvoke()` and check the `std::optional` return value. - /// - /// The `DelegateAsyncWaitMsg` does not duplicate and copy the function arguments into heap - /// memory. The source thread waits on the destintation thread to complete, therefore argument - /// data is shared between the source and destination threads and simultaneous access is prevented - /// using a mutex. - /// @param[in] args The function arguments, if any. - /// @return The bound function return value, if any. Use `IsSuccess()` to determine if - /// the return value is valid before use. - virtual RetType operator()(Args... args) override { - // The result lives in locals, so concurrent callers sharing this instance - // (e.g. one Signal emitted from two threads) each get their own return value. - std::optional retVal; - bool success = DispatchWait(retVal, std::forward(args)...); - SetLastResult(success, retVal); - - if constexpr (std::is_void::value == false) { - return success ? TakeRet(retVal) : RetType(); - } - } - - /// @brief Invoke delegate function asynchronously and block for function return value. - /// Called by the source thread. Always safe to call, including concurrently. - /// @param[in] args The function arguments, if any. - /// @return The bound function return value stored withing `std::optional`. Use - /// `has_value()` to check if the the return value is valid. `value()` contains - /// the target function return value. - auto AsyncInvoke(Args... args) { - std::optional retVal; - bool success = DispatchWait(retVal, std::forward(args)...); - SetLastResult(success, retVal); - - if constexpr (std::is_void::value == true) { - return success ? std::optional(true) : std::optional(); - } else { - return success ? std::optional(TakeRet(retVal)) : std::optional(); - } - } - - /// @brief Invoke the delegate function on the destination thread. Called by the - /// destination thread. - /// @details Each source thread call to `operator()` generate a call to `Invoke()` - /// on the destination thread. A lock is used to protect source and destination thread shared - /// data. A semaphore is used to signal the source thread when the destination thread - /// completes the target function call. - /// - /// If source thread timeout expires and before the destination thread invokes the - /// target function, the target function is not called. - /// @param[in] msg The delegate message created and sent within `operator()(Args... args)`. - /// @return `true` if target function invoked or timeout expired; `false` if error. - virtual bool Invoke(std::shared_ptr msg) override { - static_assert(!(is_unique_ptr::value), "std::unique_ptr return value not allowed"); - - // Typecast the base pointer to back correct derived to instance - auto delegateMsg = std::dynamic_pointer_cast>(msg); - if (delegateMsg == nullptr) - return false; - - // Protect data shared between source and destination threads - const dmq::LockGuard lock(delegateMsg->GetLock()); - - // Is the source thread waiting for the target function invoke to complete? - if (delegateMsg->GetInvokerWaiting()) { - // Signals the source thread when this scope exits, including via an exception - // propagating out of the target function invoke below. Without this, a target - // function that throws would leave the source thread blocked until timeout. - struct SemaSignalGuard { - Semaphore& sema; - ~SemaSignalGuard() { sema.Signal(); } - } semaSignalGuard{ delegateMsg->GetSema() }; - - // Does target function have a void return value? - if constexpr (std::is_void::value == true) { - // Call the target with the message's stored arguments: a qualified, non-virtual - // call, so there is no copy of the argument tuple and no virtual hop back through - // operator(). Each argument is forwarded as declared: by-value arguments are moved - // out of the message (each message is invoked exactly once), references bind to - // the stored copies. - std::apply([this](auto&... args) { this->BaseType::operator()(std::forward(args)...); }, - delegateMsg->GetArgs()); - } else { - // As above, and keep the return value (in this clone's typed slot). - m_retVal.emplace(std::apply( - [this](auto&... args) -> RetType { return this->BaseType::operator()(std::forward(args)...); }, - delegateMsg->GetArgs())); - } - - // Only reached if the std::apply() call above did not throw - delegateMsg->SetInvokeSucceeded(true); - } - return true; - } - - /// Returns `true` if the last asynchronous call on this delegate succeeded. - /// @return `true` if the target asynchronous function call succeeded. `false` if - /// the timeout expired before the target function could be invoked. - /// @note If several threads call this delegate concurrently, this reports whichever - /// call finished last. Use `AsyncInvoke()`'s return value to get each call's own result. - bool IsSuccess() noexcept { return m_state.IsSuccess(); } - - /// Get the asynchronous function return value of the last call on this delegate. - /// @return The destination thread target function return value - /// @note Same caveat as `IsSuccess()` for concurrent callers. - RetType GetRetVal() noexcept { - if constexpr (std::is_void::value == false) { - std::optional copy; - { - const dmq::LockGuard lock(detail::AsyncWaitResultLock()); - copy = m_retVal; - } - return TakeRet(copy); - } - } - ///@brief Get the destination thread that the target function is invoked on. - // @return The target thread. - IThread* GetThread() noexcept { return m_state.GetThread(); } - - /// @brief Get the delegate message priority - /// @return Delegate message priority - Priority GetPriority() const noexcept { return m_state.GetPriority(); } - void SetPriority(Priority priority) noexcept { m_state.SetPriority(priority); } - -private: - /// Return value storage type (std::optional can't hold void). - using RetStorage = std::conditional_t::value, bool, std::decay_t>; - - /// Dispatch to the destination thread and wait (up to the timeout) for the call. - /// @param[out] retVal The target function's return value, set when this returns `true`. - /// @return `true` if the target function was invoked and completed. - bool DispatchWait(std::optional& retVal, Args&&... args) { - if (this->Empty()) - return false; - - // Create a clone instance of this delegate. Erase to the non-templated - // IThreadInvoker interface BEFORE constructing the shared_ptr (rather than - // xmake_shared) so the shared_ptr control block is not templated - // on RetType/Args... -- one control-block type is then shared across every - // DelegateAsyncWait kind and signature instead of duplicated per signature. - // `rawClone` stays valid for the whole function (kept alive by `delegate`) - // and is used below to read back the clone's own result state. - ClassType* rawClone = this->Clone(); - if (!rawClone) - BAD_ALLOC(); - IThreadInvoker* invokerBase = rawClone; - std::shared_ptr delegate(invokerBase, std::default_delete(), dmq::stl_allocator()); - - bool success = detail::DispatchAsyncWait(delegate, m_state.GetThread(), m_state.GetPriority(), - m_state.GetTimeout(), std::forward(args)...); - if (success) { - // Invoke() (running as the clone, on the destination thread) wrote the - // target function's return value into the clone's own m_retVal. - retVal = std::move(rawClone->m_retVal); - } - return success; - } - - /// Move the value out of `v`, or return a default value if it holds none. - static RetType TakeRet(std::optional& v) noexcept { - if (v) return std::move(*v); -#if defined(DMQ_ASSERTS) - DMQ_ASSERT(); // no result stored (e.g. GetRetVal() before any successful call) -#endif - return RetType(); - } - - /// Record a call's result as this delegate's last result, for IsSuccess()/GetRetVal(). - void SetLastResult(bool success, const std::optional& retVal) { - const dmq::LockGuard lock(detail::AsyncWaitResultLock()); - m_state.SetSuccess(success); - m_retVal = retVal; - } - - /// Destination thread, message priority, timeout, and whether the last async call - /// succeeded. Not templated on Sig/TClass — see `detail::AsyncWaitDispatchState`. - detail::AsyncWaitDispatchState m_state; - - /// Return value, typed so a large return type needs no heap allocation (std::any - /// put anything over its small buffer on the global heap). On the per-call clone: - /// that call's result, written by Invoke() on the destination thread and read by - /// the caller after the message lock. On the caller's delegate: the last call's - /// result for GetRetVal(), guarded by detail::AsyncWaitResultLock(). - std::optional m_retVal; - - // -}; - -template -class DelegateMemberAsyncWaitSp; // Not defined - -/// @brief `DelegateMemberAsyncWaitSp<>` class asynchronously block invokes a class member target function -/// using a weak/shared pointer semantics. -/// @tparam TClass The class type that contains the member function. -/// @tparam RetType The return type of the bound delegate function. -/// @tparam Args The argument types of the bound delegate function. -template -class DelegateMemberAsyncWaitSp : public DelegateMemberSp, public IThreadInvoker { -public: - using SharedPtr = std::shared_ptr; - using MemberFunc = RetType(TClass::*)(Args...); - using ConstMemberFunc = RetType(TClass::*)(Args...) const; - using ClassType = DelegateMemberAsyncWaitSp; - using BaseType = DelegateMemberSp; - - static_assert(!(std::disjunction_v...>), - "Non-const std::shared_ptr reference/pointer arguments are not allowed"); - - /// @brief Constructor for non-const member function - DelegateMemberAsyncWaitSp(SharedPtr object, MemberFunc func, IThread& thread, Duration timeout = WAIT_INFINITE) : - BaseType(object, func) { - Bind(object, func, thread, timeout); - } - - /// @brief Constructor for const member function - DelegateMemberAsyncWaitSp(SharedPtr object, ConstMemberFunc func, IThread& thread, Duration timeout = WAIT_INFINITE) : - BaseType(object, func) { - Bind(object, func, thread, timeout); - } - - /// @brief Copy constructor - DelegateMemberAsyncWaitSp(const ClassType& rhs) : - BaseType(rhs) { - Assign(rhs); - } - - /// @brief Move constructor - DelegateMemberAsyncWaitSp(ClassType&& rhs) noexcept : - BaseType(std::move(rhs)), m_state(rhs.m_state) { - rhs.Clear(); - } - - DelegateMemberAsyncWaitSp() = default; - - /// @brief Bind a non-const member function - void Bind(SharedPtr object, MemberFunc func, IThread& thread, Duration timeout = WAIT_INFINITE) { - m_state.SetThread(&thread); - m_state.SetTimeout(timeout); - BaseType::Bind(object, func); - } - - /// @brief Bind a const member function - void Bind(SharedPtr object, ConstMemberFunc func, IThread& thread, Duration timeout = WAIT_INFINITE) { - m_state.SetThread(&thread); - m_state.SetTimeout(timeout); - BaseType::Bind(object, func); - } - - // - - /// @brief Assigns the state of one object to another. - /// @details Copy the state from the `rhs` (right-hand side) object to the - /// current object. - /// @param[in] rhs The object whose state is to be copied. - void Assign(const ClassType& rhs) { - m_state = rhs.m_state; - m_retVal.reset(); - BaseType::Assign(rhs); - } - - /// @brief Creates a copy of the current object. - /// @details Clones the current instance of the class by creating a new object - /// and copying the state of the current object to it. - /// @return A pointer to a new `ClassType` instance or nullptr if allocation fails. - /// @post The caller is responsible for deleting the clone object and checking for - /// nullptr. - virtual ClassType* Clone() const override { - return new(std::nothrow) ClassType(*this); - } - - /// @brief Assignment operator that assigns the state of one object to another. - /// @param[in] rhs The object whose state is to be assigned to the current object. - /// @return A reference to the current object. - ClassType& operator=(const ClassType& rhs) { - if (&rhs != this) { - BaseType::operator=(rhs); - Assign(rhs); - } - return *this; - } - - /// @brief Move assignment operator that transfers ownership of resources. - /// @param[in] rhs The object to move from. - /// @return A reference to the current object. - ClassType& operator=(ClassType&& rhs) noexcept { - if (&rhs != this) { - BaseType::operator=(std::move(rhs)); - m_state = rhs.m_state; // Use the resource - m_retVal.reset(); - rhs.Clear(); - } - return *this; - } - - /// @brief Clear the target function. - virtual void operator=(std::nullptr_t) noexcept override { - return this->Clear(); - } - - /// @brief Compares two delegate objects for equality. - /// @param[in] rhs The `DelegateBase` object to compare with the current object. - /// @return `true` if the two delegate objects are equal, `false` otherwise. - virtual bool Equal(const DelegateBase& rhs) const override { - auto derivedRhs = dynamic_cast(&rhs); - return derivedRhs && - m_state.Equal(derivedRhs->m_state) && - BaseType::Equal(rhs); - } - - /// Compares two delegate objects for equality. - /// @return `true` if the objects are equal, `false` otherwise. - bool operator==(const ClassType& rhs) const noexcept { return Equal(rhs); } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - virtual bool operator==(std::nullptr_t) const noexcept override { - return this->Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - virtual bool operator!=(std::nullptr_t) const noexcept override { - return !this->Empty(); - } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - friend bool operator==(std::nullptr_t, const ClassType& rhs) noexcept { - return rhs.Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - friend bool operator!=(std::nullptr_t, const ClassType& rhs) noexcept { - return !rhs.Empty(); - } - - /// @brief Invoke delegate function asynchronously and block for function return value. - /// Called by the source thread. - /// @details Invoke delegate function asynchronously and wait for the return value. - /// This function is called by the source thread. Dispatches the delegate data into the - /// destination thread message queue. `Invoke()` must be called by the destination - /// thread to invoke the target function. Always safe to call. - /// - /// If the destination thread invokes the function within `m_timeout`, the return - /// value is obtained from the destination thread function call. If `m_timeout` expires - /// before the destination thread starts the call, the target function is not invoked - /// and a default return value is returned. If the call has already started when - /// `m_timeout` expires, the caller waits for it to finish and gets its return value. - /// Use `IsSuccess()` to check for success before using the return value. Alternatively, - /// use `AsyncInvoke()` and check the `std::optional` return value. - /// - /// The `DelegateAsyncWaitMsg` does not duplicate and copy the function arguments into heap - /// memory. The source thread waits on the destintation thread to complete, therefore argument - /// data is shared between the source and destination threads and simultaneous access is prevented - /// using a mutex. - /// @param[in] args The function arguments, if any. - /// @return The bound function return value, if any. Use `IsSuccess()` to determine if - /// the return value is valid before use. - virtual RetType operator()(Args... args) override { - // The result lives in locals, so concurrent callers sharing this instance - // (e.g. one Signal emitted from two threads) each get their own return value. - std::optional retVal; - bool success = DispatchWait(retVal, std::forward(args)...); - SetLastResult(success, retVal); - - if constexpr (std::is_void::value == false) { - return success ? TakeRet(retVal) : RetType(); - } - } - - /// @brief Invoke delegate function asynchronously and block for function return value. - /// Called by the source thread. Always safe to call, including concurrently. - /// @param[in] args The function arguments, if any. - /// @return The bound function return value stored withing `std::optional`. Use - /// `has_value()` to check if the the return value is valid. `value()` contains - /// the target function return value. - auto AsyncInvoke(Args... args) { - std::optional retVal; - bool success = DispatchWait(retVal, std::forward(args)...); - SetLastResult(success, retVal); - - if constexpr (std::is_void::value == true) { - return success ? std::optional(true) : std::optional(); - } else { - return success ? std::optional(TakeRet(retVal)) : std::optional(); - } - } - - /// @brief Invoke the delegate function on the destination thread. Called by the - /// destination thread. - /// @details Each source thread call to `operator()` generate a call to `Invoke()` - /// on the destination thread. A lock is used to protect source and destination thread shared - /// data. A semaphore is used to signal the source thread when the destination thread - /// completes the target function call. - /// - /// If source thread timeout expires and before the destination thread invokes the - /// target function, the target function is not called. - /// @param[in] msg The delegate message created and sent within `operator()(Args... args)`. - /// @return `true` if target function invoked or timeout expired; `false` if error. - virtual bool Invoke(std::shared_ptr msg) override { - static_assert(!(is_unique_ptr::value), "std::unique_ptr return value not allowed"); - - // Typecast the base pointer to back correct derived to instance - auto delegateMsg = std::dynamic_pointer_cast>(msg); - if (delegateMsg == nullptr) - return false; - - // Protect data shared between source and destination threads - const dmq::LockGuard lock(delegateMsg->GetLock()); - - // Is the source thread waiting for the target function invoke to complete? - if (delegateMsg->GetInvokerWaiting()) { - // Signals the source thread when this scope exits, including via an exception - // propagating out of the target function invoke below. Without this, a target - // function that throws would leave the source thread blocked until timeout. - struct SemaSignalGuard { - Semaphore& sema; - ~SemaSignalGuard() { sema.Signal(); } - } semaSignalGuard{ delegateMsg->GetSema() }; - - // Does target function have a void return value? - if constexpr (std::is_void::value == true) { - // Call the target with the message's stored arguments: a qualified, non-virtual - // call, so there is no copy of the argument tuple and no virtual hop back through - // operator(). Each argument is forwarded as declared: by-value arguments are moved - // out of the message (each message is invoked exactly once), references bind to - // the stored copies. - std::apply([this](auto&... args) { this->BaseType::operator()(std::forward(args)...); }, - delegateMsg->GetArgs()); - } else { - // As above, and keep the return value (in this clone's typed slot). - m_retVal.emplace(std::apply( - [this](auto&... args) -> RetType { return this->BaseType::operator()(std::forward(args)...); }, - delegateMsg->GetArgs())); - } - - // Only reached if the std::apply() call above did not throw - delegateMsg->SetInvokeSucceeded(true); - } - return true; - } - - /// Returns `true` if the last asynchronous call on this delegate succeeded. - /// @return `true` if the target asynchronous function call succeeded. `false` if - /// the timeout expired before the target function could be invoked. - /// @note If several threads call this delegate concurrently, this reports whichever - /// call finished last. Use `AsyncInvoke()`'s return value to get each call's own result. - bool IsSuccess() noexcept { return m_state.IsSuccess(); } - - /// Get the asynchronous function return value of the last call on this delegate. - /// @return The destination thread target function return value - /// @note Same caveat as `IsSuccess()` for concurrent callers. - RetType GetRetVal() noexcept { - if constexpr (std::is_void::value == false) { - std::optional copy; - { - const dmq::LockGuard lock(detail::AsyncWaitResultLock()); - copy = m_retVal; - } - return TakeRet(copy); - } - } - ///@brief Get the destination thread that the target function is invoked on. - // @return The target thread. - IThread* GetThread() noexcept { return m_state.GetThread(); } - - /// @brief Get the delegate message priority - /// @return Delegate message priority - Priority GetPriority() const noexcept { return m_state.GetPriority(); } - void SetPriority(Priority priority) noexcept { m_state.SetPriority(priority); } - -private: - /// Return value storage type (std::optional can't hold void). - using RetStorage = std::conditional_t::value, bool, std::decay_t>; - - /// Dispatch to the destination thread and wait (up to the timeout) for the call. - /// @param[out] retVal The target function's return value, set when this returns `true`. - /// @return `true` if the target function was invoked and completed. - bool DispatchWait(std::optional& retVal, Args&&... args) { - if (this->Empty()) - return false; - - // Create a clone instance of this delegate. Erase to the non-templated - // IThreadInvoker interface BEFORE constructing the shared_ptr (rather than - // xmake_shared) so the shared_ptr control block is not templated - // on RetType/Args... -- one control-block type is then shared across every - // DelegateAsyncWait kind and signature instead of duplicated per signature. - // `rawClone` stays valid for the whole function (kept alive by `delegate`) - // and is used below to read back the clone's own result state. - ClassType* rawClone = this->Clone(); - if (!rawClone) - BAD_ALLOC(); - IThreadInvoker* invokerBase = rawClone; - std::shared_ptr delegate(invokerBase, std::default_delete(), dmq::stl_allocator()); - - bool success = detail::DispatchAsyncWait(delegate, m_state.GetThread(), m_state.GetPriority(), - m_state.GetTimeout(), std::forward(args)...); - if (success) { - // Invoke() (running as the clone, on the destination thread) wrote the - // target function's return value into the clone's own m_retVal. - retVal = std::move(rawClone->m_retVal); - } - return success; - } - - /// Move the value out of `v`, or return a default value if it holds none. - static RetType TakeRet(std::optional& v) noexcept { - if (v) return std::move(*v); -#if defined(DMQ_ASSERTS) - DMQ_ASSERT(); // no result stored (e.g. GetRetVal() before any successful call) -#endif - return RetType(); - } - - /// Record a call's result as this delegate's last result, for IsSuccess()/GetRetVal(). - void SetLastResult(bool success, const std::optional& retVal) { - const dmq::LockGuard lock(detail::AsyncWaitResultLock()); - m_state.SetSuccess(success); - m_retVal = retVal; - } - - /// Destination thread, message priority, timeout, and whether the last async call - /// succeeded. Not templated on Sig/TClass — see `detail::AsyncWaitDispatchState`. - detail::AsyncWaitDispatchState m_state; - - /// Return value, typed so a large return type needs no heap allocation (std::any - /// put anything over its small buffer on the global heap). On the per-call clone: - /// that call's result, written by Invoke() on the destination thread and read by - /// the caller after the message lock. On the caller's delegate: the last call's - /// result for GetRetVal(), guarded by detail::AsyncWaitResultLock(). - std::optional m_retVal; - - // -}; - -template -class DelegateFunctionAsyncWait; // Not defined - -/// @brief `DelegateFunctionAsyncWait<>` class asynchronously block invokes a std::function target function. -/// -/// See `DelegateFunction<>` base class for important usage limitations. -/// -/// @tparam RetType The return type of the bound delegate function. -/// @tparam Args The argument types of the bound delegate function. -template -class DelegateFunctionAsyncWait : public DelegateFunction, public IThreadInvoker { -public: - using FunctionType = std::function; - using ClassType = DelegateFunctionAsyncWait; - using BaseType = DelegateFunction; - - static_assert(!(std::disjunction_v...>), - "Non-const std::shared_ptr reference/pointer arguments are not allowed"); - - /// @brief Constructor to create a class instance. - /// @param[in] func The target `std::function` to store. - /// @param[in] thread The execution thread to invoke `func`. - /// @param[in] timeout The calling thread timeout for destination thread to - /// invoke the target function. - DelegateFunctionAsyncWait(FunctionType func, IThread& thread, Duration timeout = WAIT_INFINITE) : - BaseType(func) { - Bind(func, thread, timeout); - } - - /// @brief Copy constructor that creates a copy of the given instance. - /// @details This constructor initializes a new object as a copy of the - /// provided `rhs` (right-hand side) object. The `rhs` object is used to - /// set the state of the new instance. - /// @param[in] rhs The object to copy from. - DelegateFunctionAsyncWait(const ClassType& rhs) : - BaseType(rhs) { - Assign(rhs); - } - - /// @brief Move constructor that transfers ownership of resources. - /// @param[in] rhs The object to move from. - DelegateFunctionAsyncWait(ClassType&& rhs) noexcept : - BaseType(std::move(rhs)), m_state(rhs.m_state) { - rhs.Clear(); - } - - DelegateFunctionAsyncWait() = default; - - /// @brief Bind a `std::function` to the delegate. - /// @details This method associates a member function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] func The `std::function` to bind to the delegate. This function must match - /// the signature of the delegate. - /// @param[in] thread The execution thread to invoke `func`. - /// @param[in] timeout The calling thread timeout for destination thread to - /// invoke the target function. - void Bind(FunctionType func, IThread& thread, Duration timeout = WAIT_INFINITE) { - m_state.SetThread(&thread); - m_state.SetTimeout(timeout); - BaseType::Bind(func); - } - - // - - /// @brief Assigns the state of one object to another. - /// @details Copy the state from the `rhs` (right-hand side) object to the - /// current object. - /// @param[in] rhs The object whose state is to be copied. - void Assign(const ClassType& rhs) { - m_state = rhs.m_state; - m_retVal.reset(); - BaseType::Assign(rhs); - } - - /// @brief Creates a copy of the current object. - /// @details Clones the current instance of the class by creating a new object - /// and copying the state of the current object to it. - /// @return A pointer to a new `ClassType` instance or nullptr if allocation fails. - /// @post The caller is responsible for deleting the clone object and checking for - /// nullptr. - virtual ClassType* Clone() const override { - return new(std::nothrow) ClassType(*this); - } - - /// @brief Assignment operator that assigns the state of one object to another. - /// @param[in] rhs The object whose state is to be assigned to the current object. - /// @return A reference to the current object. - ClassType& operator=(const ClassType& rhs) { - if (&rhs != this) { - BaseType::operator=(rhs); - Assign(rhs); - } - return *this; - } - - /// @brief Move assignment operator that transfers ownership of resources. - /// @param[in] rhs The object to move from. - /// @return A reference to the current object. - ClassType& operator=(ClassType&& rhs) noexcept { - if (&rhs != this) { - BaseType::operator=(std::move(rhs)); - m_state = rhs.m_state; // Use the resource - m_retVal.reset(); - rhs.Clear(); - } - return *this; - } - - /// @brief Clear the target function. - virtual void operator=(std::nullptr_t) noexcept override { - return this->Clear(); - } - - /// @brief Compares two delegate objects for equality. - /// @param[in] rhs The `DelegateBase` object to compare with the current object. - /// @return `true` if the two delegate objects are equal, `false` otherwise. - virtual bool Equal(const DelegateBase& rhs) const override { - auto derivedRhs = dynamic_cast(&rhs); - return derivedRhs && - m_state.Equal(derivedRhs->m_state) && - BaseType::Equal(rhs); - } - - /// Compares two delegate objects for equality. - /// @return `true` if the objects are equal, `false` otherwise. - bool operator==(const ClassType& rhs) const noexcept { return Equal(rhs); } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - virtual bool operator==(std::nullptr_t) const noexcept override { - return this->Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - virtual bool operator!=(std::nullptr_t) const noexcept override { - return !this->Empty(); - } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - friend bool operator==(std::nullptr_t, const ClassType& rhs) noexcept { - return rhs.Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - friend bool operator!=(std::nullptr_t, const ClassType& rhs) noexcept { - return !rhs.Empty(); - } - - /// @brief Invoke delegate function asynchronously and block for function return value. - /// Called by the source thread. - /// @details Invoke delegate function asynchronously and wait for the return value. - /// This function is called by the source thread. Dispatches the delegate data into the - /// destination thread message queue. `Invoke()` must be called by the destination - /// thread to invoke the target function. Always safe to call. - /// - /// If the destination thread invokes the function within `m_timeout`, the return - /// value is obtained from the destination thread function call. If `m_timeout` expires - /// before the destination thread starts the call, the target function is not invoked - /// and a default return value is returned. If the call has already started when - /// `m_timeout` expires, the caller waits for it to finish and gets its return value. - /// Use `IsSuccess()` to check for success before using the return value. Alternatively, - /// use `AsyncInvoke()` and check the `std::optional` return value. - /// - /// The `DelegateAsyncWaitMsg` does not duplicate and copy the function arguments into heap - /// memory. The source thread waits on the destintation thread to complete, therefore argument - /// data is shared between the source and destination threads and simultaneous access is prevented - /// using a mutex. - /// @param[in] args The function arguments, if any. - /// @return The bound function return value, if any. Use `IsSuccess()` to determine if - /// the return value is valid before use. - virtual RetType operator()(Args... args) override { - // The result lives in locals, so concurrent callers sharing this instance - // (e.g. one Signal emitted from two threads) each get their own return value. - std::optional retVal; - bool success = DispatchWait(retVal, std::forward(args)...); - SetLastResult(success, retVal); - - if constexpr (std::is_void::value == false) { - return success ? TakeRet(retVal) : RetType(); - } - } - - /// @brief Invoke delegate function asynchronously and block for function return value. - /// Called by the source thread. Always safe to call, including concurrently. - /// @param[in] args The function arguments, if any. - /// @return The bound function return value stored withing `std::optional`. Use - /// `has_value()` to check if the the return value is valid. `value()` contains - /// the target function return value. - auto AsyncInvoke(Args... args) { - std::optional retVal; - bool success = DispatchWait(retVal, std::forward(args)...); - SetLastResult(success, retVal); - - if constexpr (std::is_void::value == true) { - return success ? std::optional(true) : std::optional(); - } else { - return success ? std::optional(TakeRet(retVal)) : std::optional(); - } - } - - /// @brief Invoke the delegate function on the destination thread. Called by the - /// destination thread. - /// @details Each source thread call to `operator()` generate a call to `Invoke()` - /// on the destination thread. A lock is used to protect source and destination thread shared - /// data. A semaphore is used to signal the source thread when the destination thread - /// completes the target function call. - /// - /// If source thread timeout expires and before the destination thread invokes the - /// target function, the target function is not called. - /// @param[in] msg The delegate message created and sent within `operator()(Args... args)`. - /// @return `true` if target function invoked or timeout expired; `false` if error. - virtual bool Invoke(std::shared_ptr msg) override { - static_assert(!(is_unique_ptr::value), "std::unique_ptr return value not allowed"); - - // Typecast the base pointer to back correct derived to instance - auto delegateMsg = std::dynamic_pointer_cast>(msg); - if (delegateMsg == nullptr) - return false; - - // Protect data shared between source and destination threads - const dmq::LockGuard lock(delegateMsg->GetLock()); - - // Is the source thread waiting for the target function invoke to complete? - if (delegateMsg->GetInvokerWaiting()) { - // Signals the source thread when this scope exits, including via an exception - // propagating out of the target function invoke below. Without this, a target - // function that throws would leave the source thread blocked until timeout. - struct SemaSignalGuard { - Semaphore& sema; - ~SemaSignalGuard() { sema.Signal(); } - } semaSignalGuard{ delegateMsg->GetSema() }; - - // Does target function have a void return value? - if constexpr (std::is_void::value == true) { - // Call the target with the message's stored arguments: a qualified, non-virtual - // call, so there is no copy of the argument tuple and no virtual hop back through - // operator(). Each argument is forwarded as declared: by-value arguments are moved - // out of the message (each message is invoked exactly once), references bind to - // the stored copies. - std::apply([this](auto&... args) { this->BaseType::operator()(std::forward(args)...); }, - delegateMsg->GetArgs()); - } else { - // As above, and keep the return value (in this clone's typed slot). - m_retVal.emplace(std::apply( - [this](auto&... args) -> RetType { return this->BaseType::operator()(std::forward(args)...); }, - delegateMsg->GetArgs())); - } - - // Only reached if the std::apply() call above did not throw - delegateMsg->SetInvokeSucceeded(true); - } - return true; - } - - /// Returns `true` if the last asynchronous call on this delegate succeeded. - /// @return `true` if the target asynchronous function call succeeded. `false` if - /// the timeout expired before the target function could be invoked. - /// @note If several threads call this delegate concurrently, this reports whichever - /// call finished last. Use `AsyncInvoke()`'s return value to get each call's own result. - bool IsSuccess() noexcept { return m_state.IsSuccess(); } - - /// Get the asynchronous function return value of the last call on this delegate. - /// @return The destination thread target function return value - /// @note Same caveat as `IsSuccess()` for concurrent callers. - RetType GetRetVal() noexcept { - if constexpr (std::is_void::value == false) { - std::optional copy; - { - const dmq::LockGuard lock(detail::AsyncWaitResultLock()); - copy = m_retVal; - } - return TakeRet(copy); - } - } - ///@brief Get the destination thread that the target function is invoked on. - // @return The target thread. - IThread* GetThread() noexcept { return m_state.GetThread(); } - - /// @brief Get the delegate message priority - /// @return Delegate message priority - Priority GetPriority() const noexcept { return m_state.GetPriority(); } - void SetPriority(Priority priority) noexcept { m_state.SetPriority(priority); } - -private: - /// Return value storage type (std::optional can't hold void). - using RetStorage = std::conditional_t::value, bool, std::decay_t>; - - /// Dispatch to the destination thread and wait (up to the timeout) for the call. - /// @param[out] retVal The target function's return value, set when this returns `true`. - /// @return `true` if the target function was invoked and completed. - bool DispatchWait(std::optional& retVal, Args&&... args) { - if (this->Empty()) - return false; - - // Create a clone instance of this delegate. Erase to the non-templated - // IThreadInvoker interface BEFORE constructing the shared_ptr (rather than - // xmake_shared) so the shared_ptr control block is not templated - // on RetType/Args... -- one control-block type is then shared across every - // DelegateAsyncWait kind and signature instead of duplicated per signature. - // `rawClone` stays valid for the whole function (kept alive by `delegate`) - // and is used below to read back the clone's own result state. - ClassType* rawClone = this->Clone(); - if (!rawClone) - BAD_ALLOC(); - IThreadInvoker* invokerBase = rawClone; - std::shared_ptr delegate(invokerBase, std::default_delete(), dmq::stl_allocator()); - - bool success = detail::DispatchAsyncWait(delegate, m_state.GetThread(), m_state.GetPriority(), - m_state.GetTimeout(), std::forward(args)...); - if (success) { - // Invoke() (running as the clone, on the destination thread) wrote the - // target function's return value into the clone's own m_retVal. - retVal = std::move(rawClone->m_retVal); - } - return success; - } - - /// Move the value out of `v`, or return a default value if it holds none. - static RetType TakeRet(std::optional& v) noexcept { - if (v) return std::move(*v); -#if defined(DMQ_ASSERTS) - DMQ_ASSERT(); // no result stored (e.g. GetRetVal() before any successful call) -#endif - return RetType(); - } - - /// Record a call's result as this delegate's last result, for IsSuccess()/GetRetVal(). - void SetLastResult(bool success, const std::optional& retVal) { - const dmq::LockGuard lock(detail::AsyncWaitResultLock()); - m_state.SetSuccess(success); - m_retVal = retVal; - } - - /// Destination thread, message priority, timeout, and whether the last async call - /// succeeded. Not templated on Sig/TClass — see `detail::AsyncWaitDispatchState`. - detail::AsyncWaitDispatchState m_state; - - /// Return value, typed so a large return type needs no heap allocation (std::any - /// put anything over its small buffer on the global heap). On the per-call clone: - /// that call's result, written by Invoke() on the destination thread and read by - /// the caller after the message lock. On the caller's delegate: the last call's - /// result for GetRetVal(), guarded by detail::AsyncWaitResultLock(). - std::optional m_retVal; - - // -}; - -/// @brief Creates an asynchronous delegate that binds to a free function with a wait and timeout. -/// @tparam RetType The return type of the free function. -/// @tparam Args The types of the function arguments. -/// @param[in] func A pointer to the free function to bind to the delegate. -/// @param[in] thread The `IThread` on which the function will be invoked asynchronously. -/// @param[in] timeout The duration to wait for the function to complete before returning. -/// @return A `DelegateFreeAsyncWait` object bound to the specified free function, thread, and timeout. -template -auto MakeDelegate(RetType(*func)(Args... args), IThread& thread, Duration timeout) { - return DelegateFreeAsyncWait(func, thread, timeout); -} - -/// @brief Creates an asynchronous delegate that binds to a non-const member function with a wait and timeout. -/// @tparam TClass The class type that contains the member function. -/// @tparam RetType The return type of the member function. -/// @tparam Args The types of the function arguments. -/// @param[in] object A pointer to the instance of `TClass` that will be used for the delegate. -/// @param[in] func A pointer to the non-const member function of `TClass` to bind to the delegate. -/// @param[in] thread The `IThread` on which the function will be invoked asynchronously. -/// @param[in] timeout The duration to wait for the function to complete before returning. -/// @return A `DelegateMemberAsyncWait` object bound to the specified non-const member function, thread, and timeout. -template -auto MakeDelegate(TClass* object, RetType(TClass::*func)(Args... args), IThread& thread, Duration timeout) { - return DelegateMemberAsyncWait(object, func, thread, timeout); -} - -/// @brief Creates an asynchronous delegate that binds to a const member function with a wait and timeout. -/// @tparam TClass The class type that contains the const member function. -/// @tparam RetType The return type of the member function. -/// @tparam Args The types of the function arguments. -/// @param[in] object A pointer to the instance of `TClass` that will be used for the delegate. -/// @param[in] func A pointer to the const member function of `TClass` to bind to the delegate. -/// @param[in] thread The `IThread` on which the function will be invoked asynchronously. -/// @param[in] timeout The duration to wait for the function to complete before returning. -/// @return A `DelegateMemberAsyncWait` object bound to the specified const member function, thread, and timeout. -template -auto MakeDelegate(TClass* object, RetType(TClass::*func)(Args... args) const, IThread& thread, Duration timeout) { - return DelegateMemberAsyncWait(object, func, thread, timeout); -} - -/// @brief Creates a delegate that binds to a const member function. -/// @tparam TClass The const class type that contains the const member function. -/// @tparam RetType The return type of the member function. -/// @tparam Args The types of the function arguments. -/// @param[in] object A pointer to the instance of `TClass` that will be used for the delegate. -/// @param[in] func A pointer to the non-const member function of `TClass` to bind to the delegate. -/// @param[in] thread The `IThread` on which the function will be invoked asynchronously. -/// @param[in] timeout The duration to wait for the function to complete before returning. -/// @return A `DelegateMemberAsyncWait` object bound to the specified non-const member function. -template -auto MakeDelegate(const TClass* object, RetType(TClass::* func)(Args... args) const, IThread& thread, Duration timeout) { - return DelegateMemberAsyncWait(object, func, thread, timeout); -} - -/// @brief Creates an asynchronous delegate that binds to a non-const member function using a shared pointer, with a wait and timeout. -/// @tparam TClass The class type that contains the member function. -/// @tparam RetVal The return type of the member function. -/// @tparam Args The types of the function arguments. -/// @param[in] object A shared pointer to the instance of `TClass` that will be used for the delegate. -/// @param[in] func A pointer to the non-const member function of `TClass` to bind to the delegate. -/// @param[in] thread The `IThread` on which the function will be invoked asynchronously. -/// @param[in] timeout The duration to wait for the function to complete before returning. -/// @return A `DelegateMemberAsyncWait` shared pointer bound to the specified non-const member function, thread, and timeout. -template -auto MakeDelegate(std::shared_ptr object, RetVal(TClass::* func)(Args... args), IThread& thread, Duration timeout) { - return DelegateMemberAsyncWaitSp(object, func, thread, timeout); -} - -/// @brief Creates an asynchronous delegate that binds to a const member function using a shared pointer, with a wait and timeout. -/// @tparam TClass The class type that contains the member function. -/// @tparam RetVal The return type of the member function. -/// @tparam Args The types of the function arguments. -/// @param[in] object A shared pointer to the instance of `TClass` that will be used for the delegate. -/// @param[in] func A pointer to the const member function of `TClass` to bind to the delegate. -/// @param[in] thread The `IThread` on which the function will be invoked asynchronously. -/// @param[in] timeout The duration to wait for the function to complete before returning. -/// @return A `DelegateMemberAsyncWait` shared pointer bound to the specified const member function, thread, and timeout. -template -auto MakeDelegate(std::shared_ptr object, RetVal(TClass::* func)(Args... args) const, IThread& thread, Duration timeout) { - return DelegateMemberAsyncWaitSp(object, func, thread, timeout); -} - -/// @brief Creates an asynchronous delegate that binds to a `std::function` with a wait and timeout. -/// @tparam RetType The return type of the `std::function`. -/// @tparam Args The types of the function arguments. -/// @param[in] func The `std::function` to bind to the delegate. -/// @param[in] thread The `IThread` on which the function will be invoked asynchronously. -/// @param[in] timeout The duration to wait for the function to complete before returning. -/// @return A `DelegateFunctionAsyncWait` object bound to the specified `std::function`, thread, and timeout. -template -auto MakeDelegate(std::function func, IThread& thread, Duration timeout) { - return DelegateFunctionAsyncWait(func, thread, timeout); -} - -/// @brief Creates an asynchronous delegate that binds to a raw lambda or functor with a wait and timeout. -/// @tparam F The lambda or functor type. -/// @param[in] func The lambda or functor to bind. -/// @param[in] thread The `IThread` on which the function will be invoked asynchronously. -/// @param[in] timeout The duration to wait for the function to complete before returning. -/// @return A `DelegateFunctionAsyncWait` object bound to the specified lambda or functor, thread, and timeout. -template ::value>> -auto MakeDelegate(F&& func, IThread& thread, Duration timeout) { - using Sig = typename trait::function_traits::operator())>::function_type; - return DelegateFunctionAsyncWait(std::forward(func), thread, timeout); -} - -} - -DMQ_OPTIMIZE_OFF - -#endif // DMQ_HAS_SEMAPHORE - -#endif diff --git a/DelegateMQ/delegate/DelegateMQConfig_Default.h b/DelegateMQ/delegate/DelegateMQConfig_Default.h deleted file mode 100644 index 2065094..0000000 --- a/DelegateMQ/delegate/DelegateMQConfig_Default.h +++ /dev/null @@ -1,194 +0,0 @@ -#ifndef _DELEGATEMQ_CONFIG_DEFAULT_H -#define _DELEGATEMQ_CONFIG_DEFAULT_H - -/// @file -/// @brief Default DelegateMQ library configuration. -/// -/// To override, define DMQ_USER_CONFIG as a path to your own config header: -/// -DDMQ_USER_CONFIG="path/to/DelegateMQConfig.h" -/// Your config only needs to define the values you want to change. -/// Unset values fall back to these defaults via DelegateMQConfig_Default.h. - -#ifndef DMQ_DEFAULT_DISPATCH_TIMEOUT - #define DMQ_DEFAULT_DISPATCH_TIMEOUT 2 // seconds -#endif - -#ifndef DMQ_THREAD_IDLE_INTERVAL - #define DMQ_THREAD_IDLE_INTERVAL 100 // milliseconds; default for Thread::SetIdleHandler() -#endif - -#ifndef DMQ_MAX_TIMER_EXPIRED - #define DMQ_MAX_TIMER_EXPIRED 16 -#endif - -#ifndef DMQ_SIGNAL_SBO_COUNT - #define DMQ_SIGNAL_SBO_COUNT 8 -#endif - -#ifndef DMQ_DEFAULT_QUEUE_SIZE - #define DMQ_DEFAULT_QUEUE_SIZE 20 -#endif - -// Stack size of each dmq::os::Thread on the RTOS ports, in each port's native unit. -#ifndef DMQ_FREERTOS_STACK_WORDS - #define DMQ_FREERTOS_STACK_WORDS 4096 // words; dynamic stacks (SetStackMem() overrides) -#endif -#ifndef DMQ_THREADX_STACK_BYTES - #define DMQ_THREADX_STACK_BYTES 2048 -#endif -#ifndef DMQ_ZEPHYR_STACK_BYTES - #define DMQ_ZEPHYR_STACK_BYTES 2048 -#endif -#ifndef DMQ_CMSIS_RTOS2_STACK_BYTES - #define DMQ_CMSIS_RTOS2_STACK_BYTES 2048 -#endif -#ifndef DMQ_NUTTX_STACK_BYTES - #define DMQ_NUTTX_STACK_BYTES 8192 -#endif - -// Default dmq::os::Thread priority on the RTOS ports whose default is a plain number -// (SetThreadPriority() overrides per thread). -#ifndef DMQ_THREADX_THREAD_PRIORITY - #define DMQ_THREADX_THREAD_PRIORITY 10 // 0 = highest -#endif -#ifndef DMQ_ZEPHYR_THREAD_PRIORITY - #define DMQ_ZEPHYR_THREAD_PRIORITY 5 // passed to K_PRIO_PREEMPT() -#endif -#ifndef DMQ_NUTTX_THREAD_PRIORITY - #define DMQ_NUTTX_THREAD_PRIORITY 100 // SCHED_FIFO -#endif - -// Fallback queue size (maxQueueSize == 0) for the desktop stdlib/Win32 Thread ports -// only. Unlike DMQ_DEFAULT_QUEUE_SIZE (sized for real RTOS RAM constraints), these -// ports back their queue with a plain std::deque, so maxQueueSize == 0 otherwise -// means genuinely unbounded growth if the destination thread is dead/stuck. This -// is a high-water-mark safety net, not a throughput limiter -- large enough to -// never interfere with normal desktop bursts, but bounded so a truly dead consumer -// hits a clear FullPolicy::FAULT instead of growing the heap without limit. -#ifndef DMQ_THREAD_DESKTOP_QUEUE_SIZE - #define DMQ_THREAD_DESKTOP_QUEUE_SIZE 1000 -#endif - -#ifndef DMQ_MAX_WATCHDOG_THREADS - #define DMQ_MAX_WATCHDOG_THREADS 16 -#endif - -// A watched thread's queue wait (and Qt's heartbeat timer) is its watchdog timeout -// divided by this, so an idle thread refreshes its heartbeat this many times per -// timeout. At least 2. -#ifndef DMQ_WATCHDOG_HEARTBEAT_DIVISOR - #define DMQ_WATCHDOG_HEARTBEAT_DIVISOR 4 -#endif - -// Max threads registered for dmq::ThisThread::GetCurrent() at once on RTOS ports -// (one per running dmq::os::Thread or custom IThread worker). Exceeding it faults. -#ifndef DMQ_MAX_CURRENT_THREADS - #define DMQ_MAX_CURRENT_THREADS 16 -#endif - -#ifndef DMQ_SEQ_HISTORY_SIZE - #define DMQ_SEQ_HISTORY_SIZE 8 -#endif - -// How long a received sequence number counts toward duplicate detection. A real -// duplicate (a retry after a lost ACK) arrives within the sender's retry window; -// older entries are ignored so a restarted peer's reused numbers aren't dropped. -#ifndef DMQ_SEQ_HISTORY_EXPIRY_MS - #define DMQ_SEQ_HISTORY_EXPIRY_MS ((DMQ_RETRY_MONITOR_MAX_RETRIES + 1) * DMQ_TRANSPORT_MONITOR_TIMEOUT_SEC * 1000) -#endif - -// This node's ID, sent in every DmqHeader (1-255). 0 = unset: receivers then -// track duplicates by remote ID alone, which is only correct with one sender -// per topic. Can be changed at run time with DmqHeader::SetLocalNodeId(). -#ifndef DMQ_NODE_ID - #define DMQ_NODE_ID 0 -#endif - -#ifndef DMQ_MAX_PARTICIPANTS - #define DMQ_MAX_PARTICIPANTS 8 -#endif - -#ifndef DMQ_TRANSPORT_MONITOR_MAX_PENDING - #define DMQ_TRANSPORT_MONITOR_MAX_PENDING 100 -#endif - -// Embedded UDP transports (lwIP, netconn, Zephyr, NetX): datagram buffer size -// (header + payload), and receive timeouts. A PUB socket polls briefly for ACKs; -// a SUB socket waits longer, returning RECEIVE_NO_DATA so its thread can check -// for exit. -#ifndef DMQ_UDP_BUFFER_SIZE - #define DMQ_UDP_BUFFER_SIZE 1500 -#endif -#ifndef DMQ_UDP_PUB_RECV_TIMEOUT_MS - #define DMQ_UDP_PUB_RECV_TIMEOUT_MS 50 -#endif -#ifndef DMQ_UDP_SUB_RECV_TIMEOUT_MS - #define DMQ_UDP_SUB_RECV_TIMEOUT_MS 2000 -#endif - -// STM32 UART transport: RX ring buffer bytes, max payload per frame, blocking -// transmit timeout per frame, and the most it waits for the rest of a frame -// once its marker has arrived. -#ifndef DMQ_UART_RX_RING_SIZE - #define DMQ_UART_RX_RING_SIZE 1024 -#endif -#ifndef DMQ_UART_MAX_PAYLOAD - #define DMQ_UART_MAX_PAYLOAD 512 -#endif -#ifndef DMQ_UART_TX_TIMEOUT_MS - #define DMQ_UART_TX_TIMEOUT_MS 500 -#endif -#ifndef DMQ_UART_FRAME_TIMEOUT_MS - #define DMQ_UART_FRAME_TIMEOUT_MS 100 -#endif - -// Maximum number of distinct fixed-block allocator buckets (heap-blocks mode only). -// Each unique power-of-two allocation size gets one bucket. Most applications use -// 8-12 distinct sizes; raise this only if xallocator's ASSERT fires at runtime. -#ifndef DMQ_XALLOCATOR_MAX_ALLOCATORS - #define DMQ_XALLOCATOR_MAX_ALLOCATORS 15 -#endif - -// Default max remote peers per NetworkNode instance (fixed allocation). -// Override per-instantiation via NetworkNode's MaxPeers template parameter. -#ifndef DMQ_NETWORK_NODE_MAX_PEERS - #define DMQ_NETWORK_NODE_MAX_PEERS 4 -#endif - -// Default max in- or out-topics per NetworkNode instance (fixed allocation). -// Override per-instantiation via NetworkNode's MaxTopics template parameter. -#ifndef DMQ_NETWORK_NODE_MAX_TOPICS - #define DMQ_NETWORK_NODE_MAX_TOPICS 16 -#endif - -// Max messages drained per NetworkNode::ReceiverThread() tick (applies to both -// the incoming-message drain and the per-peer ACK drain). -#ifndef DMQ_NETWORK_NODE_MAX_WORK - #define DMQ_NETWORK_NODE_MAX_WORK 20 -#endif - -// Default number of retries before RetryMonitor gives up on an unacknowledged message. -#ifndef DMQ_RETRY_MONITOR_MAX_RETRIES - #define DMQ_RETRY_MONITOR_MAX_RETRIES 3 -#endif - -// Default per-message ACK timeout (seconds) for TransportMonitor. -#ifndef DMQ_TRANSPORT_MONITOR_TIMEOUT_SEC - #define DMQ_TRANSPORT_MONITOR_TIMEOUT_SEC 2 -#endif - -// serialize (msg_serialize.h, DMQ_SERIALIZE_SERIALIZE) limits. Longer strings or -// larger containers fail with STRING_TOO_LONG / CONTAINER_TOO_MANY, on write and -// on read. Both must be <= 65535 (16-bit length field on the wire). -#ifndef DMQ_SERIALIZE_MAX_STRING_SIZE - #define DMQ_SERIALIZE_MAX_STRING_SIZE 1024 -#endif -#ifndef DMQ_SERIALIZE_MAX_CONTAINER_SIZE - #define DMQ_SERIALIZE_MAX_CONTAINER_SIZE 64 -#endif -// Max depth of serialize::I objects nested inside each other (NESTING_TOO_DEEP beyond). -#ifndef DMQ_SERIALIZE_MAX_NESTING - #define DMQ_SERIALIZE_MAX_NESTING 5 -#endif - -#endif // _DELEGATEMQ_CONFIG_DEFAULT_H diff --git a/DelegateMQ/delegate/DelegateMQConfig_Template.h b/DelegateMQ/delegate/DelegateMQConfig_Template.h deleted file mode 100644 index 02c7c1c..0000000 --- a/DelegateMQ/delegate/DelegateMQConfig_Template.h +++ /dev/null @@ -1,151 +0,0 @@ -#ifndef _DELEGATEMQ_CONFIG_H -#define _DELEGATEMQ_CONFIG_H - -/// @file -/// @brief User configuration for the DelegateMQ library. -/// -/// Copy this file to your project as DelegateMQConfig.h. It is picked up -/// automatically when its directory is on the include path, or point the -/// compiler at it explicitly: -DDMQ_USER_CONFIG="DelegateMQConfig.h" -/// -/// Only define the values you want to change; any omitted values -/// fall back to the defaults in DelegateMQConfig_Default.h. - -// --- Port and option selection (builds without CMake) --- -// Without CMake, choose ports and options here instead of with -D flags. -// Anything left undefined is auto-selected (see delegate/DelegateSelect.h): -// stdlib threads, the built-in serializer and UDP on Windows/Linux, nothing -// on bare metal. With CMake, set DMQ_THREAD etc. in CMake instead and leave -// these commented out; defining a second port here is a compile error. -// -// #define DMQ_THREAD_FREERTOS // or DMQ_THREAD_STDLIB, _WIN32, _POSIX, _THREADX, -// // _ZEPHYR, _CMSIS_RTOS2, _NUTTX, _QT, _NONE -// #define DMQ_SERIALIZE_NONE // or DMQ_SERIALIZE_SERIALIZE, _MSGPACK, ... -// #define DMQ_TRANSPORT_NONE // or DMQ_TRANSPORT_STM32_UART, _ARM_LWIP_UDP, ... -// #define DMQ_ALLOCATOR // fixed-block allocator instead of the heap -// #define DMQ_ASSERTS // FaultHandler() instead of exceptions -// #define DMQ_DATABUS // DataBus on an RTOS (desktop default is on; -// #define DMQ_DATABUS_OFF // DMQ_DATABUS_OFF turns it off there) -// #define DMQ_CUSTOM_FAULT_HANDLER // application defines FaultHandler()/WatchdogHandler() -// // itself; port/fault/Fault.cpp compiles to nothing - -/// Timeout (seconds) used by the TIMEOUT queue-full policy on all threads. -#define DMQ_DEFAULT_DISPATCH_TIMEOUT 2 - -/// Default quiet time (milliseconds) before a Thread's idle handler runs, and -/// between calls while the queue stays empty. See Thread::SetIdleHandler(). -#define DMQ_THREAD_IDLE_INTERVAL 100 - -/// Max timers processed in one tick without heap allocation. -#define DMQ_MAX_TIMER_EXPIRED 16 - -/// Signal Small-Buffer Optimization count. -/// Signals with <= this many subscribers are invoked without heap allocation. -#define DMQ_SIGNAL_SBO_COUNT 8 - -/// Default internal message queue depth (maxQueueSize == 0) for the RTOS -/// dmq::os::Thread ports (FreeRTOS, Zephyr, ThreadX, CMSIS-RTOS2, NuttX), where -/// the backing queue primitive requires a fixed capacity at creation. -#define DMQ_DEFAULT_QUEUE_SIZE 20 - -/// Stack size of each dmq::os::Thread on the RTOS ports, in each port's native -/// unit. FreeRTOS counts words and applies to dynamically allocated stacks -/// (FreeRTOSThread::SetStackMem() supplies a static stack instead); the others -/// count bytes. -#define DMQ_FREERTOS_STACK_WORDS 4096 -#define DMQ_THREADX_STACK_BYTES 2048 -#define DMQ_ZEPHYR_STACK_BYTES 2048 -#define DMQ_CMSIS_RTOS2_STACK_BYTES 2048 -#define DMQ_NUTTX_STACK_BYTES 8192 - -/// Default dmq::os::Thread priority on the RTOS ports whose default is a plain -/// number. SetThreadPriority() overrides it per thread. ThreadX: 0 is highest. -/// Zephyr: passed to K_PRIO_PREEMPT(). NuttX: SCHED_FIFO priority. (FreeRTOS and -/// CMSIS-RTOS2 derive their defaults from configMAX_PRIORITIES / osPriorityNormal.) -#define DMQ_THREADX_THREAD_PRIORITY 10 -#define DMQ_ZEPHYR_THREAD_PRIORITY 5 -#define DMQ_NUTTX_THREAD_PRIORITY 100 - -/// Fallback queue size (maxQueueSize == 0) for the desktop stdlib/Win32 Thread -/// ports only. A high-water-mark safety net (not a throughput limiter) against -/// unbounded growth if the destination thread is dead/stuck -- large enough to -/// never interfere with normal desktop bursts. -#define DMQ_THREAD_DESKTOP_QUEUE_SIZE 1000 - -/// Max number of threads that can be registered with the watchdog. -#define DMQ_MAX_WATCHDOG_THREADS 16 - -/// A watched thread's queue wait (and Qt's heartbeat timer) is its watchdog -/// timeout divided by this: an idle thread refreshes its heartbeat this many -/// times per timeout. Higher is more margin, more wakeups. At least 2. -#define DMQ_WATCHDOG_HEARTBEAT_DIVISOR 4 - -/// Max threads registered for dmq::ThisThread::GetCurrent() at once on RTOS ports -/// (one per running dmq::os::Thread or custom IThread worker). Exceeding it faults. -/// Unused on desktop ports, which use thread_local storage. -#define DMQ_MAX_CURRENT_THREADS 16 - -/// Duplicate-detection ring buffer depth per remote Participant. -/// Larger values catch more out-of-order duplicates; reduce on RAM-constrained targets. -#define DMQ_SEQ_HISTORY_SIZE 8 - -/// How long (ms) a received sequence number counts toward duplicate detection. -/// Should cover the sender's whole retry window: (retries + 1) x ACK timeout. -/// Older entries are ignored so a restarted peer's reused numbers aren't dropped. -#define DMQ_SEQ_HISTORY_EXPIRY_MS ((DMQ_RETRY_MONITOR_MAX_RETRIES + 1) * DMQ_TRANSPORT_MONITOR_TIMEOUT_SEC * 1000) - -/// This node's ID, sent in every message header (1-255). Give every node on a -/// network a unique ID when more than one node publishes the same topic. -/// 0 = unset (duplicates tracked by remote ID alone). Run-time override: -/// dmq::transport::DmqHeader::SetLocalNodeId(). -#define DMQ_NODE_ID 0 - -/// Max number of remote Participants the DataBus can hold without heap allocation. -#define DMQ_MAX_PARTICIPANTS 8 - -/// Default max remote peers per NetworkNode instance (fixed allocation). -/// Override per-instantiation via NetworkNode's MaxPeers template parameter. -#define DMQ_NETWORK_NODE_MAX_PEERS 4 - -/// Default max in- or out-topics per NetworkNode instance (fixed allocation). -/// Override per-instantiation via NetworkNode's MaxTopics template parameter. -#define DMQ_NETWORK_NODE_MAX_TOPICS 16 - -/// Max messages drained per NetworkNode::ReceiverThread() tick (incoming-message -/// drain and per-peer ACK drain). -#define DMQ_NETWORK_NODE_MAX_WORK 20 - -/// Default number of retries before RetryMonitor gives up on an unacknowledged message. -#define DMQ_RETRY_MONITOR_MAX_RETRIES 3 - -/// Default per-message ACK timeout (seconds) for TransportMonitor. -#define DMQ_TRANSPORT_MONITOR_TIMEOUT_SEC 2 - -/// Embedded UDP transports (lwIP, netconn, Zephyr, NetX): datagram buffer size -/// (header + payload, keep within the link MTU), the PUB socket's ACK-poll -/// receive timeout, and the SUB socket's receive timeout (how often its thread -/// can check for exit). -#define DMQ_UDP_BUFFER_SIZE 1500 -#define DMQ_UDP_PUB_RECV_TIMEOUT_MS 50 -#define DMQ_UDP_SUB_RECV_TIMEOUT_MS 2000 - -/// STM32 UART transport: RX ring buffer bytes (absorbs bursts between reads), -/// max payload per frame (both ends must agree), blocking transmit timeout per -/// frame (raise for low baud rates or large payloads), and the most Receive() -/// waits for the rest of a frame once its marker has arrived. -#define DMQ_UART_RX_RING_SIZE 1024 -#define DMQ_UART_MAX_PAYLOAD 512 -#define DMQ_UART_TX_TIMEOUT_MS 500 -#define DMQ_UART_FRAME_TIMEOUT_MS 100 - -/// serialize (msg_serialize.h, DMQ_SERIALIZE_SERIALIZE): max string length and max -/// container element count, on write and on read. Both must be <= 65535 (16-bit -/// length field on the wire). Raising them also raises how much a received message -/// can make the receiver allocate. -#define DMQ_SERIALIZE_MAX_STRING_SIZE 1024 -#define DMQ_SERIALIZE_MAX_CONTAINER_SIZE 64 - -/// serialize: max depth of serialize::I objects nested inside each other. -#define DMQ_SERIALIZE_MAX_NESTING 5 - -#endif // _DELEGATEMQ_CONFIG_H diff --git a/DelegateMQ/delegate/DelegateMsg.h b/DelegateMQ/delegate/DelegateMsg.h deleted file mode 100644 index 95713c5..0000000 --- a/DelegateMQ/delegate/DelegateMsg.h +++ /dev/null @@ -1,83 +0,0 @@ -#ifndef _DELEGATE_MSG_H -#define _DELEGATE_MSG_H - -/// @file -/// @brief Delegate inter-thread message base class. - -#include "IInvoker.h" -#include "DelegateOpt.h" -#include "make_tuple_heap.h" -#include -#include - -namespace dmq { - -// Async delegate message priority -// -// Contract every dmq::os::Thread port's queue implementation must uphold: -// a HIGH message is always dispatched ahead of any NORMAL message already -// waiting, but HIGH does NOT mean "jump to the very front" -- among multiple -// HIGH messages (or multiple NORMAL messages), FIFO order relative to each -// other must be preserved. I.e. per-priority-lane FIFO, not a LIFO stack. -// -// A single queue with a "send to front" primitive (FreeRTOS xQueueSendToFront, -// ThreadX tx_queue_front_send) gets this wrong: a second HIGH message sent to -// the front lands ahead of the first HIGH message, turning HIGH ordering into -// a stack. The correct shape -- used by every port -- is two lanes (one per -// priority) with new messages always pushed to the BACK of their lane, and -// the consumer draining the HIGH lane before the NORMAL lane: -// - StdlibThread / Win32Thread: two std::deque, one shared mutex+condition_variable. -// - ZephyrDelegateQueue: two k_msgq, drained via k_poll on both. -// - FreeRTOSDelegateQueue / ThreadXDelegateQueue / CmsisRtos2DelegateQueue: two native queues, woken by -// one shared counting semaphore "doorbell" (the RTOS-native stand-in for -// the stdlib condition_variable, since none of these queue APIs exposes one). -// CMSIS-RTOS2's osMessageQueuePut msg_prio is not used: implementations may -// ignore it (Zephyr's does). -enum class Priority -{ - NORMAL, - HIGH -}; - -/// @brief Base class for all delegate inter-thread messages -class DelegateMsg -{ -public: - /// Constructor - /// @param[in] invoker - the invoker instance the delegate is registered with. - DelegateMsg(std::shared_ptr invoker, Priority priority) : - m_invoker(invoker), m_priority(priority) - { - } - - virtual ~DelegateMsg() = default; - - /// Get the delegate invoker instance the delegate is registered with. - /// @return The invoker instance. - std::shared_ptr GetInvoker() const { return m_invoker; } - - /// Get the delegate message priority - /// @return Delegate message priority - Priority GetPriority() const { return m_priority; } - - /// @brief Called by a thread that discards this message without invoking it - /// (e.g. dmq::ExitPolicy::DISCARD). Releases a sender blocked waiting on the - /// invoke, which then sees the call as failed instead of waiting out its timeout. - /// No-op for messages nobody waits on. - virtual void Cancel() {} - -private: - /// The IThreadInvoker instance used to invoke the target function - /// on the destination thread of control - std::shared_ptr m_invoker; - - /// The delegate message priority - Priority m_priority = Priority::NORMAL; - - // Use fixed-block memory allocator if DMQ_ALLOCATOR set - XALLOCATOR -}; - -} - -#endif diff --git a/DelegateMQ/delegate/DelegateOpt.h b/DelegateMQ/delegate/DelegateOpt.h deleted file mode 100644 index b27475b..0000000 --- a/DelegateMQ/delegate/DelegateOpt.h +++ /dev/null @@ -1,672 +0,0 @@ -#ifndef _DELEGATE_OPT_H -#define _DELEGATE_OPT_H - -/// @file -/// @brief Delegate library options header file. - -// Option selection (user config, port auto-detection, derived DMQ_* macros) -// comes first so everything below sees the final options. -#include "DelegateSelect.h" - -#if defined(_WIN32) || defined(_WIN64) - #ifndef WIN32_LEAN_AND_MEAN - #define WIN32_LEAN_AND_MEAN - #endif - #ifndef NOMINMAX - #define NOMINMAX - #endif - - // If networking is active, include winsock2.h here to prevent macro - // redefinitions when windows.h is included later (e.g. by FreeRTOS or stdlib). - #if defined(DMQ_DATABUS) || defined(DMQ_TRANSPORT_ZEROMQ) || \ - defined(DMQ_TRANSPORT_WIN32_UDP) || defined(DMQ_TRANSPORT_WIN32_TCP) || \ - defined(DMQ_TRANSPORT_WIN32_PIPE) || defined(DMQ_TRANSPORT_NNG) || \ - defined(DMQ_TRANSPORT_MQTT) - #include - #include - #endif -#endif - -// Host BSD/Winsock socket headers for extras/util/NetworkConnect.h's desktop -// convenience helpers (RAII WSAStartup/WSACleanup, GetLocalAddress()). -// -// _WIN32/__linux__/__APPLE__/__unix__ reflect the compiler/host doing the -// building, not the actual target. A genuine embedded cross-compile (e.g. -// arm-none-eabi-gcc for stm32-freertos) never defines these host-platform -// macros in the first place, so this guard is only ever live for a target -// that is ALSO built with a host compiler -- i.e. a simulator/native sample. -// DMQ_THREAD_HAS_NATIVE_NETWORK_STACK (above) captures exactly which -// embedded RTOS ports bundle a colliding native network stack there and -// must be excluded; see its own comment for why FreeRTOS is deliberately -// not one of them. -#if !defined(DMQ_THREAD_HAS_NATIVE_NETWORK_STACK) - #define DMQ_NETWORK_CONNECT_DESKTOP_HOST_HEADERS - #ifdef _WIN32 - #include - #include - #pragma comment(lib, "ws2_32.lib") - #elif defined(__linux__) || defined(__APPLE__) || defined(__unix__) - #include - #include - #include - #include - #include - #include - #include - #include - #include - #endif -#endif - -#include -#if defined(DMQ_HAS_THREADING) - #include - #if !defined(__cpp_lib_scoped_lock) - // No std::scoped_lock on this toolchain; see dmq::ScopedLock below. - #include "port/os/common/PortableScopedLock.h" - #endif -#endif - -// RTTI Detection Check -#if !defined(__cpp_rtti) && !defined(__GXX_RTTI) && !defined(_CPPRTTI) - #error "RTTI compiler option is disabled but required by the DelegateMQ library." -#endif - -// Some OS port headers below (e.g. ThreadXMutex.h, ThreadXConditionVariable.h) use -// DMQ_ASSERT_TRUE in constructors. Include Fault.h here, ahead of those port headers, -// so the macro is defined before first use. Fault.h is include-guarded, so the -// later #include "extras/util/Fault.h" below is a harmless no-op. -#include "extras/util/Fault.h" - -#if defined(DMQ_THREAD_STDLIB) || defined(DMQ_THREAD_WIN32) || defined(DMQ_THREAD_QT) || defined(DMQ_THREAD_POSIX) - // Windows / Linux / macOS / Qt (Standard Library) / POSIX (raw pthreads, - // but Mutex/ConditionVariable/Clock/ThisThread still reuse std:: here -- - // see port/os/posix/PosixThread.h, the only file this port adds) - #include - #include - #include "port/os/stdlib/StdlibThisThread.h" -#elif defined(DMQ_THREAD_FREERTOS) - #include "port/os/freertos/FreeRTOSClock.h" - #include "port/os/freertos/FreeRTOSMutex.h" - #include "port/os/freertos/FreeRTOSConditionVariable.h" - #include "port/os/freertos/FreeRTOSCriticalSection.h" - #include "port/os/freertos/FreeRTOSThisThread.h" -#elif defined(DMQ_THREAD_THREADX) - #include "port/os/threadx/ThreadXClock.h" - #include "port/os/threadx/ThreadXMutex.h" - #include "port/os/threadx/ThreadXConditionVariable.h" - #include "port/os/threadx/ThreadXCriticalSection.h" - #include "port/os/threadx/ThreadXThisThread.h" -#elif defined(DMQ_THREAD_ZEPHYR) - #include "port/os/zephyr/ZephyrClock.h" - #include "port/os/zephyr/ZephyrMutex.h" - #include "port/os/zephyr/ZephyrCriticalSection.h" - #include "port/os/zephyr/ZephyrSemaphore.h" - #include "port/os/zephyr/ZephyrThisThread.h" -#elif defined(DMQ_THREAD_CMSIS_RTOS2) - #include "port/os/cmsis-rtos2/CmsisRtos2Clock.h" - #include "port/os/cmsis-rtos2/CmsisRtos2Mutex.h" - #include "port/os/cmsis-rtos2/CmsisRtos2CriticalSection.h" - #include "port/os/cmsis-rtos2/CmsisRtos2Semaphore.h" - #include "port/os/cmsis-rtos2/CmsisRtos2ThisThread.h" -#elif defined(DMQ_THREAD_NUTTX) - #include "port/os/nuttx/NuttXClock.h" - #include "port/os/nuttx/NuttXMutex.h" - #include "port/os/nuttx/NuttXCriticalSection.h" - #include "port/os/nuttx/NuttXSemaphore.h" - #include "port/os/nuttx/NuttXThisThread.h" -#elif defined(DMQ_THREAD_NONE) - #include "port/os/bare-metal/BareMetalClock.h" - #include "port/os/bare-metal/BareMetalCriticalSection.h" - #include "port/os/bare-metal/BareMetalThisThread.h" -#else - #include "port/os/bare-metal/BareMetalClock.h" - #include "port/os/bare-metal/BareMetalCriticalSection.h" - #include "port/os/bare-metal/BareMetalThisThread.h" -#endif - -namespace dmq -{ - // --- PORTABLE LOCK GUARD --- - // Does not require . Works with any BasicLockable type (lock/unlock). - template - class PortableLockGuard { - T& m_mutex; - public: - explicit PortableLockGuard(T& m) noexcept : m_mutex(m) { m_mutex.lock(); } - ~PortableLockGuard() noexcept { m_mutex.unlock(); } - PortableLockGuard(const PortableLockGuard&) = delete; - PortableLockGuard& operator=(const PortableLockGuard&) = delete; - }; - - // --- PORTABLE SCOPED LOCK --- - // std::scoped_lock on threaded ports (desktop + RTOS); all RTOS mutex types - // satisfy BasicLockable (lock/unlock), so it works with them directly. Some - // bare-metal standard libraries lack std::scoped_lock without thread support - // (e.g. Arm GNU Toolchain 14); those get dmq::os::PortableScopedLock - // (port/os/common/PortableScopedLock.h). No-op for DMQ_THREAD_NONE and for - // any bare-metal build with no thread model. -#if defined(DMQ_HAS_THREADING) && defined(__cpp_lib_scoped_lock) - template - using ScopedLock = std::scoped_lock; -#elif defined(DMQ_HAS_THREADING) - template - using ScopedLock = dmq::os::PortableScopedLock; -#else - // No-op: DMQ_THREAD_NONE or no thread model defined (bare-metal, single-threaded) - template - class ScopedLock { - public: - explicit ScopedLock(M&...) noexcept {} - ~ScopedLock() noexcept = default; - ScopedLock(const ScopedLock&) = delete; - ScopedLock& operator=(const ScopedLock&) = delete; - }; -#endif - - // @TODO: Change aliases to switch clock type globally if necessary - - // --- CLOCK SELECTION --- -#if defined(DMQ_THREAD_STDLIB) || defined(DMQ_THREAD_WIN32) || defined(DMQ_THREAD_QT) || defined(DMQ_THREAD_POSIX) - // Windows / Linux / macOS / Qt / POSIX - using Clock = std::chrono::steady_clock; - -#elif defined(DMQ_THREAD_FREERTOS) - // Use the custom FreeRTOS wrapper - using Clock = dmq::os::FreeRTOSClock; - -#elif defined(DMQ_THREAD_THREADX) - // Use the custom ThreadX wrapper - using Clock = dmq::os::ThreadXClock; - -#elif defined(DMQ_THREAD_ZEPHYR) - // Use the custom Zephyr wrapper - using Clock = dmq::os::ZephyrClock; - -#elif defined(DMQ_THREAD_CMSIS_RTOS2) - using Clock = dmq::os::CmsisRtos2Clock; - -#elif defined(DMQ_THREAD_NUTTX) - // Use the custom NuttX wrapper - using Clock = dmq::os::NuttXClock; - -#else - // Assuming implemented the 'g_ticks' variable - using Clock = dmq::os::BareMetalClock; -#endif - - // --- GENERIC TYPES --- - // Automatically adapt to the underlying Clock's traits - using Duration = typename Clock::duration; - using TimePoint = typename Clock::time_point; - - // --- THIS_THREAD (sleep_for / yield / GetCurrent) SELECTION --- - // Portable equivalents of std::this_thread::sleep_for()/yield() for the - // calling thread, plus GetCurrent(): the dmq::IThread whose worker is the - // calling thread, or nullptr (registered by dmq::CurrentThreadScope in - // IThread.h). Exists so library internals that need to delay or yield - // (e.g. RetryMonitor backoff) aren't forced to pull in a full - // dmq::os::Thread -- which also drags in the message queue, watchdog, and - // stats machinery -- just to sleep. Each dmq::os::Thread::Sleep() forwards - // here too, so every port's native delay call is implemented exactly once. - // Each port implements it in port/os//ThisThread.h. - // - // A class (not a "this_thread" namespace) deliberately: sample/app code - // throughout this project does `using namespace dmq; ... using namespace - // std;` together, and a same-named nested namespace would make unqualified - // this_thread::sleep_for() calls in that code ambiguous against - // std::this_thread. -#if defined(DMQ_THREAD_STDLIB) || defined(DMQ_THREAD_WIN32) || defined(DMQ_THREAD_QT) || defined(DMQ_THREAD_POSIX) - using ThisThread = dmq::os::StdlibThisThread; -#elif defined(DMQ_THREAD_FREERTOS) - using ThisThread = dmq::os::FreeRTOSThisThread; -#elif defined(DMQ_THREAD_THREADX) - using ThisThread = dmq::os::ThreadXThisThread; -#elif defined(DMQ_THREAD_ZEPHYR) - using ThisThread = dmq::os::ZephyrThisThread; -#elif defined(DMQ_THREAD_CMSIS_RTOS2) - using ThisThread = dmq::os::CmsisRtos2ThisThread; -#elif defined(DMQ_THREAD_NUTTX) - using ThisThread = dmq::os::NuttXThisThread; -#else - // Bare metal (DMQ_THREAD_NONE, or no thread model defined): sleep_for() - // busy-waits against BareMetalClock; yield() is a no-op. - using ThisThread = dmq::os::BareMetalThisThread; -#endif - - /// @brief Policy applied when a dmq::os::Thread port's message queue is full. - /// @details Always enforced -- a constructor's maxQueueSize == 0 is a sentinel meaning - /// "use this port's default capacity" (dmq::DEFAULT_QUEUE_SIZE for the RTOS ports, - /// dmq::THREAD_DESKTOP_QUEUE_SIZE for stdlib/Win32), not "disable the cap." Every port's - /// effective queue capacity is therefore always > 0 at runtime. - /// - DROP: DispatchDelegate() silently discards the message and returns immediately. - /// - FAULT: DispatchDelegate() triggers a system fault if the queue is full. - /// - TIMEOUT: DispatchDelegate() waits up to dispatchTimeout, then logs and drops. - /// - /// Use DROP for high-rate best-effort topics (sensor telemetry, display updates) where - /// a stale sample is preferable to stalling the publisher. Use TIMEOUT for critical topics - /// (commands, state transitions) where every message should be delivered if possible. - /// FAULT is the default. Every dmq::os::Thread port aliases this single definition as - /// dmq::os::FullPolicy so existing port-qualified references keep working. - enum class FullPolicy { DROP, FAULT, TIMEOUT }; - - /// @brief What a dmq::os::Thread does with messages still queued when ExitThread() is called. - /// - DRAIN: Invoke every message queued before ExitThread(), then exit (default). - /// - DISCARD: Invoke only the message already running, then exit. Queued messages are - /// discarded without being invoked; a sender blocked on one (an async-wait - /// delegate) is released and sees the call fail (DelegateMsg::Cancel()). - /// - /// Use DISCARD for fast shutdown when pending work is disposable (telemetry, UI refresh). - /// A thread that exits itself (ExitThread() called from its own message handler) always - /// discards, since the thread's owner may already be destroyed. - enum class ExitPolicy { DRAIN, DISCARD }; - - /// @brief Default timeout for the TIMEOUT queue-full policy across all Thread ports. - /// Override via DMQ_DEFAULT_DISPATCH_TIMEOUT in DelegateMQConfig.h. - inline constexpr std::chrono::seconds DEFAULT_DISPATCH_TIMEOUT{DMQ_DEFAULT_DISPATCH_TIMEOUT}; - - /// @brief Default quiet time before a Thread's idle handler runs, and between - /// calls while its queue stays empty. See Thread::SetIdleHandler(). - /// Override via DMQ_THREAD_IDLE_INTERVAL in DelegateMQConfig.h. - inline constexpr std::chrono::milliseconds THREAD_IDLE_INTERVAL{DMQ_THREAD_IDLE_INTERVAL}; - static_assert(DMQ_THREAD_IDLE_INTERVAL > 0, "DMQ_THREAD_IDLE_INTERVAL must be greater than zero"); - - // --- RESOURCE LIMITS & SBO CONFIGURATION --- - - /// @brief Max timers processed in one tick without heap allocation. - /// Override via DMQ_MAX_TIMER_EXPIRED in delegatemqconfig.h. - inline constexpr size_t MAX_TIMER_EXPIRED = DMQ_MAX_TIMER_EXPIRED; - - /// @brief Signal Small-Buffer Optimization (SBO) count. - /// Signals with <= this many subscribers are invoked heap-free. - /// Override via DMQ_SIGNAL_SBO_COUNT in delegatemqconfig.h. - inline constexpr size_t SIGNAL_SBO_COUNT = DMQ_SIGNAL_SBO_COUNT; - - /// @brief Default internal queue size (maxQueueSize == 0) for the RTOS - /// dmq::os::Thread ports, where the backing queue primitive requires a - /// fixed capacity at creation. - /// Override via DMQ_DEFAULT_QUEUE_SIZE in delegatemqconfig.h. - inline constexpr size_t DEFAULT_QUEUE_SIZE = DMQ_DEFAULT_QUEUE_SIZE; - - /// @brief Stack size of each dmq::os::Thread on the RTOS ports, in each - /// port's native unit (FreeRTOS: words, for dynamically allocated stacks; - /// the others: bytes). - /// Override via DMQ_FREERTOS_STACK_WORDS, DMQ_THREADX_STACK_BYTES, - /// DMQ_ZEPHYR_STACK_BYTES, DMQ_CMSIS_RTOS2_STACK_BYTES and - /// DMQ_NUTTX_STACK_BYTES in delegatemqconfig.h. - inline constexpr uint32_t FREERTOS_STACK_WORDS = DMQ_FREERTOS_STACK_WORDS; - inline constexpr size_t THREADX_STACK_BYTES = DMQ_THREADX_STACK_BYTES; - inline constexpr size_t ZEPHYR_STACK_BYTES = DMQ_ZEPHYR_STACK_BYTES; - inline constexpr size_t CMSIS_RTOS2_STACK_BYTES = DMQ_CMSIS_RTOS2_STACK_BYTES; - inline constexpr size_t NUTTX_STACK_BYTES = DMQ_NUTTX_STACK_BYTES; - - /// @brief Default dmq::os::Thread priority on the ThreadX, Zephyr (passed to - /// K_PRIO_PREEMPT()) and NuttX (SCHED_FIFO) ports. SetThreadPriority() - /// overrides it per thread. - /// Override via DMQ_THREADX_THREAD_PRIORITY, DMQ_ZEPHYR_THREAD_PRIORITY and - /// DMQ_NUTTX_THREAD_PRIORITY in delegatemqconfig.h. - inline constexpr int THREADX_THREAD_PRIORITY = DMQ_THREADX_THREAD_PRIORITY; - inline constexpr int ZEPHYR_THREAD_PRIORITY = DMQ_ZEPHYR_THREAD_PRIORITY; - inline constexpr int NUTTX_THREAD_PRIORITY = DMQ_NUTTX_THREAD_PRIORITY; - - /// @brief Fallback queue size (maxQueueSize == 0) for the desktop - /// stdlib/Win32 Thread ports only, which back their queue with a plain - /// std::deque and would otherwise grow without bound if the destination - /// thread is dead/stuck. A high-water-mark safety net, not a throughput - /// limiter -- large enough to never interfere with normal desktop bursts. - /// Override via DMQ_THREAD_DESKTOP_QUEUE_SIZE in delegatemqconfig.h. - inline constexpr size_t THREAD_DESKTOP_QUEUE_SIZE = DMQ_THREAD_DESKTOP_QUEUE_SIZE; - - /// @brief Max number of threads that can be monitored by the watchdog. - /// Override via DMQ_MAX_WATCHDOG_THREADS in delegatemqconfig.h. - inline constexpr size_t MAX_WATCHDOG_THREADS = DMQ_MAX_WATCHDOG_THREADS; - - /// @brief A watched thread's queue wait (and Qt's heartbeat timer) is its - /// watchdog timeout divided by this. - /// Override via DMQ_WATCHDOG_HEARTBEAT_DIVISOR in delegatemqconfig.h. - inline constexpr int WATCHDOG_HEARTBEAT_DIVISOR = DMQ_WATCHDOG_HEARTBEAT_DIVISOR; - static_assert(WATCHDOG_HEARTBEAT_DIVISOR >= 2, "DMQ_WATCHDOG_HEARTBEAT_DIVISOR must be at least 2"); - - /// @brief Max threads registered for ThisThread::GetCurrent() at once on RTOS - /// ports (see port/os/common/CurrentThreadStorage.h). Exceeding it faults. - /// Override via DMQ_MAX_CURRENT_THREADS in delegatemqconfig.h. - inline constexpr size_t MAX_CURRENT_THREADS = DMQ_MAX_CURRENT_THREADS; - - /// @brief Max number of remote Participants the DataBus can hold without heap allocation. - /// Override via DMQ_MAX_PARTICIPANTS in delegatemqconfig.h. - inline constexpr size_t MAX_PARTICIPANTS = DMQ_MAX_PARTICIPANTS; - - /// @brief serialize (msg_serialize.h) limits: max string length, max container - /// element count and max nesting depth of serialize::I objects. - /// Override via DMQ_SERIALIZE_MAX_STRING_SIZE, DMQ_SERIALIZE_MAX_CONTAINER_SIZE - /// and DMQ_SERIALIZE_MAX_NESTING in delegatemqconfig.h. - inline constexpr uint16_t SERIALIZE_MAX_STRING_SIZE = DMQ_SERIALIZE_MAX_STRING_SIZE; - inline constexpr uint16_t SERIALIZE_MAX_CONTAINER_SIZE = DMQ_SERIALIZE_MAX_CONTAINER_SIZE; - inline constexpr size_t SERIALIZE_MAX_NESTING = DMQ_SERIALIZE_MAX_NESTING; - static_assert(DMQ_SERIALIZE_MAX_STRING_SIZE <= 65535 && DMQ_SERIALIZE_MAX_CONTAINER_SIZE <= 65535, - "serialize length fields are 16 bits"); - static_assert(DMQ_SERIALIZE_MAX_NESTING >= 1, "DMQ_SERIALIZE_MAX_NESTING must be at least 1"); - - /// @brief Default max remote peers per NetworkNode instance (fixed allocation). - /// Override via DMQ_NETWORK_NODE_MAX_PEERS in delegatemqconfig.h, or per-instantiation - /// via NetworkNode's MaxPeers template parameter. - inline constexpr size_t NETWORK_NODE_MAX_PEERS = DMQ_NETWORK_NODE_MAX_PEERS; - - /// @brief Default max in- or out-topics per NetworkNode instance (fixed allocation). - /// Override via DMQ_NETWORK_NODE_MAX_TOPICS in delegatemqconfig.h, or per-instantiation - /// via NetworkNode's MaxTopics template parameter. - inline constexpr size_t NETWORK_NODE_MAX_TOPICS = DMQ_NETWORK_NODE_MAX_TOPICS; - - /// @brief Max messages drained per NetworkNode::ReceiverThread() tick. - /// Override via DMQ_NETWORK_NODE_MAX_WORK in delegatemqconfig.h. - inline constexpr int NETWORK_NODE_MAX_WORK = DMQ_NETWORK_NODE_MAX_WORK; - - /// @brief Default number of retries before RetryMonitor gives up on an unacknowledged message. - /// Override via DMQ_RETRY_MONITOR_MAX_RETRIES in delegatemqconfig.h, or per-call via - /// RetryMonitor's maxRetries constructor/Init() parameter. - inline constexpr int RETRY_MONITOR_MAX_RETRIES = DMQ_RETRY_MONITOR_MAX_RETRIES; - - /// @brief Default per-message ACK timeout for TransportMonitor. - /// Override via DMQ_TRANSPORT_MONITOR_TIMEOUT_SEC in delegatemqconfig.h, or per-instance - /// via TransportMonitor's timeout constructor parameter. - inline constexpr Duration TRANSPORT_MONITOR_TIMEOUT = std::chrono::seconds(DMQ_TRANSPORT_MONITOR_TIMEOUT_SEC); - - /// @brief How long a received sequence number counts toward duplicate detection. - /// Override via DMQ_SEQ_HISTORY_EXPIRY_MS in delegatemqconfig.h. - inline constexpr Duration SEQ_HISTORY_EXPIRY = std::chrono::milliseconds(DMQ_SEQ_HISTORY_EXPIRY_MS); - - /// @brief Default node ID sent in every DmqHeader (0 = unset). - /// Override via DMQ_NODE_ID in delegatemqconfig.h. - static_assert(DMQ_NODE_ID >= 0 && DMQ_NODE_ID <= 255, "DMQ_NODE_ID must be 0-255"); - inline constexpr uint8_t NODE_ID = DMQ_NODE_ID; - - /// @brief Max number of pending messages the TransportMonitor can track. - /// Override via DMQ_TRANSPORT_MONITOR_MAX_PENDING in delegatemqconfig.h. - inline constexpr size_t MAX_TRANSPORT_MONITOR_PENDING = DMQ_TRANSPORT_MONITOR_MAX_PENDING; - - /// @brief Embedded UDP transports: datagram buffer size and receive timeouts. - /// Override via DMQ_UDP_BUFFER_SIZE / DMQ_UDP_PUB_RECV_TIMEOUT_MS / - /// DMQ_UDP_SUB_RECV_TIMEOUT_MS in delegatemqconfig.h. - inline constexpr size_t UDP_BUFFER_SIZE = DMQ_UDP_BUFFER_SIZE; - inline constexpr std::chrono::milliseconds UDP_PUB_RECV_TIMEOUT{ DMQ_UDP_PUB_RECV_TIMEOUT_MS }; - inline constexpr std::chrono::milliseconds UDP_SUB_RECV_TIMEOUT{ DMQ_UDP_SUB_RECV_TIMEOUT_MS }; - - /// @brief STM32 UART transport sizes and timeouts. - /// Override via DMQ_UART_RX_RING_SIZE / DMQ_UART_MAX_PAYLOAD / - /// DMQ_UART_TX_TIMEOUT_MS / DMQ_UART_FRAME_TIMEOUT_MS in delegatemqconfig.h. - inline constexpr size_t UART_RX_RING_SIZE = DMQ_UART_RX_RING_SIZE; - inline constexpr size_t UART_MAX_PAYLOAD = DMQ_UART_MAX_PAYLOAD; - inline constexpr std::chrono::milliseconds UART_TX_TIMEOUT{ DMQ_UART_TX_TIMEOUT_MS }; - inline constexpr std::chrono::milliseconds UART_FRAME_TIMEOUT{ DMQ_UART_FRAME_TIMEOUT_MS }; - - // --- MUTEX / LOCK SELECTION --- -#if defined(DMQ_THREAD_STDLIB) || defined(DMQ_THREAD_WIN32) || defined(DMQ_THREAD_QT) || defined(DMQ_THREAD_POSIX) - // Windows / Linux / macOS / Qt / POSIX - using Mutex = std::mutex; - using RecursiveMutex = std::recursive_mutex; - // No ISR concept reachable from userspace on desktop OSes, and - // Timer::ProcessTimers() is always driven from an ordinary thread here - // in practice -- CriticalSection is just RecursiveMutex. See - // ThreadXCriticalSection.h for what a "real" ISR-safe implementation - // looks like on a port where it matters. - using CriticalSection = RecursiveMutex; - using ConditionVariable = std::condition_variable; - template using LockGuard = std::lock_guard; - template using UniqueLock = std::unique_lock; - #define DMQ_HAS_CV - #define DMQ_HAS_SEMAPHORE // generic dmq::Semaphore (delegate/Semaphore.h) needs a real ConditionVariable - -#elif defined(DMQ_THREAD_FREERTOS) - // Use the custom FreeRTOS wrapper - using Mutex = dmq::os::FreeRTOSMutex; - using RecursiveMutex = dmq::os::FreeRTOSRecursiveMutex; - // ISR-safe on real ARM Cortex-M FreeRTOS ports (auto-detects context via - // xPortIsInsideInterrupt() and selects taskENTER_CRITICAL[_FROM_ISR] - // accordingly); on the desktop simulator ports (POSIX/Win32) it is - // task-context-only, since there is no real hardware interrupt to - // detect there. See FreeRTOSCriticalSection.h for the detection details - // and the __arm__/__ARM_ARCH scoping assumption. - using CriticalSection = dmq::os::FreeRTOSCriticalSection; - using ConditionVariable = dmq::os::FreeRTOSConditionVariable; - template using LockGuard = PortableLockGuard; - template using UniqueLock = std::unique_lock; - #define DMQ_HAS_CV - #define DMQ_HAS_SEMAPHORE // generic dmq::Semaphore (delegate/Semaphore.h) needs a real ConditionVariable - -#elif defined(DMQ_THREAD_THREADX) - // Use the custom ThreadX wrapper - using Mutex = dmq::os::ThreadXMutex; - using RecursiveMutex = dmq::os::ThreadXRecursiveMutex; - // Genuinely ISR-safe (interrupt masking, not a TX_MUTEX) -- see - // ThreadXCriticalSection.h for why a real OS mutex can never be made - // to work here, and for the narrow-use-only warnings that apply to it. - using CriticalSection = dmq::os::ThreadXCriticalSection; - using ConditionVariable = dmq::os::ThreadXConditionVariable; - template using LockGuard = PortableLockGuard; - template using UniqueLock = std::unique_lock; - #define DMQ_HAS_CV - #define DMQ_HAS_SEMAPHORE // generic dmq::Semaphore (delegate/Semaphore.h) needs a real ConditionVariable - -#elif defined(DMQ_THREAD_ZEPHYR) - // Use the custom Zephyr wrapper - using Mutex = dmq::os::ZephyrMutex; - using RecursiveMutex = dmq::os::ZephyrRecursiveMutex; - // ISR-safe (irq_lock()/irq_unlock(key), not a k_mutex) -- see - // ZephyrCriticalSection.h. - using CriticalSection = dmq::os::ZephyrCriticalSection; - // No dmq::ConditionVariable port for Zephyr (no DMQ_HAS_CV), but - // dmq::Semaphore is available via Zephyr's own native k_sem instead of - // the generic condvar+mutex implementation -- see ZephyrSemaphore.h and - // delegate/Semaphore.h. This is what makes DelegateAsyncWait available - // here. - using Semaphore = dmq::os::ZephyrSemaphore; - #define DMQ_HAS_SEMAPHORE - template using LockGuard = PortableLockGuard; - -#elif defined(DMQ_THREAD_CMSIS_RTOS2) - using Mutex = dmq::os::CmsisRtos2Mutex; - using RecursiveMutex = dmq::os::CmsisRtos2RecursiveMutex; - // ISR-safe (__disable_irq()/__enable_irq() via CMSIS-Core, bypassing - // osMutex entirely) -- see CmsisRtos2CriticalSection.h. UNVERIFIED: no - // CMSIS-RTOS2 SDK or Cortex-M hardware/QEMU target is available in this - // development environment to build and run it; review before relying - // on it in production. - using CriticalSection = dmq::os::CmsisRtos2CriticalSection; - // No dmq::ConditionVariable port for CMSIS-RTOS2 (no DMQ_HAS_CV, and no - // native condvar primitive to build one from), but dmq::Semaphore is - // available via osSemaphore directly instead -- see - // CmsisRtos2Semaphore.h and delegate/Semaphore.h. This is what makes - // DelegateAsyncWait available here. - using Semaphore = dmq::os::CmsisRtos2Semaphore; - #define DMQ_HAS_SEMAPHORE - template using LockGuard = PortableLockGuard; - -#elif defined(DMQ_THREAD_NUTTX) - // Use the custom NuttX wrapper (NuttX implements real POSIX - // pthread_mutex_t, unlike the bespoke kernel-object wrappers the other - // RTOS ports need). - using Mutex = dmq::os::NuttXMutex; - using RecursiveMutex = dmq::os::NuttXRecursiveMutex; - // ISR-safe (up_irq_save()/up_irq_restore(), NuttX's own architecture- - // portable interrupt-masking primitive, not a pthread_mutex_t) -- see - // NuttXCriticalSection.h, including its FLAT-vs-PROTECTED/KERNEL-build - // caveat. - using CriticalSection = dmq::os::NuttXCriticalSection; - // No dmq::ConditionVariable port for NuttX (no DMQ_HAS_CV) -- not - // because NuttX lacks pthread_cond_t (it has a real one), but because - // dmq::Semaphore is available via NuttX's own native sem_t instead of - // the generic condvar+mutex implementation -- see NuttXSemaphore.h and - // delegate/Semaphore.h. This is what makes DelegateAsyncWait available - // here. - using Semaphore = dmq::os::NuttXSemaphore; - #define DMQ_HAS_SEMAPHORE - template using LockGuard = PortableLockGuard; - -#else - // Bare metal has no threads, so no locking is required. - // NullMutex satisfies BasicLockable; PortableLockGuard compiles to nothing meaningful. - struct NullMutex { - void lock() {} - void unlock() {} - }; - using Mutex = NullMutex; - using RecursiveMutex = NullMutex; - // Unlike Mutex/RecursiveMutex above, NullMutex would NOT be correct here: - // bare metal still has real hardware ISRs that can preempt the main - // loop, even with no RTOS/threads. dmq::os::BareMetalCriticalSection - // does real interrupt masking (save/disable/restore PRIMASK), the same - // technique BareMetalClock.h already uses. - using CriticalSection = dmq::os::BareMetalCriticalSection; - template using LockGuard = PortableLockGuard; - // No DMQ_HAS_SEMAPHORE — no RTOS means no native semaphore primitive to - // build one from either; Semaphore and DelegateAsyncWait are unavailable - // on bare metal. -#endif -} - -// Detect if exceptions are disabled at the compiler level -#if !defined(__cpp_exceptions) - #ifndef DMQ_ASSERTS - #define DMQ_ASSERTS // Force asserts if exceptions are off - #endif -#endif - -// @TODO: Select the desired software fault handling (see Port.cmake). -#ifdef DMQ_ASSERTS - #include "extras/util/Fault.h" - // Use assert error handling. Change assert to a different error - // handler as required by the target application. - #define BAD_ALLOC() DMQ_ASSERT() -#else - #include "extras/util/Fault.h" - #include - // Use exception error handling - #define BAD_ALLOC() throw std::bad_alloc() -#endif - -// @TODO: Select the desired heap allocation (see Port.cmake). -// If DMQ_ASSERTS defined above, consider defining DMQ_ALLOCATOR to prevent -// std::list usage within delegate library from throwing a std::bad_alloc -// exception. The std_allocator calls assert if out of memory. -// See master CMakeLists.txt for info on enabling the fixed-block allocator. -#ifdef DMQ_ALLOCATOR - // Use stl_allocator fixed-block allocator for dynamic storage allocation - #include "extras/allocator/xstring.h" - #include "extras/allocator/xlist.h" - #include "extras/allocator/xmap.h" - #include "extras/allocator/xset.h" - #include "extras/allocator/xqueue.h" - #include "extras/allocator/xsstream.h" - #include "extras/allocator/stl_allocator.h" - #include "extras/allocator/xnew.h" - #include "extras/allocator/xmake_shared.h" -#else - #include - #include - #include - #include - #include - #include - #include - #include - #include - - // Not using xallocator; define as nothing - #undef XALLOCATOR - #define XALLOCATOR - - namespace dmq { - // Use default std::allocator for dynamic storage allocation - template - using stl_allocator = std::allocator; - - // An alias, like xmap/xset here and xlist under DMQ_ALLOCATOR, so code - // overloaded on std::list (e.g. msg_serialize.h) accepts it in both builds. - template > - using xlist = std::list; - - // stl_allocator is std::allocator here, so these are the standard types - typedef std::ostringstream xostringstream; - typedef std::stringstream xstringstream; - - typedef std::string xstring; - - // Fallback xmake_shared — uses std::make_shared when fixed-block allocator is disabled - template - inline std::shared_ptr xmake_shared(Args&&... args) - { - return std::make_shared(std::forward(args)...); - } - - // Fallback xnew/xdelete — use standard new/delete when fixed-block allocator is disabled - template - inline T* xnew(Args&&... args) { - return new(std::nothrow) T(std::forward(args)...); - } - - template - inline void xdelete(T* p) { - delete p; - } - - // Fallback xmap/xmultimap — use std::map when fixed-block allocator is disabled - template >> - using xmap = std::map, Alloc>; - - template >> - using xmultimap = std::multimap, Alloc>; - - // Fallback xset/xmultiset — use std::set when fixed-block allocator is disabled - template , typename Alloc = stl_allocator> - using xset = std::set; - - template , typename Alloc = stl_allocator> - using xmultiset = std::multiset; - - // Fallback xqueue — use std::queue when fixed-block allocator is disabled - template >> - using xqueue = std::queue; - } -#endif - -// @TODO: Select the desired logging (see Port.cmake). -#ifdef DMQ_LOG - #include - #define LOG_INFO(...) spdlog::info(__VA_ARGS__) - #define LOG_DEBUG(...) spdlog::debug(__VA_ARGS__) - #define LOG_ERROR(...) spdlog::error(__VA_ARGS__) -#else - // No-op macros when logging disabled - #define LOG_INFO(...) do {} while(0) - #define LOG_DEBUG(...) do {} while(0) - #define LOG_ERROR(...) do {} while(0) -#endif - -// @TODO: Select the desired template optimization level. -// Enable DMQ_FORCE_OPTIMIZE_DEBUG in your build system (e.g. CMake) to force -// the compiler to aggressively inline and optimize DelegateMQ templates even -// during unoptimized Debug builds. This significantly reduces code bloat and -// call stack depth for variadic template unpacking without losing the ability -// to step-debug your application code. -// -// NOTE: This feature relies on GCC/Clang-specific pragmas. MSVC's #pragma optimize -// cannot elevate optimizations above the command-line (/Od) baseline and is mostly -// deprecated for x64 targets. Thus, this macro is a silent no-op on MSVC Windows builds. -// For GCC/Clang, this uses -Os (optimize for size) to maximize flash savings. -#ifdef DMQ_FORCE_OPTIMIZE_DEBUG - #if defined(__GNUC__) || defined(__clang__) - #define DMQ_OPTIMIZE_ON \ - _Pragma("GCC push_options") \ - _Pragma("GCC optimize (\"Os\")") - #define DMQ_OPTIMIZE_OFF \ - _Pragma("GCC pop_options") - #else - #define DMQ_OPTIMIZE_ON - #define DMQ_OPTIMIZE_OFF - #endif -#else - #define DMQ_OPTIMIZE_ON - #define DMQ_OPTIMIZE_OFF -#endif - -#endif // _DELEGATE_OPT_H diff --git a/DelegateMQ/delegate/DelegateRemote.h b/DelegateMQ/delegate/DelegateRemote.h deleted file mode 100644 index b892ba7..0000000 --- a/DelegateMQ/delegate/DelegateRemote.h +++ /dev/null @@ -1,1688 +0,0 @@ -#ifndef _DELEGATE_REMOTE_H -#define _DELEGATE_REMOTE_H - -// DelegateRemote.h -// @see https://github.com/DelegateMQ/DelegateMQ -// David Lafreniere, Aug 2025. - -/// @file -/// @brief Delegate "`Remote`" series of classes used to invoke a function remotely -/// (i.e. different CPU, different process, etc...). -/// -/// @details The classes are not thread safe. Invoking a function remotely requires serializing -/// all target function arguments and sending the argument data to the remote destination. All -/// argument data is serialized into a stream. The receiver calls `Invoke()` with the received -/// serialized stream arguments. -/// -/// An `ISerializer` and `IDispatcher` implementations are required to serialize and dispatch a -/// remote delegate. These interface implementations, relied upon by the remote delegate, might not -/// be thread safe. Therefore, ensure each remote delegate instance is called from a single thread -/// of control. -/// -/// `RetType operator()(Args... args)` - called by the sender to initiate the remote function call. -/// Use `SetErrorHandler()` to catch invoke errors. Clone() may throw `std::bad_alloc` unless -/// `DMQ_ASSERTS`. All other delegate class functions do not throw exceptions. -/// -/// `void Invoke(std::istream& is)` - called by the receiver to invoke the target function. -/// -/// Limitations: -/// -/// * The target function return value is not valid after invoke since the delegate does -/// not wait for the target function to be called. -/// -/// * Cannot use a `void*` as a target function argument. -/// -/// * Cannot use rvalue reference (T&&) as a target function argument. -/// -/// * Cannot insert `DelegateRemoteAsync` into an ordered container. e.g. `std::list` ok, -/// `std::set` not ok. -/// -/// * `std::function` compares the function signature type, not the underlying object instance. -/// See `DelegateFunction<>` class for more info. -/// -/// Code within `` and `` is updated using src_dup.py. Manually update -/// the code within the `DelegateFreeRemote` `common_code` tags, then run the script to -/// propagate to the remaining delegate classes to simplify code maintenance. -/// -/// `python src_dup.py DelegateRemote.h` - -#include "Delegate.h" -#include "UnicastDelegate.h" -#include "ISerializer.h" -#include "IDispatcher.h" -#include "IInvoker.h" -#include -#include "DelegateOpt.h" -#include -#include - -DMQ_OPTIMIZE_ON - -namespace dmq { - -enum class DelegateError { - SUCCESS = 0, - ERR_STREAM_NOT_GOOD = 1, - ERR_NO_SERIALIZER = 2, - ERR_SERIALIZE = 3, - ERR_DESERIALIZE = 4, - ERR_DESERIALIZE_EXCEPTION = 5, - ERR_NO_DISPATCHER = 6, - ERR_DISPATCH = 7, - ERR_TYPE_MISMATCH = 8, - ERR_TRANSPORT_RECEIVE = 9, // Transport-level receive failure (bad frame, socket error) - ERR_CAPACITY_EXCEEDED = 10 // A fixed-size capacity limit was reached (e.g. MAX_PARTICIPANTS) -}; - -typedef int DelegateErrorAux; - -// Get the type of the Nth position within a template parameter pack -template using ArgTypeOf = -typename std::tuple_element>::type; - -// Get the value of the Nth position within a template parameter pack -template -decltype(auto) ArgValueOf(Args&&... ts) { - return std::get(std::forward_as_tuple(ts...)); -} - -template -class RemoteArg -{ -public: - using NonConstArg = std::remove_const_t; - NonConstArg& Get() { return m_arg; } -private: - NonConstArg m_arg{}; -}; - -template -class RemoteArg -{ -public: - using NonConstArg = std::remove_const_t; - - // Initialize the member pointer to point to the internal storage - RemoteArg() : m_ptr(&m_arg) {} - - // Custom copy/move semantics to ensure m_ptr always points to the *local* m_arg - RemoteArg(const RemoteArg& other) : m_arg(other.m_arg), m_ptr(&m_arg) {} - RemoteArg& operator=(const RemoteArg& other) { - if (this != &other) { - m_arg = other.m_arg; - m_ptr = &m_arg; - } - return *this; - } - - RemoteArg(RemoteArg&& other) noexcept : m_arg(std::move(other.m_arg)), m_ptr(&m_arg) {} - RemoteArg& operator=(RemoteArg&& other) noexcept { - if (this != &other) { - m_arg = std::move(other.m_arg); - m_ptr = &m_arg; - } - return *this; - } - - // Return a REFERENCE to the pointer (L-value), satisfying ISerializer::Read - Arg*& Get() { return m_ptr; } - -private: - NonConstArg m_arg{}; // The actual object storage - Arg* m_ptr; // The persistent pointer variable -}; - -#if 0 // Arg** not supported on remote delegates -template -class RemoteArg -{ -public: - RemoteArg() : m_pArg(&m_arg), m_ppArg(&m_pArg) {} - - // Return reference to the pointer-to-pointer - Arg**& Get() { return m_ppArg; } - -private: - Arg m_arg; - Arg* m_pArg; - Arg** m_ppArg; -}; -#endif - -template -class RemoteArg -{ -public: - using NonConstArg = std::remove_const_t; - NonConstArg& Get() { return m_arg; } -private: - NonConstArg m_arg{}; -}; - -namespace detail { - -/// @brief Fully non-template holder for a `DelegateXRemote<...>` instance's dispatch -/// state — remote id, dispatcher, output stream, last error, last dispatched sequence -/// number, and error-handler delegate. None of this depends on the bound function's -/// signature or target class (the error handler's own signature is fixed, independent -/// of the owning delegate's), so every `DelegateFreeRemote`/`DelegateMemberRemote`/ -/// `DelegateFunctionRemote` instantiation — for every signature and target class in the -/// program — composes this one definition instead of each generating its own copy. -/// @note `m_serializer` deliberately stays outside this class, on each owning delegate: -/// `ISerializer*` is the one piece of remote-dispatch state that -/// genuinely varies by signature. -/// @note `m_error` and `m_lastSeqNum` are per-instance, transient run-time observations -/// (the last error *this* object raised; the last sequence number *this* object's most -/// recent send was assigned) — never copied, assigned, or moved between instances, -/// only ever reset to their defaults on a fresh object. The special members below -/// deliberately leave them alone, mirroring the pre-refactor Assign()/copy-ctor/ -/// move-ctor/move-assign, none of which touched them either. -class RemoteDispatchState { -public: - RemoteDispatchState() = default; - - RemoteDispatchState(const RemoteDispatchState& rhs) - : m_id(rhs.m_id), m_errorHandler(rhs.m_errorHandler), - m_dispatcher(rhs.m_dispatcher), m_stream(rhs.m_stream), - m_sendMutex(rhs.m_sendMutex) { - } - - RemoteDispatchState(RemoteDispatchState&& rhs) noexcept - : m_id(rhs.m_id), m_errorHandler(std::move(rhs.m_errorHandler)), - m_dispatcher(rhs.m_dispatcher), m_stream(rhs.m_stream), - m_sendMutex(rhs.m_sendMutex) { - rhs.m_dispatcher = nullptr; - rhs.m_stream = nullptr; - rhs.m_sendMutex = nullptr; - } - - RemoteDispatchState& operator=(const RemoteDispatchState& rhs) { - if (this != &rhs) { - m_id = rhs.m_id; - m_errorHandler = rhs.m_errorHandler; - m_dispatcher = rhs.m_dispatcher; - m_stream = rhs.m_stream; - m_sendMutex = rhs.m_sendMutex; - } - return *this; - } - - RemoteDispatchState& operator=(RemoteDispatchState&& rhs) noexcept { - if (this != &rhs) { - m_id = rhs.m_id; - m_errorHandler = std::move(rhs.m_errorHandler); - m_dispatcher = rhs.m_dispatcher; - m_stream = rhs.m_stream; - m_sendMutex = rhs.m_sendMutex; - rhs.m_dispatcher = nullptr; - rhs.m_stream = nullptr; - rhs.m_sendMutex = nullptr; - } - return *this; - } - - DelegateRemoteId GetRemoteId() const noexcept { return m_id; } - void SetRemoteId(DelegateRemoteId id) noexcept { m_id = id; } - - IDispatcher* GetDispatcher() const noexcept { return m_dispatcher; } - void SetDispatcher(IDispatcher* dispatcher) noexcept { m_dispatcher = dispatcher; } - - dmq::xostringstream* GetStream() const noexcept { return m_stream; } - void SetStream(dmq::xostringstream* stream) noexcept { m_stream = stream; } - - dmq::Mutex* GetSendMutex() const noexcept { return m_sendMutex; } - void SetSendMutex(dmq::Mutex* mutex) noexcept { m_sendMutex = mutex; } - - uint16_t GetLastSeqNum() const noexcept { return m_lastSeqNum; } - - void SetErrorHandler(const Delegate& errorHandler) { - m_errorHandler = errorHandler; // Copy - } - void SetErrorHandler(Delegate&& errorHandler) { - m_errorHandler = std::move(errorHandler); // Moving the temporary - } - void ClearErrorHandler() { - m_errorHandler.Clear(); - } - - /// @brief Get the last error code. - /// @return The last error detected. - /// @post Error is reset to SUCCESS after call. - DelegateError GetError() noexcept { - DelegateError retVal = m_error; - m_error = DelegateError::SUCCESS; - return retVal; - } - - /// Raise an error and callback the registered error handler. - /// @param[in] error Error code. - /// @param[in] auxCode Optional auxiliary code. - /// @throws std::runtime_error If no error handler is registered. - void RaiseError(DelegateError error, DelegateErrorAux auxCode = 0) { - m_error = error; - if (m_errorHandler) { - m_errorHandler(m_id, error, auxCode); - } - else { -#if !defined(__cpp_exceptions) || defined(DMQ_ASSERTS) - // No throw -#else - throw std::runtime_error("Delegate remote error " + std::to_string(static_cast(error)) + " id " + std::to_string(m_id)); -#endif - } - } - - /// Raise success and callback the registered error handler. - void RaiseSuccess() { - if (m_errorHandler) - m_errorHandler(m_id, dmq::DelegateError::SUCCESS, 0); - } - - /// @brief Check the stream, dispatch it to the remote, and report success/error - /// through the error handler. - /// @details Everything past the argument serialization step is identical - /// regardless of the delegate's signature or target class, so it lives here once - /// instead of being duplicated in every `DelegateXRemote<...>::operator()`. - /// @param[in] writeFailed `true` if the caller's `ISerializer::Write()` call threw - /// (already reported through `RaiseError(ERR_SERIALIZE)` by the caller). - void SendSerialized(bool writeFailed) { - if (writeFailed) - return; - - if (!m_stream || !m_stream->good()) { - RaiseError(DelegateError::ERR_STREAM_NOT_GOOD); - return; - } - - if (!m_dispatcher) { - RaiseError(DelegateError::ERR_NO_DISPATCHER); - return; - } - - // Dispatch delegate invocation to the remote destination -#if !defined(__cpp_exceptions) || defined(DMQ_ASSERTS) - int error = m_dispatcher->Dispatch(*m_stream, m_id, &m_lastSeqNum); - if (error) - RaiseError(DelegateError::ERR_DISPATCH, error); - else - RaiseSuccess(); -#else - try { - int error = m_dispatcher->Dispatch(*m_stream, m_id, &m_lastSeqNum); - if (error) - RaiseError(DelegateError::ERR_DISPATCH, error); - else - RaiseSuccess(); - } - catch (std::exception&) { - RaiseError(DelegateError::ERR_DISPATCH); - } -#endif - } - - bool Equal(const RemoteDispatchState& rhs) const noexcept { - return m_id == rhs.m_id; - } - -private: - DelegateRemoteId m_id = INVALID_REMOTE_ID; - mutable uint16_t m_lastSeqNum = 0; - UnicastDelegate m_errorHandler; - IDispatcher* m_dispatcher = nullptr; - DelegateError m_error = DelegateError::SUCCESS; - dmq::xostringstream* m_stream = nullptr; - dmq::Mutex* m_sendMutex = nullptr; -}; - -/// @brief Holds a remote delegate's send mutex, if it has one, for the whole -/// serialize-and-dispatch step of one call. -class RemoteSendLock { -public: - explicit RemoteSendLock(dmq::Mutex* mutex) noexcept : m_mutex(mutex) { - if (m_mutex) - m_mutex->lock(); - } - ~RemoteSendLock() noexcept { - if (m_mutex) - m_mutex->unlock(); - } - RemoteSendLock(const RemoteSendLock&) = delete; - RemoteSendLock& operator=(const RemoteSendLock&) = delete; - -private: - dmq::Mutex* m_mutex; -}; - -} // namespace detail - -template -class DelegateFreeRemote; // Not defined - -/// @brief `DelegateFreeRemote<>` class asynchronously invokes a free target function. -/// @tparam RetType The return type of the bound delegate function. -/// @tparam Args The argument types of the bound delegate function. -template -class DelegateFreeRemote : public DelegateFree, public IRemoteInvoker { -public: - typedef std::integral_constant ArgCnt; - typedef RetType(*FreeFunc)(Args...); - using ClassType = DelegateFreeRemote; - using BaseType = DelegateFree; - - static_assert(!(std::disjunction_v...>), - "std::shared_ptr arguments must be passed by value on remote delegates; reference and pointer forms are not allowed"); - static_assert(!(std::disjunction_v...>), - "Double pointer arguments (Arg**) are not allowed on remote delegates"); - using BaseType::operator=; - - /// @brief Constructor to create a class instance. Typically called by sender. - /// @param[in] id The remote delegate identifier. - DelegateFreeRemote(DelegateRemoteId id) { m_state.SetRemoteId(id); } - - /// @brief Constructor to create a class instance. Typically called by receiver. - /// @param[in] func The target free function to store. - /// @param[in] id The remote delegate identifier. - DelegateFreeRemote(FreeFunc func, DelegateRemoteId id) : - BaseType(func) { - Bind(func, id); - } - - /// @brief Copy constructor that creates a copy of the given instance. - /// @details This constructor initializes a new object as a copy of the - /// provided `rhs` (right-hand side) object. The `rhs` object is used to - /// set the state of the new instance. - /// @param[in] rhs The object to copy from. - DelegateFreeRemote(const ClassType& rhs) : - BaseType(rhs) { - Assign(rhs); - } - - /// @brief Move constructor that transfers ownership of resources. - /// @param[in] rhs The object to move from. - DelegateFreeRemote(ClassType&& rhs) noexcept : - BaseType(std::move(rhs)), m_state(std::move(rhs.m_state)), m_serializer(rhs.m_serializer) { - rhs.Clear(); - rhs.m_serializer = nullptr; - } - - DelegateFreeRemote() = default; - - /// @brief Bind a free function to the delegate. - /// @details This method associates a free function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] func The free function to bind to the delegate. This function must - /// match the signature of the delegate. - /// @param[in] id The remote delegate identifier. - void Bind(FreeFunc func, DelegateRemoteId id) { - m_state.SetRemoteId(id); - BaseType::Bind(func); - } - - // - - /// @brief Assigns the state of one object to another. - /// @details Copy the state from the `rhs` (right-hand side) object to the - /// current object. - /// @param[in] rhs The object whose state is to be copied. - void Assign(const ClassType& rhs) { - m_state = rhs.m_state; - m_serializer = rhs.m_serializer; - BaseType::Assign(rhs); - } - - /// @brief Creates a copy of the current object. - /// @details Clones the current instance of the class by creating a new object - /// and copying the state of the current object to it. - /// @return A pointer to a new `ClassType` instance or nullptr if allocation fails. - /// @post The caller is responsible for deleting the clone object and checking for - /// nullptr. - virtual ClassType* Clone() const override { - return new(std::nothrow) ClassType(*this); - } - - /// @brief Assignment operator that assigns the state of one object to another. - /// @param[in] rhs The object whose state is to be assigned to the current object. - /// @return A reference to the current object. - ClassType& operator=(const ClassType& rhs) { - if (&rhs != this) { - BaseType::operator=(rhs); - Assign(rhs); - } - return *this; - } - - /// @brief Move assignment operator that transfers ownership of resources. - /// @param[in] rhs The object to move from. - /// @return A reference to the current object. - ClassType& operator=(ClassType&& rhs) noexcept { - if (&rhs != this) { - BaseType::operator=(std::move(rhs)); - m_state = std::move(rhs.m_state); // Use the resource - m_serializer = rhs.m_serializer; - rhs.m_serializer = nullptr; - } - return *this; - } - - /// @brief Clear the target function. - virtual void operator=(std::nullptr_t) noexcept override { - return this->Clear(); - } - - /// @brief Compares two delegate objects for equality. - /// @param[in] rhs The `DelegateBase` object to compare with the current object. - /// @return `true` if the two delegate objects are equal, `false` otherwise. - virtual bool Equal(const DelegateBase& rhs) const override { - auto derivedRhs = dynamic_cast(&rhs); - return derivedRhs && - m_state.Equal(derivedRhs->m_state) && - BaseType::Equal(rhs); - } - - /// Compares two delegate objects for equality. - /// @return `true` if the objects are equal, `false` otherwise. - bool operator==(const ClassType& rhs) const noexcept { return Equal(rhs); } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - virtual bool operator==(std::nullptr_t) const noexcept override { - return this->Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - virtual bool operator!=(std::nullptr_t) const noexcept override { - return !this->Empty(); - } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - friend bool operator==(std::nullptr_t, const ClassType& rhs) noexcept { - return rhs.Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - friend bool operator!=(std::nullptr_t, const ClassType& rhs) noexcept { - return !rhs.Empty(); - } - - /// @brief Invoke the bound delegate function on the remote. Called by the sender. - /// @details Invoke remote delegate function asynchronously and do not wait for the - /// return value. This function is called by the sender. Dispatches the delegate data to - /// the destination remote receiver. `Invoke()` must be called by the destination - /// remote receiver to invoke the target function. Always safe to call. - /// - /// All argument data is serialized into a binary byte stream. The stream of bytes is - /// sent to the receiver. The receivder deserializes the arguments and invokes the remote - /// target function. - /// - /// All user-defined argument data must inherit from ISerializer and implement the - /// `read()` and `write()` functions to serialize each data member. - /// - /// Does not throw exceptions. However, the platform-specific `ISerializer` implementation - /// might. Register for error callbacks using `SetErrorHandler()`. - /// - /// @param[in] args The function arguments, if any. - /// @return A default return value. The return value is *not* returned from the - /// target function. Do not use the return value. - /// @post Do not use the return value as its not valid. - virtual RetType operator()(Args... args) override { - if (m_serializer && m_state.GetStream()) { - // Remote delegates may share one stream (e.g. every delegate made from - // one RemoteChannel); the send mutex keeps their sends from interleaving. - detail::RemoteSendLock sendLock(m_state.GetSendMutex()); - // Only true once the whole send succeeds (write + stream check + dispatch). - // RaiseSuccess() is deferred to that single point so a write/dispatch failure - // is never preceded by a spurious success callback, and a failure is never - // reported more than once for the same call. - bool writeFailed = false; -#if !defined(__cpp_exceptions) || defined(DMQ_ASSERTS) - // Serialize all target function arguments into a stream - m_serializer->Write(*m_state.GetStream(), std::forward(args)...); -#else - try { - // Serialize all target function arguments into a stream - m_serializer->Write(*m_state.GetStream(), std::forward(args)...); - } - catch (std::exception&) { - writeFailed = true; - m_state.RaiseError(DelegateError::ERR_SERIALIZE); - } -#endif - // Stream-good check, dispatch, and error/success reporting are identical - // regardless of signature or target class - see RemoteDispatchState::SendSerialized(). - m_state.SendSerialized(writeFailed); - } - else { - m_state.RaiseError(DelegateError::ERR_NO_SERIALIZER); - } - - // Do not wait for remote to invoke function call - return RetType(); - } - - /// @brief Invoke delegate function asynchronously. Do not wait for return value. - /// Called by the remote sender. Always safe to call. - /// @param[in] args The function arguments, if any. - void AsyncInvoke(Args... args) { - operator()(std::forward(args)...); - } - - /// @brief Invoke the delegate function on the destination receiver. Called by the - /// remote destination. The sender serializes all target function arguments. This - /// function unserializes the argument data and invokes the remote target function. - /// @details Each source sender call to `operator()` generate a call to `Invoke()` - /// on the destination receiver. - /// @param[in] is The delegate argument stream created and sent within - /// `operator()(Args... args)`. - /// @return `true` if target function invoked; `false` if error. - virtual bool Invoke(std::istream& is) override { - if (!m_serializer) { - m_state.RaiseError(DelegateError::ERR_NO_SERIALIZER); - return false; - } - - if (!is.good()) { - m_state.RaiseError(DelegateError::ERR_STREAM_NOT_GOOD); - return false; - } - -#if !defined(__cpp_exceptions) || defined(DMQ_ASSERTS) - if constexpr (ArgCnt::value == 0) { - BaseType::operator()(); - } - else { - // 1. Create a tuple of RemoteArg to hold the temporary storage - std::tuple...> remoteArgs; - - // 2. Use std::apply to unpack the tuple elements - std::apply([this, &is](auto&... rArgs) { - - // 3. Deserialize: Expand the pack to call Read(is, arg1, arg2...) - // rArgs.Get() returns the reference/pointer to the internal storage - m_serializer->Read(is, rArgs.Get()...); - - if (!is.bad() && !is.fail()) { - // 4. Invoke: Expand the pack to call operator()(arg1, arg2...) - this->BaseType::operator()(rArgs.Get()...); - } - else { - this->m_state.RaiseError(DelegateError::ERR_DESERIALIZE); - } - - }, remoteArgs); - } -#else - if constexpr (ArgCnt::value == 0) { - // No arguments to deserialize, so nothing here can throw a - // deserialization exception. Let any exception from the target - // function itself propagate uncaught -- it is an application - // fault, not a wire-format/serializer fault. - BaseType::operator()(); - } - else { - // 1. Create a tuple of RemoteArg to hold the temporary storage - std::tuple...> remoteArgs; - - // 2. Use std::apply to unpack the tuple elements - std::apply([this, &is](auto&... rArgs) { - - // 3. Deserialize: Expand the pack to call Read(is, arg1, arg2...) - // rArgs.Get() returns the reference/pointer to the internal storage. - // Only this step is wrapped in try/catch: an exception here reflects - // a corrupt stream or serializer bug. The invocation below is - // deliberately NOT wrapped -- if the bound target function throws, - // that is an application exception and must propagate to the caller, - // not be misreported as ERR_DESERIALIZE_EXCEPTION. - bool deserializeOk = true; - try { - m_serializer->Read(is, rArgs.Get()...); - } - catch (std::exception&) { - this->m_state.RaiseError(DelegateError::ERR_DESERIALIZE_EXCEPTION); - deserializeOk = false; - } - - if (deserializeOk) { - if (!is.bad() && !is.fail()) { - // 4. Invoke: Expand the pack to call operator()(arg1, arg2...) - this->BaseType::operator()(rArgs.Get()...); - } - else { - this->m_state.RaiseError(DelegateError::ERR_DESERIALIZE); - } - } - - }, remoteArgs); - } -#endif - - return true; - } - - ///@brief Get the remote identifier. - // @return The remote identifier. - DelegateRemoteId GetRemoteId() noexcept { return m_state.GetRemoteId(); } - - ///@brief Set the remote identifier. - /// @param[in] id The remote identifier. - void SetRemoteId(DelegateRemoteId id) noexcept { m_state.SetRemoteId(id); } - - /// @brief Set the dispatcher instance used to send to remote - /// @param[in] dispatcher A dispatcher instance - void SetDispatcher(IDispatcher* dispatcher) { - m_state.SetDispatcher(dispatcher); - } - - /// @brief Set the serializer instance used to serialize/deserialize - /// function arguments. - /// @param[in] serializer A serializer instance - void SetSerializer(ISerializer* serializer) { - m_serializer = serializer; - } - - /// @brief Set the serialization stream used to store serialized function - /// argument data. - /// @param[in] stream An output stream. - void SetStream(dmq::xostringstream* stream) { - m_state.SetStream(stream); - } - - /// @brief Set the mutex held while serializing into and dispatching the - /// stream. Required when several delegates share one stream across threads. - /// @param[in] mutex The mutex, or nullptr for none. Caller owns it. - void SetSendMutex(dmq::Mutex* mutex) { - m_state.SetSendMutex(mutex); - } - - /// @brief Set the error handler - /// @param[in] errorHandler The delegate error handler called when - /// an error is detected. - void SetErrorHandler(const Delegate& errorHandler) { - m_state.SetErrorHandler(errorHandler); // Copy - } - - /// @brief Set the error handler - /// @param[in] errorHandler The delegate error handler called when - /// an error is detected. - void SetErrorHandler(Delegate&& errorHandler) { - m_state.SetErrorHandler(std::move(errorHandler)); // Moving the temporary - } - - /// @brief Clear the error handler - void ClearErrorHandler() { - m_state.ClearErrorHandler(); - } - - /// @brief Get the last error code - /// @return The last error detected - /// @post Error is reset to SUCCESS after call - DelegateError GetError() { - return m_state.GetError(); - } - - /// @brief Get the sequence number assigned by the dispatcher to the most - /// recent successful dispatch. - /// @return The last dispatched sequence number, or 0 if nothing has been - /// dispatched yet. - uint16_t GetLastSeqNum() const noexcept { return m_state.GetLastSeqNum(); } - -private: - /// Destination remote id, dispatcher, output stream, last error, last sequence - /// number, and error handler. Not templated on Sig/TClass — see - /// `detail::RemoteDispatchState`. - detail::RemoteDispatchState m_state; - - /// A pointer to the function argument serializer. Kept outside `m_state` since, - /// unlike everything else there, its pointee type genuinely varies by signature. - ISerializer* m_serializer = nullptr; - - // -}; - -template -class DelegateMemberRemote; // Not defined - -/// @brief `DelegateMemberRemote<>` class asynchronously invokes a class member target function. -/// @tparam TClass The class type that contains the member function. -/// @tparam RetType The return type of the bound delegate function. -/// @tparam Args The argument types of the bound delegate function. -template -class DelegateMemberRemote : public DelegateMember, public IRemoteInvoker { -public: - typedef std::integral_constant ArgCnt; - typedef TClass* ObjectPtr; - typedef std::shared_ptr SharedPtr; - typedef RetType(TClass::* MemberFunc)(Args...); - typedef RetType(TClass::* ConstMemberFunc)(Args...) const; - using ClassType = DelegateMemberRemote; - using BaseType = DelegateMember; - - static_assert(!(std::disjunction_v...>), - "std::shared_ptr arguments must be passed by value on remote delegates; reference and pointer forms are not allowed"); - static_assert(!(std::disjunction_v...>), - "Double pointer arguments (Arg**) are not allowed on remote delegates"); - using BaseType::operator=; - - /// @brief Constructor to create a class instance. Typically called by sender. - /// @param[in] id The remote delegate identifier. - DelegateMemberRemote(DelegateRemoteId id) { m_state.SetRemoteId(id); } - - /// @brief Constructor to create a class instance. Typically called by receiver. - /// @param[in] object The target object pointer to store. - /// @param[in] func The target member function to store. - /// @param[in] id The delegate remote identifier. - DelegateMemberRemote(SharedPtr object, MemberFunc func, DelegateRemoteId id) : BaseType(object, func) { - Bind(object, func, id); - } - - /// @brief Constructor to create a class instance. Typically called by receiver. - /// @param[in] object The target object pointer to store. - /// @param[in] func The target const member function to store. - /// @param[in] id The delegate remote identifier. - DelegateMemberRemote(SharedPtr object, ConstMemberFunc func, DelegateRemoteId id) : BaseType(object, func) { - Bind(object, func, id); - } - - /// @brief Constructor to create a class instance. Typically called by receiver. - /// @param[in] object The target object pointer to store. - /// @param[in] func The target member function to store. - /// @param[in] id The delegate remote identifier. - DelegateMemberRemote(ObjectPtr object, MemberFunc func, DelegateRemoteId id) : BaseType(object, func) { - Bind(object, func, id); - } - - /// @brief Constructor to create a class instance. Typically called by receiver. - /// @param[in] object The target object pointer to store. - /// @param[in] func The target const member function to store. - /// @param[in] id The delegate remote identifier. - DelegateMemberRemote(ObjectPtr object, ConstMemberFunc func, DelegateRemoteId id) : BaseType(object, func) { - Bind(object, func, id); - } - - /// @brief Copy constructor that creates a copy of the given instance. - /// @details This constructor initializes a new object as a copy of the - /// provided `rhs` (right-hand side) object. The `rhs` object is used to - /// set the state of the new instance. - /// @param[in] rhs The object to copy from. - DelegateMemberRemote(const ClassType& rhs) : - BaseType(rhs) { - Assign(rhs); - } - - /// @brief Move constructor that transfers ownership of resources. - /// @param[in] rhs The object to move from. - DelegateMemberRemote(ClassType&& rhs) noexcept : - BaseType(std::move(rhs)), m_state(std::move(rhs.m_state)), m_serializer(rhs.m_serializer) { - rhs.Clear(); - rhs.m_serializer = nullptr; - } - - DelegateMemberRemote() = default; - - /// @brief Bind a member function to the delegate. - /// @details This method associates a member function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] object The target object instance. - /// @param[in] func The function to bind to the delegate. This function must match - /// the signature of the delegate. - /// @param[in] id The delegate remote identifier. - void Bind(SharedPtr object, MemberFunc func, DelegateRemoteId id) { - m_state.SetRemoteId(id); - BaseType::Bind(object, func); - } - - /// @brief Bind a const member function to the delegate. - /// @details This method associates a member function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] object The target object instance. - /// @param[in] func The member function to bind to the delegate. This function must - /// match the signature of the delegate. - /// @param[in] id The delegate remote identifier. - void Bind(SharedPtr object, ConstMemberFunc func, DelegateRemoteId id) { - m_state.SetRemoteId(id); - BaseType::Bind(object, func); - } - - /// @brief Bind a member function to the delegate. - /// @details This method associates a member function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] object The target object instance. - /// @param[in] func The function to bind to the delegate. This function must match - /// the signature of the delegate. - /// @param[in] id The delegate remote identifier. - void Bind(ObjectPtr object, MemberFunc func, DelegateRemoteId id) { - m_state.SetRemoteId(id); - BaseType::Bind(object, func); - } - - /// @brief Bind a const member function to the delegate. - /// @details This method associates a member function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] object The target object instance. - /// @param[in] func The member function to bind to the delegate. This function must - /// match the signature of the delegate. - /// @param[in] id The delegate remote identifier. - void Bind(ObjectPtr object, ConstMemberFunc func, DelegateRemoteId id) { - m_state.SetRemoteId(id); - BaseType::Bind(object, func); - } - - // - - /// @brief Assigns the state of one object to another. - /// @details Copy the state from the `rhs` (right-hand side) object to the - /// current object. - /// @param[in] rhs The object whose state is to be copied. - void Assign(const ClassType& rhs) { - m_state = rhs.m_state; - m_serializer = rhs.m_serializer; - BaseType::Assign(rhs); - } - - /// @brief Creates a copy of the current object. - /// @details Clones the current instance of the class by creating a new object - /// and copying the state of the current object to it. - /// @return A pointer to a new `ClassType` instance or nullptr if allocation fails. - /// @post The caller is responsible for deleting the clone object and checking for - /// nullptr. - virtual ClassType* Clone() const override { - return new(std::nothrow) ClassType(*this); - } - - /// @brief Assignment operator that assigns the state of one object to another. - /// @param[in] rhs The object whose state is to be assigned to the current object. - /// @return A reference to the current object. - ClassType& operator=(const ClassType& rhs) { - if (&rhs != this) { - BaseType::operator=(rhs); - Assign(rhs); - } - return *this; - } - - /// @brief Move assignment operator that transfers ownership of resources. - /// @param[in] rhs The object to move from. - /// @return A reference to the current object. - ClassType& operator=(ClassType&& rhs) noexcept { - if (&rhs != this) { - BaseType::operator=(std::move(rhs)); - m_state = std::move(rhs.m_state); // Use the resource - m_serializer = rhs.m_serializer; - rhs.m_serializer = nullptr; - } - return *this; - } - - /// @brief Clear the target function. - virtual void operator=(std::nullptr_t) noexcept override { - return this->Clear(); - } - - /// @brief Compares two delegate objects for equality. - /// @param[in] rhs The `DelegateBase` object to compare with the current object. - /// @return `true` if the two delegate objects are equal, `false` otherwise. - virtual bool Equal(const DelegateBase& rhs) const override { - auto derivedRhs = dynamic_cast(&rhs); - return derivedRhs && - m_state.Equal(derivedRhs->m_state) && - BaseType::Equal(rhs); - } - - /// Compares two delegate objects for equality. - /// @return `true` if the objects are equal, `false` otherwise. - bool operator==(const ClassType& rhs) const noexcept { return Equal(rhs); } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - virtual bool operator==(std::nullptr_t) const noexcept override { - return this->Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - virtual bool operator!=(std::nullptr_t) const noexcept override { - return !this->Empty(); - } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - friend bool operator==(std::nullptr_t, const ClassType& rhs) noexcept { - return rhs.Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - friend bool operator!=(std::nullptr_t, const ClassType& rhs) noexcept { - return !rhs.Empty(); - } - - /// @brief Invoke the bound delegate function on the remote. Called by the sender. - /// @details Invoke remote delegate function asynchronously and do not wait for the - /// return value. This function is called by the sender. Dispatches the delegate data to - /// the destination remote receiver. `Invoke()` must be called by the destination - /// remote receiver to invoke the target function. Always safe to call. - /// - /// All argument data is serialized into a binary byte stream. The stream of bytes is - /// sent to the receiver. The receivder deserializes the arguments and invokes the remote - /// target function. - /// - /// All user-defined argument data must inherit from ISerializer and implement the - /// `read()` and `write()` functions to serialize each data member. - /// - /// Does not throw exceptions. However, the platform-specific `ISerializer` implementation - /// might. Register for error callbacks using `SetErrorHandler()`. - /// - /// @param[in] args The function arguments, if any. - /// @return A default return value. The return value is *not* returned from the - /// target function. Do not use the return value. - /// @post Do not use the return value as its not valid. - virtual RetType operator()(Args... args) override { - if (m_serializer && m_state.GetStream()) { - // Remote delegates may share one stream (e.g. every delegate made from - // one RemoteChannel); the send mutex keeps their sends from interleaving. - detail::RemoteSendLock sendLock(m_state.GetSendMutex()); - // Only true once the whole send succeeds (write + stream check + dispatch). - // RaiseSuccess() is deferred to that single point so a write/dispatch failure - // is never preceded by a spurious success callback, and a failure is never - // reported more than once for the same call. - bool writeFailed = false; -#if !defined(__cpp_exceptions) || defined(DMQ_ASSERTS) - // Serialize all target function arguments into a stream - m_serializer->Write(*m_state.GetStream(), std::forward(args)...); -#else - try { - // Serialize all target function arguments into a stream - m_serializer->Write(*m_state.GetStream(), std::forward(args)...); - } - catch (std::exception&) { - writeFailed = true; - m_state.RaiseError(DelegateError::ERR_SERIALIZE); - } -#endif - // Stream-good check, dispatch, and error/success reporting are identical - // regardless of signature or target class - see RemoteDispatchState::SendSerialized(). - m_state.SendSerialized(writeFailed); - } - else { - m_state.RaiseError(DelegateError::ERR_NO_SERIALIZER); - } - - // Do not wait for remote to invoke function call - return RetType(); - } - - /// @brief Invoke delegate function asynchronously. Do not wait for return value. - /// Called by the remote sender. Always safe to call. - /// @param[in] args The function arguments, if any. - void AsyncInvoke(Args... args) { - operator()(std::forward(args)...); - } - - /// @brief Invoke the delegate function on the destination receiver. Called by the - /// remote destination. The sender serializes all target function arguments. This - /// function unserializes the argument data and invokes the remote target function. - /// @details Each source sender call to `operator()` generate a call to `Invoke()` - /// on the destination receiver. - /// @param[in] is The delegate argument stream created and sent within - /// `operator()(Args... args)`. - /// @return `true` if target function invoked; `false` if error. - virtual bool Invoke(std::istream& is) override { - if (!m_serializer) { - m_state.RaiseError(DelegateError::ERR_NO_SERIALIZER); - return false; - } - - if (!is.good()) { - m_state.RaiseError(DelegateError::ERR_STREAM_NOT_GOOD); - return false; - } - -#if !defined(__cpp_exceptions) || defined(DMQ_ASSERTS) - if constexpr (ArgCnt::value == 0) { - BaseType::operator()(); - } - else { - // 1. Create a tuple of RemoteArg to hold the temporary storage - std::tuple...> remoteArgs; - - // 2. Use std::apply to unpack the tuple elements - std::apply([this, &is](auto&... rArgs) { - - // 3. Deserialize: Expand the pack to call Read(is, arg1, arg2...) - // rArgs.Get() returns the reference/pointer to the internal storage - m_serializer->Read(is, rArgs.Get()...); - - if (!is.bad() && !is.fail()) { - // 4. Invoke: Expand the pack to call operator()(arg1, arg2...) - this->BaseType::operator()(rArgs.Get()...); - } - else { - this->m_state.RaiseError(DelegateError::ERR_DESERIALIZE); - } - - }, remoteArgs); - } -#else - if constexpr (ArgCnt::value == 0) { - // No arguments to deserialize, so nothing here can throw a - // deserialization exception. Let any exception from the target - // function itself propagate uncaught -- it is an application - // fault, not a wire-format/serializer fault. - BaseType::operator()(); - } - else { - // 1. Create a tuple of RemoteArg to hold the temporary storage - std::tuple...> remoteArgs; - - // 2. Use std::apply to unpack the tuple elements - std::apply([this, &is](auto&... rArgs) { - - // 3. Deserialize: Expand the pack to call Read(is, arg1, arg2...) - // rArgs.Get() returns the reference/pointer to the internal storage. - // Only this step is wrapped in try/catch: an exception here reflects - // a corrupt stream or serializer bug. The invocation below is - // deliberately NOT wrapped -- if the bound target function throws, - // that is an application exception and must propagate to the caller, - // not be misreported as ERR_DESERIALIZE_EXCEPTION. - bool deserializeOk = true; - try { - m_serializer->Read(is, rArgs.Get()...); - } - catch (std::exception&) { - this->m_state.RaiseError(DelegateError::ERR_DESERIALIZE_EXCEPTION); - deserializeOk = false; - } - - if (deserializeOk) { - if (!is.bad() && !is.fail()) { - // 4. Invoke: Expand the pack to call operator()(arg1, arg2...) - this->BaseType::operator()(rArgs.Get()...); - } - else { - this->m_state.RaiseError(DelegateError::ERR_DESERIALIZE); - } - } - - }, remoteArgs); - } -#endif - - return true; - } - - ///@brief Get the remote identifier. - // @return The remote identifier. - DelegateRemoteId GetRemoteId() noexcept { return m_state.GetRemoteId(); } - - ///@brief Set the remote identifier. - /// @param[in] id The remote identifier. - void SetRemoteId(DelegateRemoteId id) noexcept { m_state.SetRemoteId(id); } - - /// @brief Set the dispatcher instance used to send to remote - /// @param[in] dispatcher A dispatcher instance - void SetDispatcher(IDispatcher* dispatcher) { - m_state.SetDispatcher(dispatcher); - } - - /// @brief Set the serializer instance used to serialize/deserialize - /// function arguments. - /// @param[in] serializer A serializer instance - void SetSerializer(ISerializer* serializer) { - m_serializer = serializer; - } - - /// @brief Set the serialization stream used to store serialized function - /// argument data. - /// @param[in] stream An output stream. - void SetStream(dmq::xostringstream* stream) { - m_state.SetStream(stream); - } - - /// @brief Set the mutex held while serializing into and dispatching the - /// stream. Required when several delegates share one stream across threads. - /// @param[in] mutex The mutex, or nullptr for none. Caller owns it. - void SetSendMutex(dmq::Mutex* mutex) { - m_state.SetSendMutex(mutex); - } - - /// @brief Set the error handler - /// @param[in] errorHandler The delegate error handler called when - /// an error is detected. - void SetErrorHandler(const Delegate& errorHandler) { - m_state.SetErrorHandler(errorHandler); // Copy - } - - /// @brief Set the error handler - /// @param[in] errorHandler The delegate error handler called when - /// an error is detected. - void SetErrorHandler(Delegate&& errorHandler) { - m_state.SetErrorHandler(std::move(errorHandler)); // Moving the temporary - } - - /// @brief Clear the error handler - void ClearErrorHandler() { - m_state.ClearErrorHandler(); - } - - /// @brief Get the last error code - /// @return The last error detected - /// @post Error is reset to SUCCESS after call - DelegateError GetError() { - return m_state.GetError(); - } - - /// @brief Get the sequence number assigned by the dispatcher to the most - /// recent successful dispatch. - /// @return The last dispatched sequence number, or 0 if nothing has been - /// dispatched yet. - uint16_t GetLastSeqNum() const noexcept { return m_state.GetLastSeqNum(); } - -private: - /// Destination remote id, dispatcher, output stream, last error, last sequence - /// number, and error handler. Not templated on Sig/TClass — see - /// `detail::RemoteDispatchState`. - detail::RemoteDispatchState m_state; - - /// A pointer to the function argument serializer. Kept outside `m_state` since, - /// unlike everything else there, its pointee type genuinely varies by signature. - ISerializer* m_serializer = nullptr; - - // -}; - -template -class DelegateFunctionRemote; // Not defined - -/// @brief `DelegateFunctionRemote<>` class asynchronously invokes a `std::function` target function. -/// @details Caution when binding to a `std::function` using this class. `std::function` cannot be -/// compared for equality directly in a meaningful way using `operator==`. -/// -/// See `DelegateFunction<>` base class for important usage limitations. -/// -/// @tparam RetType The return type of the bound delegate function. -/// @tparam Args The argument types of the bound delegate function. -template -class DelegateFunctionRemote : public DelegateFunction, public IRemoteInvoker { -public: - typedef std::integral_constant ArgCnt; - using FunctionType = std::function; - using ClassType = DelegateFunctionRemote; - using BaseType = DelegateFunction; - - static_assert(!(std::disjunction_v...>), - "std::shared_ptr arguments must be passed by value on remote delegates; reference and pointer forms are not allowed"); - static_assert(!(std::disjunction_v...>), - "Double pointer arguments (Arg**) are not allowed on remote delegates"); - using BaseType::operator=; - - /// @brief Constructor to create a class instance. Typically called by sender. - /// @param[in] id The remote delegate identifier. - DelegateFunctionRemote(DelegateRemoteId id) { m_state.SetRemoteId(id); } - - /// @brief Constructor to create a class instance. Typically called by receiver. - /// @param[in] func The target `std::function` to store. - /// @param[in] id The unique remote delegate identifier. - DelegateFunctionRemote(FunctionType func, DelegateRemoteId id) : - BaseType(func) { - Bind(func, id); - } - - /// @brief Copy constructor that creates a copy of the given instance. - /// @details This constructor initializes a new object as a copy of the - /// provided `rhs` (right-hand side) object. The `rhs` object is used to - /// set the state of the new instance. - /// @param[in] rhs The object to copy from. - DelegateFunctionRemote(const ClassType& rhs) : - BaseType(rhs) { - Assign(rhs); - } - - /// @brief Move constructor that transfers ownership of resources. - /// @param[in] rhs The object to move from. - DelegateFunctionRemote(ClassType&& rhs) noexcept : - BaseType(std::move(rhs)), m_state(std::move(rhs.m_state)), m_serializer(rhs.m_serializer) { - rhs.Clear(); - rhs.m_serializer = nullptr; - } - - DelegateFunctionRemote() = default; - - /// @brief Bind a `std::function` to the delegate. - /// @details This method associates a member function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] func The `std::function` to bind to the delegate. This function must match - /// the signature of the delegate. - /// @param[in] id The delegate remote identifier. - void Bind(FunctionType func, DelegateRemoteId id) { - m_state.SetRemoteId(id); - BaseType::Bind(func); - } - - // - - /// @brief Assigns the state of one object to another. - /// @details Copy the state from the `rhs` (right-hand side) object to the - /// current object. - /// @param[in] rhs The object whose state is to be copied. - void Assign(const ClassType& rhs) { - m_state = rhs.m_state; - m_serializer = rhs.m_serializer; - BaseType::Assign(rhs); - } - - /// @brief Creates a copy of the current object. - /// @details Clones the current instance of the class by creating a new object - /// and copying the state of the current object to it. - /// @return A pointer to a new `ClassType` instance or nullptr if allocation fails. - /// @post The caller is responsible for deleting the clone object and checking for - /// nullptr. - virtual ClassType* Clone() const override { - return new(std::nothrow) ClassType(*this); - } - - /// @brief Assignment operator that assigns the state of one object to another. - /// @param[in] rhs The object whose state is to be assigned to the current object. - /// @return A reference to the current object. - ClassType& operator=(const ClassType& rhs) { - if (&rhs != this) { - BaseType::operator=(rhs); - Assign(rhs); - } - return *this; - } - - /// @brief Move assignment operator that transfers ownership of resources. - /// @param[in] rhs The object to move from. - /// @return A reference to the current object. - ClassType& operator=(ClassType&& rhs) noexcept { - if (&rhs != this) { - BaseType::operator=(std::move(rhs)); - m_state = std::move(rhs.m_state); // Use the resource - m_serializer = rhs.m_serializer; - rhs.m_serializer = nullptr; - } - return *this; - } - - /// @brief Clear the target function. - virtual void operator=(std::nullptr_t) noexcept override { - return this->Clear(); - } - - /// @brief Compares two delegate objects for equality. - /// @param[in] rhs The `DelegateBase` object to compare with the current object. - /// @return `true` if the two delegate objects are equal, `false` otherwise. - virtual bool Equal(const DelegateBase& rhs) const override { - auto derivedRhs = dynamic_cast(&rhs); - return derivedRhs && - m_state.Equal(derivedRhs->m_state) && - BaseType::Equal(rhs); - } - - /// Compares two delegate objects for equality. - /// @return `true` if the objects are equal, `false` otherwise. - bool operator==(const ClassType& rhs) const noexcept { return Equal(rhs); } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - virtual bool operator==(std::nullptr_t) const noexcept override { - return this->Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - virtual bool operator!=(std::nullptr_t) const noexcept override { - return !this->Empty(); - } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - friend bool operator==(std::nullptr_t, const ClassType& rhs) noexcept { - return rhs.Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - friend bool operator!=(std::nullptr_t, const ClassType& rhs) noexcept { - return !rhs.Empty(); - } - - /// @brief Invoke the bound delegate function on the remote. Called by the sender. - /// @details Invoke remote delegate function asynchronously and do not wait for the - /// return value. This function is called by the sender. Dispatches the delegate data to - /// the destination remote receiver. `Invoke()` must be called by the destination - /// remote receiver to invoke the target function. Always safe to call. - /// - /// All argument data is serialized into a binary byte stream. The stream of bytes is - /// sent to the receiver. The receivder deserializes the arguments and invokes the remote - /// target function. - /// - /// All user-defined argument data must inherit from ISerializer and implement the - /// `read()` and `write()` functions to serialize each data member. - /// - /// Does not throw exceptions. However, the platform-specific `ISerializer` implementation - /// might. Register for error callbacks using `SetErrorHandler()`. - /// - /// @param[in] args The function arguments, if any. - /// @return A default return value. The return value is *not* returned from the - /// target function. Do not use the return value. - /// @post Do not use the return value as its not valid. - virtual RetType operator()(Args... args) override { - if (m_serializer && m_state.GetStream()) { - // Remote delegates may share one stream (e.g. every delegate made from - // one RemoteChannel); the send mutex keeps their sends from interleaving. - detail::RemoteSendLock sendLock(m_state.GetSendMutex()); - // Only true once the whole send succeeds (write + stream check + dispatch). - // RaiseSuccess() is deferred to that single point so a write/dispatch failure - // is never preceded by a spurious success callback, and a failure is never - // reported more than once for the same call. - bool writeFailed = false; -#if !defined(__cpp_exceptions) || defined(DMQ_ASSERTS) - // Serialize all target function arguments into a stream - m_serializer->Write(*m_state.GetStream(), std::forward(args)...); -#else - try { - // Serialize all target function arguments into a stream - m_serializer->Write(*m_state.GetStream(), std::forward(args)...); - } - catch (std::exception&) { - writeFailed = true; - m_state.RaiseError(DelegateError::ERR_SERIALIZE); - } -#endif - // Stream-good check, dispatch, and error/success reporting are identical - // regardless of signature or target class - see RemoteDispatchState::SendSerialized(). - m_state.SendSerialized(writeFailed); - } - else { - m_state.RaiseError(DelegateError::ERR_NO_SERIALIZER); - } - - // Do not wait for remote to invoke function call - return RetType(); - } - - /// @brief Invoke delegate function asynchronously. Do not wait for return value. - /// Called by the remote sender. Always safe to call. - /// @param[in] args The function arguments, if any. - void AsyncInvoke(Args... args) { - operator()(std::forward(args)...); - } - - /// @brief Invoke the delegate function on the destination receiver. Called by the - /// remote destination. The sender serializes all target function arguments. This - /// function unserializes the argument data and invokes the remote target function. - /// @details Each source sender call to `operator()` generate a call to `Invoke()` - /// on the destination receiver. - /// @param[in] is The delegate argument stream created and sent within - /// `operator()(Args... args)`. - /// @return `true` if target function invoked; `false` if error. - virtual bool Invoke(std::istream& is) override { - if (!m_serializer) { - m_state.RaiseError(DelegateError::ERR_NO_SERIALIZER); - return false; - } - - if (!is.good()) { - m_state.RaiseError(DelegateError::ERR_STREAM_NOT_GOOD); - return false; - } - -#if !defined(__cpp_exceptions) || defined(DMQ_ASSERTS) - if constexpr (ArgCnt::value == 0) { - BaseType::operator()(); - } - else { - // 1. Create a tuple of RemoteArg to hold the temporary storage - std::tuple...> remoteArgs; - - // 2. Use std::apply to unpack the tuple elements - std::apply([this, &is](auto&... rArgs) { - - // 3. Deserialize: Expand the pack to call Read(is, arg1, arg2...) - // rArgs.Get() returns the reference/pointer to the internal storage - m_serializer->Read(is, rArgs.Get()...); - - if (!is.bad() && !is.fail()) { - // 4. Invoke: Expand the pack to call operator()(arg1, arg2...) - this->BaseType::operator()(rArgs.Get()...); - } - else { - this->m_state.RaiseError(DelegateError::ERR_DESERIALIZE); - } - - }, remoteArgs); - } -#else - if constexpr (ArgCnt::value == 0) { - // No arguments to deserialize, so nothing here can throw a - // deserialization exception. Let any exception from the target - // function itself propagate uncaught -- it is an application - // fault, not a wire-format/serializer fault. - BaseType::operator()(); - } - else { - // 1. Create a tuple of RemoteArg to hold the temporary storage - std::tuple...> remoteArgs; - - // 2. Use std::apply to unpack the tuple elements - std::apply([this, &is](auto&... rArgs) { - - // 3. Deserialize: Expand the pack to call Read(is, arg1, arg2...) - // rArgs.Get() returns the reference/pointer to the internal storage. - // Only this step is wrapped in try/catch: an exception here reflects - // a corrupt stream or serializer bug. The invocation below is - // deliberately NOT wrapped -- if the bound target function throws, - // that is an application exception and must propagate to the caller, - // not be misreported as ERR_DESERIALIZE_EXCEPTION. - bool deserializeOk = true; - try { - m_serializer->Read(is, rArgs.Get()...); - } - catch (std::exception&) { - this->m_state.RaiseError(DelegateError::ERR_DESERIALIZE_EXCEPTION); - deserializeOk = false; - } - - if (deserializeOk) { - if (!is.bad() && !is.fail()) { - // 4. Invoke: Expand the pack to call operator()(arg1, arg2...) - this->BaseType::operator()(rArgs.Get()...); - } - else { - this->m_state.RaiseError(DelegateError::ERR_DESERIALIZE); - } - } - - }, remoteArgs); - } -#endif - - return true; - } - - ///@brief Get the remote identifier. - // @return The remote identifier. - DelegateRemoteId GetRemoteId() noexcept { return m_state.GetRemoteId(); } - - ///@brief Set the remote identifier. - /// @param[in] id The remote identifier. - void SetRemoteId(DelegateRemoteId id) noexcept { m_state.SetRemoteId(id); } - - /// @brief Set the dispatcher instance used to send to remote - /// @param[in] dispatcher A dispatcher instance - void SetDispatcher(IDispatcher* dispatcher) { - m_state.SetDispatcher(dispatcher); - } - - /// @brief Set the serializer instance used to serialize/deserialize - /// function arguments. - /// @param[in] serializer A serializer instance - void SetSerializer(ISerializer* serializer) { - m_serializer = serializer; - } - - /// @brief Set the serialization stream used to store serialized function - /// argument data. - /// @param[in] stream An output stream. - void SetStream(dmq::xostringstream* stream) { - m_state.SetStream(stream); - } - - /// @brief Set the mutex held while serializing into and dispatching the - /// stream. Required when several delegates share one stream across threads. - /// @param[in] mutex The mutex, or nullptr for none. Caller owns it. - void SetSendMutex(dmq::Mutex* mutex) { - m_state.SetSendMutex(mutex); - } - - /// @brief Set the error handler - /// @param[in] errorHandler The delegate error handler called when - /// an error is detected. - void SetErrorHandler(const Delegate& errorHandler) { - m_state.SetErrorHandler(errorHandler); // Copy - } - - /// @brief Set the error handler - /// @param[in] errorHandler The delegate error handler called when - /// an error is detected. - void SetErrorHandler(Delegate&& errorHandler) { - m_state.SetErrorHandler(std::move(errorHandler)); // Moving the temporary - } - - /// @brief Clear the error handler - void ClearErrorHandler() { - m_state.ClearErrorHandler(); - } - - /// @brief Get the last error code - /// @return The last error detected - /// @post Error is reset to SUCCESS after call - DelegateError GetError() { - return m_state.GetError(); - } - - /// @brief Get the sequence number assigned by the dispatcher to the most - /// recent successful dispatch. - /// @return The last dispatched sequence number, or 0 if nothing has been - /// dispatched yet. - uint16_t GetLastSeqNum() const noexcept { return m_state.GetLastSeqNum(); } - -private: - /// Destination remote id, dispatcher, output stream, last error, last sequence - /// number, and error handler. Not templated on Sig/TClass — see - /// `detail::RemoteDispatchState`. - detail::RemoteDispatchState m_state; - - /// A pointer to the function argument serializer. Kept outside `m_state` since, - /// unlike everything else there, its pointee type genuinely varies by signature. - ISerializer* m_serializer = nullptr; - - // -}; - -/// @brief Creates an asynchronous delegate that binds to a free function. -/// @tparam RetType The return type of the free function. -/// @tparam Args The types of the function arguments. -/// @param[in] func A pointer to the free function to bind to the delegate. -/// @param[in] id The delegate remote identifier. -/// @return A `DelegateFreeRemote` object bound to the specified free function and id. -template -auto MakeDelegate(RetType(*func)(Args... args), DelegateRemoteId id) { - return DelegateFreeRemote(func, id); -} - -/// @brief Creates an asynchronous delegate that binds to a non-const member function. -/// @tparam TClass The class type that contains the member function. -/// @tparam RetType The return type of the member function. -/// @tparam Args The types of the function arguments. -/// @param[in] object A pointer to the instance of `TClass` that will be used for the delegate. -/// @param[in] func A pointer to the non-const member function of `TClass` to bind to the delegate. -/// @param[in] id The delegate remote identifier. -/// @return A `DelegateMemberRemote` object bound to the specified non-const member function and id. -template -auto MakeDelegate(TClass* object, RetType(TClass::* func)(Args... args), DelegateRemoteId id) { - return DelegateMemberRemote(object, func, id); -} - -/// @brief Creates an asynchronous delegate that binds to a const member function. -/// @tparam TClass The class type that contains the const member function. -/// @tparam RetType The return type of the member function. -/// @tparam Args The types of the function arguments. -/// @param[in] object A pointer to the instance of `TClass` that will be used for the delegate. -/// @param[in] func A pointer to the const member function of `TClass` to bind to the delegate. -/// @param[in] id The delegate remote identifier. -/// @return A `DelegateMemberRemote` object bound to the specified const member function and id. -template -auto MakeDelegate(TClass* object, RetType(TClass::* func)(Args... args) const, DelegateRemoteId id) { - return DelegateMemberRemote(object, func, id); -} - -/// @brief Creates a delegate that binds to a const member function. -/// @tparam TClass The const class type that contains the const member function. -/// @tparam RetType The return type of the member function. -/// @tparam Args The types of the function arguments. -/// @param[in] object A pointer to the instance of `TClass` that will be used for the delegate. -/// @param[in] func A pointer to the non-const member function of `TClass` to bind to the delegate. -/// @param[in] id The delegate remote identifier. -/// @return A `DelegateMemberRemote` object bound to the specified non-const member function. -template -auto MakeDelegate(const TClass* object, RetType(TClass::* func)(Args... args) const, DelegateRemoteId id) { - return DelegateMemberRemote(object, func, id); -} - -/// @brief Creates an asynchronous delegate that binds to a non-const member function using a shared pointer. -/// @tparam TClass The class type that contains the member function. -/// @tparam RetType The return type of the member function. -/// @tparam Args The types of the function arguments. -/// @param[in] object A shared pointer to the instance of `TClass` that will be used for the delegate. -/// @param[in] func A pointer to the non-const member function of `TClass` to bind to the delegate. -/// @param[in] id The delegate remote identifier. -/// @return A `DelegateMemberRemote` shared pointer bound to the specified non-const member function and id. -template -auto MakeDelegate(std::shared_ptr object, RetVal(TClass::* func)(Args... args), DelegateRemoteId id) { - return DelegateMemberRemote(object, func, id); -} - -/// @brief Creates an asynchronous delegate that binds to a const member function using a shared pointer. -/// @tparam TClass The class type that contains the member function. -/// @tparam RetVal The return type of the member function. -/// @tparam Args The types of the function arguments. -/// @param[in] object A shared pointer to the instance of `TClass` that will be used for the delegate. -/// @param[in] func A pointer to the const member function of `TClass` to bind to the delegate. -/// @param[in] id The delegate remote identifier. -/// @return A `DelegateMemberRemote` shared pointer bound to the specified const member function and id. -template -auto MakeDelegate(std::shared_ptr object, RetVal(TClass::* func)(Args... args) const, DelegateRemoteId id) { - return DelegateMemberRemote(object, func, id); -} - -/// @brief Creates an asynchronous delegate that binds to a `std::function`. -/// @tparam RetType The return type of the `std::function`. -/// @tparam Args The types of the function arguments. -/// @param[in] func The `std::function` to bind to the delegate. -/// @param[in] id The delegate remote identifier. -/// @return A `DelegateFunctionRemote` object bound to the specified `std::function` and id. -template -auto MakeDelegate(std::function func, DelegateRemoteId id) { - return DelegateFunctionRemote(func, id); -} - -/// @brief Creates an asynchronous delegate that binds to a raw lambda or functor. -/// @tparam F The lambda or functor type. -/// @param[in] func The lambda or functor to bind. -/// @param[in] id The delegate remote identifier. -/// @return A `DelegateFunctionRemote` object bound to the specified lambda or functor and id. -template ::value>> -auto MakeDelegate(F&& func, DelegateRemoteId id) { - using Sig = typename trait::function_traits::operator())>::function_type; - return DelegateFunctionRemote(std::forward(func), id); -} - -} - -DMQ_OPTIMIZE_OFF - -#endif diff --git a/DelegateMQ/delegate/DelegateSelect.h b/DelegateMQ/delegate/DelegateSelect.h deleted file mode 100644 index 55b20d4..0000000 --- a/DelegateMQ/delegate/DelegateSelect.h +++ /dev/null @@ -1,182 +0,0 @@ -#ifndef _DELEGATE_SELECT_H -#define _DELEGATE_SELECT_H - -/// @file -/// @brief Option selection: user config, port auto-detection and derived -/// DMQ_* macros. -/// -/// Preprocessor definitions only: no code, no includes beyond the user and -/// default config headers. Library .cpp files include this (not DelegateOpt.h) -/// to decide whether they compile to anything, so an unselected file adds -/// nothing to the build. DelegateOpt.h includes it first. - -// Pull in user config if provided, otherwise use library defaults. -// To provide your own config: -DDMQ_USER_CONFIG="path/to/DelegateMQConfig.h", -// or put a file named DelegateMQConfig.h on the include path and it is picked -// up automatically (define DMQ_NO_USER_CONFIG to ignore it). The config can -// select ports and options (DMQ_THREAD_*, DMQ_ALLOCATOR, ...) as well as tune -// constants, so a build without CMake needs no -D flags at all. -#ifdef DMQ_USER_CONFIG - #include DMQ_USER_CONFIG -#elif !defined(DMQ_NO_USER_CONFIG) && defined(__has_include) - #if __has_include("DelegateMQConfig.h") - #include "DelegateMQConfig.h" - #endif -#endif -#include "DelegateMQConfig_Default.h" - -// --- PLATFORM AUTO-DETECTION --- -// If no threading model is defined, attempt to auto-select a default -#if !defined(DMQ_THREAD_STDLIB) && !defined(DMQ_THREAD_WIN32) && !defined(DMQ_THREAD_POSIX) && \ - !defined(DMQ_THREAD_FREERTOS) && !defined(DMQ_THREAD_THREADX) && \ - !defined(DMQ_THREAD_ZEPHYR) && !defined(DMQ_THREAD_CMSIS_RTOS2) && \ - !defined(DMQ_THREAD_NUTTX) && \ - !defined(DMQ_THREAD_QT) && !defined(DMQ_THREAD_NONE) - - #if defined(_WIN32) || defined(__linux__) || defined(__APPLE__) || defined(__unix__) - #define DMQ_THREAD_STDLIB - #else - #define DMQ_THREAD_NONE - #endif -#endif - -// --- EMBEDDED RTOS THREAD CLASSIFICATION --- -// Named composite macros for two related but distinct "is this DMQ_THREAD_* -// an embedded RTOS port" questions, so downstream code (this file's own -// DataBus default below, extras/util/NetworkConnect.h's host-header default) -// references a name instead of each re-deriving its own copy of the -// DMQ_THREAD_* list. Adding a new DMQ_THREAD_* port means updating these two -// macros -- and Defaults.cmake's DMQ_DATABUS default, which mirrors -// DMQ_THREAD_IS_EMBEDDED_RTOS's membership and says so in its own comment -- -// not every call site that happens to care about the answer. - -// True for every embedded RTOS thread port. Used to decide whether desktop- -// oriented defaults (DataBus auto-enable, below) should apply. -#if defined(DMQ_THREAD_FREERTOS) || defined(DMQ_THREAD_THREADX) || \ - defined(DMQ_THREAD_ZEPHYR) || defined(DMQ_THREAD_CMSIS_RTOS2) || \ - defined(DMQ_THREAD_NUTTX) - #define DMQ_THREAD_IS_EMBEDDED_RTOS -#endif - -// True only for the subset of embedded RTOS thread ports whose simulator/ -// native build bundles its own network stack headers that collide with real -// host BSD/Winsock headers (e.g. Zephyr's redefining -// sockaddr_in et al.). FreeRTOS is deliberately NOT included here: its -// Win32/POSIX simulator ports (databus-freertos, freertos-linux) have no -// native network stack of their own to collide with, and use real host -// sockets on purpose. -#if defined(DMQ_THREAD_THREADX) || defined(DMQ_THREAD_ZEPHYR) || defined(DMQ_THREAD_CMSIS_RTOS2) - #define DMQ_THREAD_HAS_NATIVE_NETWORK_STACK -#endif - -// True when a real thread model is configured (desktop or embedded RTOS), -// as opposed to DMQ_THREAD_NONE or no thread model at all (bare metal, -// single-threaded). Named once here instead of hand-copying this same -// 8-macro list at every call site that needs to know whether Mutex/ -// ConditionVariable/std::thread-equivalent support exists. -#if defined(DMQ_THREAD_STDLIB) || defined(DMQ_THREAD_WIN32) || defined(DMQ_THREAD_QT) || \ - defined(DMQ_THREAD_POSIX) || \ - defined(DMQ_THREAD_FREERTOS) || defined(DMQ_THREAD_THREADX) || \ - defined(DMQ_THREAD_ZEPHYR) || defined(DMQ_THREAD_CMSIS_RTOS2) || \ - defined(DMQ_THREAD_NUTTX) - #define DMQ_HAS_THREADING -#endif - -// dmq::os::StartGate / Thread::SetStartGate() (port/os/common/StartGate.h): -// every thread port. Code also built for bare metal tests this first. -#if defined(DMQ_HAS_THREADING) - #define DMQ_HAS_START_GATE -#endif - -// If no serialization model is defined, attempt to auto-select a default -#if !defined(DMQ_SERIALIZE_SERIALIZE) && !defined(DMQ_SERIALIZE_RAPIDJSON) && \ - !defined(DMQ_SERIALIZE_MSGPACK) && !defined(DMQ_SERIALIZE_CEREAL) && \ - !defined(DMQ_SERIALIZE_BITSERY) && !defined(DMQ_SERIALIZE_NONE) - - #if defined(_WIN32) || defined(__linux__) || defined(__APPLE__) || defined(__unix__) - #define DMQ_SERIALIZE_SERIALIZE - #else - #define DMQ_SERIALIZE_NONE - #endif -#endif - -// If no transport is defined, auto-select one. Matches Defaults.cmake on -// desktop (CMake always passes a transport, so this only applies to builds -// without it). RTOS and bare-metal ports default to no transport, even when -// built as a host simulator, so host socket headers aren't pulled in. -#if !defined(DMQ_TRANSPORT_NONE) && !defined(DMQ_TRANSPORT_ZEROMQ) && \ - !defined(DMQ_TRANSPORT_NNG) && !defined(DMQ_TRANSPORT_MQTT) && \ - !defined(DMQ_TRANSPORT_WIN32_PIPE) && !defined(DMQ_TRANSPORT_WIN32_UDP) && \ - !defined(DMQ_TRANSPORT_WIN32_TCP) && !defined(DMQ_TRANSPORT_LINUX_UDP) && \ - !defined(DMQ_TRANSPORT_LINUX_UDS) && !defined(DMQ_TRANSPORT_LINUX_TCP) && \ - !defined(DMQ_TRANSPORT_SERIAL_PORT) && !defined(DMQ_TRANSPORT_ARM_LWIP_UDP) && \ - !defined(DMQ_TRANSPORT_ARM_LWIP_NETCONN_UDP) && !defined(DMQ_TRANSPORT_THREADX_UDP) && \ - !defined(DMQ_TRANSPORT_STM32_UART) && !defined(DMQ_TRANSPORT_ZEPHYR_UDP) - - #if defined(DMQ_THREAD_IS_EMBEDDED_RTOS) || !defined(DMQ_HAS_THREADING) - #define DMQ_TRANSPORT_NONE - #elif defined(_WIN32) - #define DMQ_TRANSPORT_WIN32_UDP - #elif defined(__linux__) - #define DMQ_TRANSPORT_LINUX_UDP - #else - #define DMQ_TRANSPORT_NONE - #endif -#endif - -// --- ONE OF EACH --- -// Two ports of a kind means two places picked one, typically CMake's DMQ_THREAD -// (passed with -D) and a #define in DelegateMQConfig.h. CMake then compiles one -// port's sources while the headers use another, so fail here instead. -#if (defined(DMQ_THREAD_STDLIB) + defined(DMQ_THREAD_WIN32) + defined(DMQ_THREAD_POSIX) + \ - defined(DMQ_THREAD_FREERTOS) + defined(DMQ_THREAD_THREADX) + defined(DMQ_THREAD_ZEPHYR) + \ - defined(DMQ_THREAD_CMSIS_RTOS2) + defined(DMQ_THREAD_NUTTX) + defined(DMQ_THREAD_QT) + \ - defined(DMQ_THREAD_NONE)) > 1 - #error "More than one DMQ_THREAD_* is defined. With CMake, set DMQ_THREAD in CMake only, not in DelegateMQConfig.h." -#endif -#if (defined(DMQ_SERIALIZE_SERIALIZE) + defined(DMQ_SERIALIZE_RAPIDJSON) + \ - defined(DMQ_SERIALIZE_MSGPACK) + defined(DMQ_SERIALIZE_CEREAL) + \ - defined(DMQ_SERIALIZE_BITSERY) + defined(DMQ_SERIALIZE_NONE)) > 1 - #error "More than one DMQ_SERIALIZE_* is defined. With CMake, set DMQ_SERIALIZE in CMake only, not in DelegateMQConfig.h." -#endif -#if (defined(DMQ_TRANSPORT_NONE) + defined(DMQ_TRANSPORT_ZEROMQ) + defined(DMQ_TRANSPORT_NNG) + \ - defined(DMQ_TRANSPORT_MQTT) + defined(DMQ_TRANSPORT_WIN32_PIPE) + defined(DMQ_TRANSPORT_WIN32_UDP) + \ - defined(DMQ_TRANSPORT_WIN32_TCP) + defined(DMQ_TRANSPORT_LINUX_UDP) + defined(DMQ_TRANSPORT_LINUX_UDS) + \ - defined(DMQ_TRANSPORT_LINUX_TCP) + defined(DMQ_TRANSPORT_SERIAL_PORT) + \ - defined(DMQ_TRANSPORT_ARM_LWIP_UDP) + defined(DMQ_TRANSPORT_ARM_LWIP_NETCONN_UDP) + \ - defined(DMQ_TRANSPORT_THREADX_UDP) + defined(DMQ_TRANSPORT_STM32_UART) + \ - defined(DMQ_TRANSPORT_ZEPHYR_UDP)) > 1 - #error "More than one DMQ_TRANSPORT_* is defined. With CMake, set DMQ_TRANSPORT in CMake only, not in DelegateMQConfig.h." -#endif - -// Default to DataBus ON on Desktop if not explicitly disabled. -// -// _WIN32/__linux__/__APPLE__/__unix__ reflect the compiler/host doing the -// building, not the actual target: an RTOS simulator sample (e.g. -// zephyr-linux/threadx-linux/freertos-linux) compiles with a host GCC on a -// Unix box despite targeting DMQ_THREAD_ZEPHYR/THREADX/FREERTOS, so this -// used to auto-enable DataBus for those too even without CMake in the -// picture. DataBus's NetworkConnect.h reaches for the host's own BSD -// socket headers unconditionally on Linux/macOS/Windows, which can conflict -// outright with a target's own native network stack headers (e.g. Zephyr's -// redefining sockaddr_in et al.) if the application -// also pulls those in directly (a UDP transport sample, for instance). -// DMQ_THREAD_IS_EMBEDDED_RTOS mirrors Defaults.cmake's equivalent CMake- -// level default, for projects that set these macros by hand instead of -// going through DelegateMQ.cmake. DMQ_THREAD_NONE is excluded as well, as in -// Defaults.cmake: DataBus's ThreadMonitor needs a thread port. -#if !defined(DMQ_DATABUS) && !defined(DMQ_DATABUS_OFF) && \ - !defined(DMQ_THREAD_IS_EMBEDDED_RTOS) && defined(DMQ_HAS_THREADING) - #if defined(_WIN32) || defined(__linux__) || defined(__APPLE__) || defined(__unix__) - #define DMQ_DATABUS - #endif -#endif - -// Default to DataBus Tools ON on Desktop if DataBus is active and not explicitly disabled -#if defined(DMQ_DATABUS) && !defined(DMQ_DATABUS_TOOLS) && !defined(DMQ_DATABUS_TOOLS_OFF) - #if defined(_WIN32) || defined(__linux__) || defined(__APPLE__) || defined(__unix__) - #define DMQ_DATABUS_TOOLS - #endif -#endif - -#endif // _DELEGATE_SELECT_H diff --git a/DelegateMQ/delegate/IDispatcher.h b/DelegateMQ/delegate/IDispatcher.h deleted file mode 100644 index 8029deb..0000000 --- a/DelegateMQ/delegate/IDispatcher.h +++ /dev/null @@ -1,42 +0,0 @@ -#ifndef _IDISPATCHER_H -#define _IDISPATCHER_H - -/// @file -/// @brief Delegate dispatcher interface class. - -#include -#include "DelegateOpt.h" - -namespace dmq { - -// Remote identifier shared between sender and receiver remotes. -typedef uint16_t DelegateRemoteId; -const uint16_t INVALID_REMOTE_ID = static_cast(-1); -const uint16_t ACK_REMOTE_ID = 0; - -/// @TODO Implement the IDispatcher interface if necessary. -/// @brief Delegate interface class to dispatch serialized function argument data -/// to a remote destination. Implemented by the application if using remote delegates. -/// -/// @details Incoming data from the remote must the `IDispatcher::Dispatch()` to -/// invoke the target function using argument data. The argument data is serialized -/// for transport using a concrete class implementing the `ISerialzer` interface -/// allowing any data argument serialization method is supported. -/// @post The receiver calls `IRemoteInvoker::Invoke()` when the dispatched message -/// is received. -class IDispatcher -{ -public: - virtual ~IDispatcher() = default; - - /// Dispatch a stream of bytes to a remote system. The implementer is responsible - /// for sending the bytes over a communication transport (UDP, TCP, shared memory, - /// serial, ...). - /// @param[in] os An outgoing stream to send to the remote destination. - /// @param[in] id The unique delegate identifier shared between sender and receiver. - virtual int Dispatch(dmq::xostringstream& os, DelegateRemoteId id, uint16_t* outSeqNum = nullptr) = 0; -}; - -} - -#endif \ No newline at end of file diff --git a/DelegateMQ/delegate/IInvoker.h b/DelegateMQ/delegate/IInvoker.h deleted file mode 100644 index ea48368..0000000 --- a/DelegateMQ/delegate/IInvoker.h +++ /dev/null @@ -1,43 +0,0 @@ -#ifndef _IINVOKER_H -#define _IINVOKER_H - -/// @file -/// @brief Delegate inter-thread invoker base class. - -#include - -namespace dmq { - -class DelegateMsg; - -/// @brief Abstract base class to support asynchronous delegate function invoke -/// on destination thread of control. Used internally by the delegate library, -/// not user application code. -class IThreadInvoker -{ -public: - virtual ~IThreadInvoker() = default; - - /// Called to invoke the bound target function by the destination thread of control. - /// @param[in] msg The incoming delegate message. - /// @return `true` if function was invoked; `false` if failed. - virtual bool Invoke(std::shared_ptr msg) = 0; -}; - -/// @brief Abstract base class to support remote delegate function invoke -/// to a remote system. Used internally by the delegate library, not -/// user application code. -class IRemoteInvoker -{ -public: - virtual ~IRemoteInvoker() = default; - - /// Called to invoke the bound target function by the remote system. - /// @param[in] is The incoming remote message stream. - /// @return `true` if function was invoked; `false` if failed. - virtual bool Invoke(std::istream& is) = 0; -}; - -} - -#endif \ No newline at end of file diff --git a/DelegateMQ/delegate/ISerializer.h b/DelegateMQ/delegate/ISerializer.h deleted file mode 100644 index 5045585..0000000 --- a/DelegateMQ/delegate/ISerializer.h +++ /dev/null @@ -1,66 +0,0 @@ -#ifndef _ISERIALIZER_H -#define _ISERIALIZER_H - -/// @file ISerializer.h -/// @brief Interface for custom argument serialization/deserialization. -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. - -#include - -namespace dmq { - - template - class ISerializer; // Not defined - - /// @TODO Implement the ISerializer interface if necessary. - /// @brief Interface definition for serializing remote function arguments. - /// - /// @details - /// When using Remote Delegates, the library needs a way to turn arbitrary C++ function arguments - /// into a byte stream (for network transport) and back again. - /// - /// Users must implement this interface for the specific function signatures they intend to call - /// remotely, OR use one of the pre-defined serializers provided in `port/serialize` - /// (e.g., MessagePack, JSON, Cereal). - /// - /// @tparam RetType The return type of the function signature. - /// @tparam Args The variadic argument types of the function signature. - template - class ISerializer - { - public: - virtual ~ISerializer() = default; - - /// @brief Serializes function arguments into the output stream. - /// - /// @details - /// Called by the `DelegateRemote` when the user invokes a remote delegate. - /// The implementation must write every argument in `args` into `os`. - /// - /// @param[out] os The output stream (buffer) to write data to. - /// @param[in] args The actual arguments passed to the delegate invocation. - /// @return Reference to the output stream. - virtual std::ostream& Write(std::ostream& os, const Args&... args) = 0; - - /// @brief Deserializes data from the input stream into function arguments. - /// - /// @details - /// Called by the receiving endpoint before invoking the target function. - /// The implementation must read data from `is` and populate the references in `args`. - /// - /// @note - /// When deserializing pointer arguments like `const T*`, `args` will be a reference - /// to a `const T*` (`const T*&`). Because the object is conceptually const, writing - /// deserialized data directly to `*arg` is ill-formed. As a workaround, implementations - /// must use `const_cast(arg)` to cast away constness and write to the underlying - /// mutable storage provided by the framework, or allocate a new object if preferred. - /// - /// @param[in] is The input stream (buffer) containing received data. - /// @param[out] args References to the arguments where the data should be stored. - /// @return Reference to the input stream. - virtual std::istream& Read(std::istream& is, Args&... args) = 0; - }; -} - -#endif \ No newline at end of file diff --git a/DelegateMQ/delegate/IThread.h b/DelegateMQ/delegate/IThread.h deleted file mode 100644 index fb3069e..0000000 --- a/DelegateMQ/delegate/IThread.h +++ /dev/null @@ -1,68 +0,0 @@ -#ifndef _ITHREAD_H -#define _ITHREAD_H - -/// @file IThread.h -/// @brief Interface for cross-thread delegate dispatching. -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. - -#include "DelegateMsg.h" - -namespace dmq { - -/// @TODO Implement the IThread interface if necessary. -/// @brief A base class for a delegate enabled execution thread. Implemented by -/// application code if asynchronous delegates are used. -/// -/// @details Each platform specific implementation must inherit from `IThread` -/// and provide an implementation for `DispatchDelegate()`. The `DispatchDelegate()` -/// function is called by the source thread to initiate an asynchronous function call -/// onto the destination thread of control. -class IThread -{ -public: - /// Destructor - virtual ~IThread() = default; - - /// @brief Enqueues a delegate message for execution on this thread. - /// - /// @details - /// This function is called by the *source* thread (the caller). The implementation must - /// thread-safely transfer ownership of the `msg` into the target thread's processing queue. - /// - /// Once the message is received by the target thread's main loop, that loop is responsible - /// for calling `IInvoker::Invoke(msg)` to actually execute the function. - /// - /// @param[in] msg A shared pointer to the delegate message. This pointer must remain valid - /// until the target thread finishes execution. - /// @return true if the message was successfully enqueued, false otherwise. - virtual bool DispatchDelegate(std::shared_ptr msg) = 0; - - /// @brief Returns true if the calling thread is this thread. - /// Used to decide whether to marshal an event or execute inline. - virtual bool IsCurrentThread() = 0; -}; - -/// @brief Registers `thread` as the calling thread's dmq::ThisThread::GetCurrent() -/// for the lifetime of this object, restoring the previous value when destroyed. -/// -/// @details An IThread implementation creates one on its worker thread at the top -/// of its worker loop, so code running there can find the thread it runs on. A -/// custom IThread does the same to be found by GetCurrent(). Does nothing on ports -/// without current-thread storage (GetCurrent() then always returns nullptr). -class CurrentThreadScope -{ -public: - explicit CurrentThreadScope(IThread* thread) noexcept : m_prev(ThisThread::SetCurrent(thread)) {} - ~CurrentThreadScope() { ThisThread::SetCurrent(m_prev); } - - CurrentThreadScope(const CurrentThreadScope&) = delete; - CurrentThreadScope& operator=(const CurrentThreadScope&) = delete; - -private: - IThread* m_prev; -}; - -} - -#endif diff --git a/DelegateMQ/delegate/MulticastDelegate.h b/DelegateMQ/delegate/MulticastDelegate.h deleted file mode 100644 index 2abe74a..0000000 --- a/DelegateMQ/delegate/MulticastDelegate.h +++ /dev/null @@ -1,326 +0,0 @@ -#ifndef _MULTICAST_DELEGATE_H -#define _MULTICAST_DELEGATE_H - -/// @file -/// @brief Delegate container for storing and iterating over a collection of -/// delegate instances. Supports reentrant removal during invocation. -/// Class is not thread-safe. - -#include "Delegate.h" -#include -#include - -DMQ_OPTIMIZE_ON - -namespace dmq { - -template -class MulticastDelegate; // Not defined - -namespace detail { - -/// @brief Clone `delegate` and append it to `delegates`, fully erased to the -/// non-templated `DelegateBase` at construction. `delegate.Clone()` is called -/// through a `const DelegateBase&`, so its return type here is `DelegateBase*` -/// (not the more-derived leaf type) -- the resulting shared_ptr control block -/// is therefore not templated on RetType/Args, and is shared by every -/// `MulticastDelegate` in the program instead of duplicated per signature. -/// Templated only on nothing at all (a plain function): none of this logic -/// depends on the owning container's signature. -/// @param[in,out] delegates The list to append to. -/// @param[in] delegate The delegate to clone and store. -inline void MulticastPushBack(xlist>& delegates, const DelegateBase& delegate) { - auto delegateClone = delegate.Clone(); - if (!delegateClone) - BAD_ALLOC(); - -#if !defined(__cpp_exceptions) || defined(DMQ_ASSERTS) - // No exceptions: Direct execution. - // If shared_ptr or vector allocation fails here on embedded, - // standard behavior is usually an abort() or system reset. - std::shared_ptr sharedDelegate(delegateClone, std::default_delete(), ::dmq::stl_allocator()); - delegates.push_back(std::forward>(sharedDelegate)); -#else - // Exceptions enabled: Safe to try-catch. - try { - std::shared_ptr sharedDelegate(delegateClone, std::default_delete(), ::dmq::stl_allocator()); - delegates.push_back(std::forward>(sharedDelegate)); - } - catch (const std::bad_alloc&) { - BAD_ALLOC(); - } -#endif -} - -/// @brief Remove `delegate` from `delegates`, respecting reentrant removal -/// during an active broadcast. -/// @param[in,out] delegates The list to remove from. -/// @param[in] broadcastCount The owning container's current broadcast nesting depth. -/// @param[out] cleanup Set to `true` if a lazy null-removal is needed later. -/// @param[in] delegate The delegate to remove. -inline void MulticastRemove(xlist>& delegates, int broadcastCount, bool& cleanup, const DelegateBase& delegate) { - auto it = std::find_if(delegates.begin(), delegates.end(), - [&delegate](const std::shared_ptr& item) { - // Must check if item is valid before comparing! - return item && (*item == delegate); - }); - - if (it != delegates.end()) { - if (broadcastCount > 0) { - // REENTRANCY DETECTED: - // Do not erase(). Just null out the pointer. - // The iterator in operator() stays valid, but next access sees null. - it->reset(); - cleanup = true; - } - else { - // Safe to erase immediately - delegates.erase(it); - } - } -} - -/// @brief Remove all delegates from `delegates`, respecting reentrant removal. -inline void MulticastClear(xlist>& delegates, int broadcastCount, bool& cleanup) { - if (broadcastCount > 0) { - for (auto& delegate : delegates) { - delegate.reset(); - } - cleanup = true; - } - else { - delegates.clear(); - } -} - -/// @brief Deep-copy every delegate in `src` (cloned, fully erased to -/// `DelegateBase`) into `dest`. -inline void MulticastCopyFrom(xlist>& dest, const xlist>& src) { - for (auto& delegate : src) { - if (!delegate) continue; - auto delegateClone = delegate->Clone(); - if (!delegateClone) - BAD_ALLOC(); - -#if !defined(__cpp_exceptions) || defined(DMQ_ASSERTS) - // No exceptions: Direct execution. - std::shared_ptr sharedDelegate(delegateClone, std::default_delete(), ::dmq::stl_allocator()); - dest.push_back(sharedDelegate); -#else - // Exceptions enabled: Safe to try-catch. - try { - std::shared_ptr sharedDelegate(delegateClone, std::default_delete(), ::dmq::stl_allocator()); - dest.push_back(sharedDelegate); - } - catch (const std::bad_alloc&) { - BAD_ALLOC(); - } -#endif - } -} - -/// @brief Move every element of `src` onto the end of `dest`, then clear `src`. -/// Used by the reentrant branch of move-assignment, which must keep `dest`'s -/// own list object identity stable (an active broadcast's iterator into it may -/// be live) rather than replacing it outright. -inline void MulticastAppendAndClear(xlist>& dest, xlist>& src) { - for (auto& delegate : src) { - dest.push_back(std::move(delegate)); - } - src.clear(); -} - -/// @brief RAII guard marking an active broadcast. Increments `cnt` on -/// construction, decrements on destruction, and purges lazily-nulled entries -/// from `delegates` once the outermost nested broadcast finishes. Takes plain -/// references to the exact fields it needs rather than a container pointer, -/// so it carries no dependency on RetType/Args at all. -class BroadcastGuard { -public: - BroadcastGuard(int& cnt, xlist>& delegates, bool& cleanup) - : m_cnt(cnt), m_delegates(delegates), m_cleanup(cleanup) { - m_cnt++; // Lock - } - ~BroadcastGuard() { - m_cnt--; // Unlock - if (m_cnt == 0 && m_cleanup) { - // Efficiently remove all null pointers from the list - m_delegates.remove_if([](const std::shared_ptr& item) { - return item == nullptr; - }); - m_cleanup = false; - } - } -private: - int& m_cnt; - xlist>& m_delegates; - bool& m_cleanup; -}; - -} // namespace detail - -/// @brief Not thread-safe multicast delegate container class. The class has a list of -/// `Delegate<>` instances. When invoked, each `Delegate` instance within the invocation -/// list is called. The broadcast iterates over the live list; if a delegate is removed -/// during a broadcast, its current execution finishes safely but it is removed from the list. -/// If a new delegate is added during a broadcast, it may be invoked in the current pass. -/// @note The subscriber list is stored as `shared_ptr` rather than -/// `shared_ptr>` so that `xlist`'s instantiation (and all its -/// member functions) is shared across every `MulticastDelegate` in the program instead -/// of being duplicated once per signature. The bookkeeping operations on that list -/// (`PushBack`/`Remove`/`Clear`/copy/the broadcast-nesting guard) are likewise implemented as -/// plain, non-templated `detail::Multicast*` functions/`detail::BroadcastGuard` above, for the -/// same reason -- their bodies never touch `RetType`/`Args` either. Only `operator()`, which -/// must actually invoke the bound function, needs the concrete `DelegateType` back. -template -class MulticastDelegate -{ -public: - using DelegateType = Delegate; - - MulticastDelegate() = default; - virtual ~MulticastDelegate() { Clear(); } - - /// @brief Copy constructor that creates a copy of the given instance. - /// @details This constructor initializes a new object as a copy of the - /// provided `rhs` (right-hand side) object. The `rhs` object is used to - /// set the state of the new instance. - /// @param[in] rhs The object to copy from. - MulticastDelegate(const MulticastDelegate& rhs) { detail::MulticastCopyFrom(m_delegates, rhs.m_delegates); } - - /// @brief Move constructor that transfers ownership of resources. - /// @param[in] rhs The object to move from. - MulticastDelegate(MulticastDelegate&& rhs) noexcept : m_delegates(std::move(rhs.m_delegates)) { } - - /// Constructor to initialize from a single Delegate (Copy) - MulticastDelegate(const DelegateType& d) { - PushBack(d); - } - - /// Constructor to initialize from a single Delegate (Move) - MulticastDelegate(DelegateType&& d) { - PushBack(d); - } - - /// Invoke all bound target functions. Safe to remove delegates during invocation. - /// A void return value is used since multiple targets invoked. - /// @param[in] args The arguments used when invoking the target functions - void operator()(Args... args) { - // RAII Guard: Increments now, Decrements + Cleans up on return/throw - detail::BroadcastGuard guard(m_broadcastCount, m_delegates, m_cleanup); - - // Iterate safely - for (auto it = m_delegates.begin(); it != m_delegates.end(); ++it) { - std::shared_ptr delegate = *it; // Copy to prevent UAF if removed mid-invocation - if (delegate) { - (*static_cast(delegate.get()))(args...); - } - } - } - - /// Invoke all bound target functions. A void return value is used - /// since multiple targets invoked. - /// @param[in] args The arguments used when invoking the target functions - void Broadcast(Args... args) { - (*this)(args...); - } - - /// Insert a delegate into the container. - /// @param[in] delegate A delegate target to insert - void operator+=(const DelegateType& delegate) { PushBack(delegate); } - - /// Insert a delegate into the container. - /// @param[in] delegate A delegate target to insert - void operator+=(DelegateType&& delegate) { PushBack(delegate); } - - /// Remove a delegate from the container. - /// @param[in] delegate A delegate target to remove - void operator-=(const DelegateType& delegate) { Remove(delegate); } - - /// Remove a delegate from the container. - /// @param[in] delegate A delegate target to remove - void operator-=(DelegateType&& delegate) { Remove(delegate); } - - /// @brief Assignment operator that assigns the state of one object to another. - /// @param[in] rhs The object whose state is to be assigned to the current object. - /// @return A reference to the current object. - MulticastDelegate& operator=(const MulticastDelegate& rhs) { - if (&rhs != this) { - Clear(); - detail::MulticastCopyFrom(m_delegates, rhs.m_delegates); - } - return *this; - } - - /// @brief Move assignment operator that transfers ownership of resources. - /// @param[in] rhs The object to move from. - /// @return A reference to the current object. - MulticastDelegate& operator=(MulticastDelegate&& rhs) noexcept { - if (&rhs != this) { - if (m_broadcastCount > 0) { - // Reentrant: a callback is reassigning the container it's currently - // broadcasting from. Clear() only nulls existing entries in this case, - // leaving m_delegates itself intact so the active iterator in operator() - // stays valid. Append rhs's delegates rather than replacing the - // container outright; stale nulls are purged after the broadcast ends. - Clear(); - detail::MulticastAppendAndClear(m_delegates, rhs.m_delegates); - } - else { - Clear(); - m_delegates = std::move(rhs.m_delegates); - } - } - return *this; - } - - /// @brief Clear the all target functions. - virtual void operator=(std::nullptr_t) noexcept { Clear(); } - - /// Insert a delegate into the container. - /// @param[in] delegate A delegate target to insert - void PushBack(const DelegateType& delegate) { - detail::MulticastPushBack(m_delegates, delegate); - } - - /// Remove a delegate into the container. - /// @param[in] delegate The delegate target to remove. - void Remove(const DelegateType& delegate) { - detail::MulticastRemove(m_delegates, m_broadcastCount, m_cleanup, delegate); - } - - /// Any registered delegates? - /// @return `true` if delegate container is empty. - bool Empty() const { return m_delegates.empty(); } - - /// Removal all registered delegates. - void Clear() { - detail::MulticastClear(m_delegates, m_broadcastCount, m_cleanup); - } - - /// Get the number of delegates stored. - /// @return The number of delegates stored. - std::size_t Size() const { return m_delegates.size(); } - - /// @brief Implicit conversion operator to `bool`. - /// @return `true` if the container is not empty, `false` if the container is empty. - explicit operator bool() const { return !Empty(); } - -protected: - /// List of registered delegates. Stored as `DelegateBase` (not `DelegateType`) so this - /// `xlist` instantiation, and every member function on it, is shared across all - /// `MulticastDelegate` signatures instead of being duplicated per signature. - xlist> m_delegates; - - /// Count of active nested broadcasts - int m_broadcastCount = 0; - - /// Flag for handling lazy delete - bool m_cleanup = false; -}; - -} - -DMQ_OPTIMIZE_OFF - -#endif diff --git a/DelegateMQ/delegate/MulticastDelegateSafe.h b/DelegateMQ/delegate/MulticastDelegateSafe.h deleted file mode 100644 index 3643b0b..0000000 --- a/DelegateMQ/delegate/MulticastDelegateSafe.h +++ /dev/null @@ -1,248 +0,0 @@ -#ifndef _MULTICAST_DELEGATE_SAFE_H -#define _MULTICAST_DELEGATE_SAFE_H - -/// @file -/// @brief Delegate container for storing and iterating over a collection of -/// delegate instances. Class is thread-safe. -/// -/// @note Invocation snapshots the delegates and calls them after releasing the -/// lock, so a delegate removed on one thread may still be called once by an -/// invocation already in progress on another. Removal does not make the target -/// safe to destroy by itself; see the note in Signal.h. - -#include "MulticastDelegate.h" -#include -#include - -DMQ_OPTIMIZE_ON - -namespace dmq { - -template -class MulticastDelegateSafe; // Not defined - -namespace detail { - -/// @brief Lock-protected wrapper around `MulticastPushBack` (MulticastDelegate.h). -/// Non-templated: none of this depends on the owning container's signature. -inline void MulticastSafePushBack(xlist>& delegates, RecursiveMutex& lock, const DelegateBase& delegate) { - const dmq::LockGuard g(lock); - MulticastPushBack(delegates, delegate); -} - -/// @brief Lock-protected wrapper around `MulticastRemove`. -inline void MulticastSafeRemove(xlist>& delegates, int broadcastCount, bool& cleanup, RecursiveMutex& lock, const DelegateBase& delegate) { - const dmq::LockGuard g(lock); - MulticastRemove(delegates, broadcastCount, cleanup, delegate); -} - -/// @brief Lock-protected wrapper around `MulticastClear`. -inline void MulticastSafeClear(xlist>& delegates, int broadcastCount, bool& cleanup, RecursiveMutex& lock) { - const dmq::LockGuard g(lock); - MulticastClear(delegates, broadcastCount, cleanup); -} - -/// @brief Lock-protected emptiness check. -inline bool MulticastSafeEmpty(const xlist>& delegates, RecursiveMutex& lock) { - const dmq::LockGuard g(lock); - return delegates.empty(); -} - -/// @brief Lock-protected size check. -inline size_t MulticastSafeSize(const xlist>& delegates, RecursiveMutex& lock) { - const dmq::LockGuard g(lock); - return delegates.size(); -} - -/// @brief Snapshot the current delegate list under lock, into `smallBuf` (up to -/// `smallCap` entries) or `largeBuf` if there are more than `smallCap`. Returns -/// the number of delegates snapshotted. The lock is released before returning, -/// so the caller can invoke each delegate without holding it (see the comment -/// on `MulticastDelegateSafe::operator()` for why). Non-templated: entirely -/// independent of the owning container's signature. -inline size_t MulticastSafeSnapshot(xlist>& delegates, RecursiveMutex& lock, - std::shared_ptr* smallBuf, size_t smallCap, xlist>& largeBuf) { - const dmq::LockGuard g(lock); - size_t count = delegates.size(); - if (count <= smallCap) { - std::copy(delegates.begin(), delegates.end(), smallBuf); - } else { - largeBuf = delegates; - } - return count; -} - -} // namespace detail - -/// @brief Thread-safe multicast delegate container class. -template -class MulticastDelegateSafe : public MulticastDelegate -{ -public: - using DelegateType = Delegate; - using BaseType = MulticastDelegate; - - MulticastDelegateSafe() = default; - virtual ~MulticastDelegateSafe() = default; - - MulticastDelegateSafe(const MulticastDelegateSafe& rhs) : BaseType() { - dmq::ScopedLock lock(m_lock, rhs.m_lock); - BaseType::operator=(rhs); - } - - MulticastDelegateSafe(MulticastDelegateSafe&& rhs) : BaseType() { - dmq::ScopedLock lock(m_lock, rhs.m_lock); - BaseType::operator=(std::move(rhs)); - } - - /// Constructor to initialize from a single Delegate (Copy) - MulticastDelegateSafe(const DelegateType& d) { - this->PushBack(d); - } - - /// Constructor to initialize from a single Delegate (Move) - MulticastDelegateSafe(DelegateType&& d) { - this->PushBack(std::move(d)); - } - - /// Invoke the bound target function for all stored delegate instances. - /// A void return value is used since multiple targets invoked. - /// @param[in] args The arguments used when invoking the target functions - void operator()(Args... args) { - // To prevent deadlocks, the mutex must be released before invoking the - // delegate. Circular lock dependencies can occur if the delegate target - // function itself attempts to acquire a lock that is held by the - // thread invoking the delegate. - // Use a small-buffer optimization to avoid heap allocation in the common case. - // Buffers hold `DelegateBase` (not `DelegateType`) so this `xlist` instantiation - // is shared across every `MulticastDelegateSafe` signature; only the final - // invoke below needs the concrete `DelegateType` back. The snapshot-under-lock - // logic itself lives in `detail::MulticastSafeSnapshot` for the same reason. - std::array, SIGNAL_SBO_COUNT> small_buf; - xlist> large_buf; - size_t count = detail::MulticastSafeSnapshot(this->m_delegates, m_lock, small_buf.data(), SIGNAL_SBO_COUNT, large_buf); - - if (count <= SIGNAL_SBO_COUNT) { - for (size_t i = 0; i < count; ++i) { - if (small_buf[i]) - (*static_cast(small_buf[i].get()))(args...); - small_buf[i].reset(); // Clear to release shared_ptr immediately - } - } else { - for (auto& d : large_buf) { - if (d) - (*static_cast(d.get()))(args...); - } - } - } - - /// Invoke all bound target functions. A void return value is used - /// since multiple targets invoked. - /// @param[in] args The arguments used when invoking the target functions - void Broadcast(Args... args) { - operator()(args...); - } - - /// Insert a delegate into the container. - /// @param[in] delegate A delegate target to insert - void operator+=(const Delegate& delegate) { - const dmq::LockGuard lock(m_lock); - BaseType::operator +=(delegate); - } - - /// Insert a delegate into the container. - /// @param[in] delegate A delegate target to insert - void operator+=(Delegate&& delegate) { - const dmq::LockGuard lock(m_lock); - BaseType::operator +=(delegate); - } - - /// Remove a delegate from the container. - /// @param[in] delegate A delegate target to remove - void operator-=(const Delegate& delegate) { - const dmq::LockGuard lock(m_lock); - BaseType::operator -=(delegate); - } - - /// Remove a delegate from the container. - /// @param[in] delegate A delegate target to remove - void operator-=(Delegate&& delegate) { - const dmq::LockGuard lock(m_lock); - BaseType::operator -=(delegate); - } - - /// @brief Assignment operator that assigns the state of one object to another. - /// @param[in] rhs The object whose state is to be assigned to the current object. - /// @return A reference to the current object. - MulticastDelegateSafe& operator=(const MulticastDelegateSafe& rhs) { - if (this != &rhs) { - // Lock both instances safely to prevent modification of source during copy - dmq::ScopedLock lock(m_lock, rhs.m_lock); - BaseType::operator=(rhs); - } - return *this; - } - - /// @brief Move assignment operator that transfers ownership of resources. - /// @param[in] rhs The object to move from. - /// @return A reference to the current object. - MulticastDelegateSafe& operator=(MulticastDelegateSafe&& rhs) noexcept { - if (this != &rhs) { - dmq::ScopedLock lock(m_lock, rhs.m_lock); - BaseType::operator=(std::move(rhs)); - } - return *this; - } - - /// @brief Clear the all target functions. - virtual void operator=(std::nullptr_t) noexcept { - const dmq::LockGuard lock(m_lock); - BaseType::Clear(); - } - - /// Insert a delegate into the container. - /// @param[in] delegate A delegate target to insert - void PushBack(const DelegateType& delegate) { - detail::MulticastSafePushBack(this->m_delegates, m_lock, delegate); - } - - /// Remove a delegate into the container. - /// @param[in] delegate The delegate target to remove. - void Remove(const DelegateType& delegate) { - detail::MulticastSafeRemove(this->m_delegates, this->m_broadcastCount, this->m_cleanup, m_lock, delegate); - } - - /// Any registered delegates? - /// @return `true` if delegate container is empty. - bool Empty() const { - return detail::MulticastSafeEmpty(this->m_delegates, m_lock); - } - - /// Removal all registered delegates. - void Clear() { - detail::MulticastSafeClear(this->m_delegates, this->m_broadcastCount, this->m_cleanup, m_lock); - } - - /// Get the number of delegates stored. - /// @return The number of delegates stored. - std::size_t Size() const { - return detail::MulticastSafeSize(this->m_delegates, m_lock); - } - - /// @brief Implicit conversion operator to `bool`. - /// @return `true` if the container is not empty, `false` if the container is empty. - explicit operator bool() const { - const dmq::LockGuard lock(m_lock); - return BaseType::operator bool(); - } - -private: - /// Lock to make the class thread-safe - mutable RecursiveMutex m_lock; -}; - -} - -DMQ_OPTIMIZE_OFF - -#endif diff --git a/DelegateMQ/delegate/Semaphore.h b/DelegateMQ/delegate/Semaphore.h deleted file mode 100644 index ee1c4a9..0000000 --- a/DelegateMQ/delegate/Semaphore.h +++ /dev/null @@ -1,89 +0,0 @@ -#ifndef _DELEGATE_SEMAPHORE_H -#define _DELEGATE_SEMAPHORE_H - -/// @file -/// @brief Delegate library semaphore wrapper class. -/// -/// dmq::Semaphore is available (DMQ_HAS_SEMAPHORE) on every port except -/// bare metal. On stdlib/Win32/Qt, FreeRTOS, and ThreadX (DMQ_HAS_CV -- -/// these have a real dmq::ConditionVariable) it's the generic class -/// defined below, built from dmq::ConditionVariable + dmq::Mutex. On -/// Zephyr and CMSIS-RTOS2 (no ConditionVariable port) DelegateOpt.h -/// already resolves dmq::Semaphore to a port-native implementation -/// instead (ZephyrSemaphore / CmsisRtos2Semaphore) -- nothing more to -/// define here for those two. - -#include "DelegateOpt.h" - -#ifdef DMQ_HAS_SEMAPHORE - -// Fix compiler error on Windows -#undef max - -#ifdef DMQ_HAS_CV - -namespace dmq { - -/// @brief A semaphore wrapper class. -class Semaphore -{ -public: - Semaphore() = default; - ~Semaphore() = default; - - /// Called to wait on a semaphore to be signaled. - /// @param[in] timeout - semaphore timeout - /// @return Return true if semaphore signaled, false if timeout occurred. - bool Wait(Duration timeout) - { - dmq::UniqueLock lk(m_lock); - if (timeout == Duration::max()) - { - m_sema.wait(lk, [this] { return m_signaled; }); - } - else - { - if (!m_sema.wait_for(lk, timeout, [this] { return m_signaled; })) - { - return false; // Timeout occurred - } - } - - if (m_signaled) - { - m_signaled = false; - return true; - } - else - { - return false; - } - } - - /// Called to signal a semaphore. - void Signal() - { - { - dmq::UniqueLock lk(m_lock); - m_signaled = true; - } - m_sema.notify_one(); - } - -private: - // Prevent copying objects - Semaphore(const Semaphore&) = delete; - Semaphore& operator=(const Semaphore&) = delete; - - dmq::ConditionVariable m_sema; - dmq::Mutex m_lock; - bool m_signaled = false; -}; - -} - -#endif // DMQ_HAS_CV - -#endif // DMQ_HAS_SEMAPHORE - -#endif diff --git a/DelegateMQ/delegate/Signal.h b/DelegateMQ/delegate/Signal.h deleted file mode 100644 index 09b6fab..0000000 --- a/DelegateMQ/delegate/Signal.h +++ /dev/null @@ -1,395 +0,0 @@ -#ifndef SIGNAL_H -#define SIGNAL_H - -/// @file Signal.h -/// @brief Thread-safe Signal/slot with RAII connection handles; no allocation requirement. -/// -/// @details `Signal` is a thread-safe multicast delegate container that returns RAII -/// `ScopedConnection` handles from `Connect()`. Key properties: -/// -/// * **No allocation requirement** — Signal may live on the stack, as a class member, or on -/// the heap without restriction. -/// * **Thread-safe** — concurrent Connect/Disconnect/operator() calls are all safe. -/// * **Lifetime-safe disconnect** — calling `Disconnect()` (or letting a `ScopedConnection` -/// go out of scope) after the Signal is destroyed is always a safe no-op. -/// -/// **A slot can still run after `Disconnect()` returns.** Disconnect removes the slot from -/// the list, but it does not wait for a call that has already started: `operator()` takes -/// a snapshot of the slots under the lock and invokes them after releasing it (so a slot may -/// itself Connect/Disconnect/emit without deadlocking). If thread A is emitting while -/// thread B disconnects, A can still invoke the slot once, after B's `Disconnect()` has -/// returned. Separately, for an asynchronous delegate (`MakeDelegate(..., thread)`), a -/// message already queued on the target thread still runs after the disconnect. -/// -/// So when Signal is used across threads, disconnecting is not by itself enough to make -/// the slot's target safe to destroy. The owner must also guard its own lifetime, for -/// example: route the slot through a shared flag/mutex it closes before destruction (the -/// slot checks it under the lock and returns if closed), and for async delegates drain or -/// exit the target thread (`ExitThread()`) before destroying what its messages target. -/// Single-threaded use (connect, emit and disconnect on one thread) needs none of this. -/// -/// Internally, Signal stores its subscriber list in a heap-allocated `State` block. Each -/// `Connection` holds two `shared_ptr` context fields (state and delegate copy) plus -/// a raw `DisconnectImpl` function pointer. The destructor marks the block dead under the -/// mutex, so any concurrent disconnect that races with destruction simply sees the dead flag -/// and returns without touching the list. - -#include "DelegateOpt.h" -#include "Delegate.h" -#include -#include - -DMQ_OPTIMIZE_ON - -namespace dmq { - -template -class UnicastDelegate; - -template -class Signal; - -// --------------------------------------------------------------------------- -// detail::Connection (implementation detail — use ScopedConnection) -// --------------------------------------------------------------------------- -namespace detail { - -/// @brief Move-only subscription token. Internal implementation detail of Signal. -/// Users should store `ScopedConnection`, not `Connection` directly. -/// -/// Stores two type-erased `shared_ptr` contexts (signal state and delegate copy) -/// plus a raw `DisconnectFn` function pointer. No `std::function` heap allocation. -class Connection { -public: - using DisconnectFn = void(*)(const std::shared_ptr&, const std::shared_ptr&); - - Connection() = default; - - Connection(std::shared_ptr ctx1, std::shared_ptr ctx2, DisconnectFn fn) noexcept - : m_ctx1(std::move(ctx1)) - , m_ctx2(std::move(ctx2)) - , m_disconnect_fn(fn) - , m_connected(true) {} - - Connection(const Connection&) = delete; - Connection& operator=(const Connection&) = delete; - - Connection(Connection&& other) noexcept - : m_ctx1(std::move(other.m_ctx1)) - , m_ctx2(std::move(other.m_ctx2)) - , m_disconnect_fn(other.m_disconnect_fn) - , m_connected(other.m_connected) { - other.m_connected = false; - other.m_disconnect_fn = nullptr; - } - - Connection& operator=(Connection&& other) noexcept { - if (this != &other) { - Disconnect(); - m_ctx1 = std::move(other.m_ctx1); - m_ctx2 = std::move(other.m_ctx2); - m_disconnect_fn = other.m_disconnect_fn; - m_connected = other.m_connected; - other.m_connected = false; - other.m_disconnect_fn = nullptr; - } - return *this; - } - - ~Connection() {} - - bool IsConnected() const { return m_connected; } - - void Disconnect() { - if (!m_connected) return; - if (m_disconnect_fn) - m_disconnect_fn(m_ctx1, m_ctx2); - m_ctx1.reset(); - m_ctx2.reset(); - m_disconnect_fn = nullptr; - m_connected = false; - } - -private: - std::shared_ptr m_ctx1; - std::shared_ptr m_ctx2; - DisconnectFn m_disconnect_fn = nullptr; - bool m_connected = false; - XALLOCATOR -}; - -} // namespace detail - -// --------------------------------------------------------------------------- -// ScopedConnection -// --------------------------------------------------------------------------- - -/// @brief RAII handle to a single Signal subscription. Disconnects automatically -/// on destruction. The only connection type users need to store. -/// -/// @note Disconnecting does not wait for a call already in progress on another -/// thread, or for an async delegate message already queued; see the Signal.h file -/// comment before destroying a slot's target right after disconnecting. -/// -/// @code -/// dmq::ScopedConnection conn = mySignal.Connect(MakeDelegate(...)); -/// // conn goes out of scope -> automatically disconnected -/// @endcode -class ScopedConnection { -public: - ScopedConnection() = default; - explicit ScopedConnection(detail::Connection&& conn) : m_connection(std::move(conn)) {} - ~ScopedConnection() { m_connection.Disconnect(); } - - ScopedConnection(ScopedConnection&& other) noexcept - : m_connection(std::move(other.m_connection)) {} - - ScopedConnection& operator=(ScopedConnection&& other) noexcept { - if (this != &other) { - m_connection.Disconnect(); - m_connection = std::move(other.m_connection); - } - return *this; - } - - ScopedConnection(const ScopedConnection&) = delete; - ScopedConnection& operator=(const ScopedConnection&) = delete; - - void Disconnect() { m_connection.Disconnect(); } - bool IsConnected() const { return m_connection.IsConnected(); } - -private: - detail::Connection m_connection; - XALLOCATOR -}; - -// --------------------------------------------------------------------------- -// detail::Signal* helpers (implementation detail of Signal, defined here so -// they can construct/return ScopedConnection) -// --------------------------------------------------------------------------- -namespace detail { - -/// @brief Non-templated: the mutex + alive-flag + delegate list shared by every -/// `Signal` in the program. Hoisted out of `Signal` (where it lived as -/// a nested `State` struct) because nesting inside the class template caused a -/// separate (byte-identical) type -- and critically a separate `xmake_shared` -/// allocation control block -- to be generated per signature, even though none -/// of its members depend on RetType/Args. -struct SignalState { - mutable RecursiveMutex mtx; - bool alive = true; - xlist> delegates; - XALLOCATOR -}; - -/// @brief Non-templated: a snapshot of a signal's subscriber list at a point in -/// time, captured under lock so `operator()` can invoke without holding it. -struct SignalSnapshot { - std::array, SIGNAL_SBO_COUNT> small_buf; - xlist> large_buf; - size_t count = 0; -}; - -/// @brief Identity-based disconnect: removes `copyVoid` (the exact shared_ptr -/// instance stored at Connect() time) from `stateVoid`'s delegate list, if the -/// state is still alive. Non-templated: this never needed the concrete -/// `DelegateType` to begin with, but as a member of `Signal` it used to be -/// emitted once per signature anyway. -inline void SignalDisconnectImpl(const std::shared_ptr& stateVoid, const std::shared_ptr& copyVoid) { - auto* state = static_cast(stateVoid.get()); - auto copy = std::static_pointer_cast(copyVoid); - dmq::LockGuard lock(state->mtx); - if (state->alive) - state->delegates.remove(copy); -} - -/// @brief Clone `delegate` and append it to `state`'s list under lock, returning -/// a connection handle wired to `SignalDisconnectImpl`. `delegate` is taken as -/// `const DelegateBase&` (rather than the more-derived `Delegate&`) so -/// `delegate.Clone()`'s return type here is `DelegateBase*` -- the resulting -/// shared_ptr control block is therefore not templated on RetType/Args, and is -/// shared by every `Signal` in the program instead of duplicated per -/// signature (mirrors the fix already applied to `MulticastDelegate::PushBack`). -inline ScopedConnection SignalConnect(std::shared_ptr& state, RecursiveMutex& mutex, const DelegateBase& delegate) { - auto copy = std::shared_ptr(delegate.Clone(), std::default_delete(), ::dmq::stl_allocator()); - if (!copy) - BAD_ALLOC(); - - dmq::LockGuard lock(mutex); - dmq::LockGuard stateLock(state->mtx); - state->delegates.push_back(copy); - - return ScopedConnection(Connection( - std::static_pointer_cast(state), - std::static_pointer_cast(copy), - &SignalDisconnectImpl - )); -} - -/// @brief Capture a snapshot of `state`'s current delegate list under lock. -inline SignalSnapshot SignalGetSnapshot(const std::shared_ptr& state, RecursiveMutex& mutex) { - dmq::LockGuard lock(mutex); - dmq::LockGuard stateLock(state->mtx); - - SignalSnapshot s; - s.count = state->delegates.size(); - if (s.count <= SIGNAL_SBO_COUNT) { - size_t i = 0; - for (auto& d : state->delegates) { -#if defined(__clang__) -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wunsafe-buffer-usage" -#endif - s.small_buf[i++] = d; -#if defined(__clang__) -#pragma clang diagnostic pop -#endif - } - } else { - s.large_buf = state->delegates; - } - return s; -} - -/// @brief Disconnect all subscribers: swap in a fresh `SignalState`, mark the -/// old one dead+cleared under its own lock. Used by `Signal::Clear()`. -inline void SignalClear(std::shared_ptr& state, RecursiveMutex& mutex) { - std::shared_ptr oldState; - { - dmq::LockGuard lock(mutex); - oldState = state; - state = xmake_shared(); - } - { - dmq::LockGuard lock(oldState->mtx); - oldState->alive = false; - oldState->delegates.clear(); - } -} - -/// @brief Mark `state` dead and clear its list under lock. Used by `~Signal()` -/// -- unlike `SignalClear`, does not swap in a replacement state, since the -/// owning Signal is being destroyed rather than reset for reuse. -inline void SignalMarkDead(std::shared_ptr& state, RecursiveMutex& mutex) { - dmq::LockGuard lock(mutex); - dmq::LockGuard stateLock(state->mtx); - state->alive = false; - state->delegates.clear(); -} - -/// @brief Lock-protected subscriber count. -inline size_t SignalSize(const std::shared_ptr& state, RecursiveMutex& mutex) { - dmq::LockGuard lock(mutex); - dmq::LockGuard stateLock(state->mtx); - return state->delegates.size(); -} - -} // namespace detail - -// --------------------------------------------------------------------------- -// Signal -// --------------------------------------------------------------------------- - -/// @brief Thread-safe multicast delegate returning RAII connection handles. -/// @details May be instantiated on the stack, as a class member, or on the heap. -/// `Signal` is the single signal type in the library. -template -class Signal -{ -public: - using DelegateType = Delegate; - - /// @brief Snapshot of the subscriber list at a point in time. Alias for the - /// non-templated `detail::SignalSnapshot` -- kept as a nested name here since - /// external code (e.g. `extras/util/Timer.cpp`) names it as `Signal::Snapshot`. - using Snapshot = detail::SignalSnapshot; - - Signal() = default; - - ~Signal() { - // Mark the shared state dead under the lock. Any concurrent Disconnect() - // that races with this will either complete its removal first (holding the - // lock) or see alive=false and skip removal. Either way, no UAF. - detail::SignalMarkDead(m_state, m_mutex); - } - - Signal(const Signal&) = delete; - Signal& operator=(const Signal&) = delete; - Signal(Signal&&) = delete; - Signal& operator=(Signal&&) = delete; - - /// @brief Subscribe a delegate and return a RAII connection handle. - /// @details The returned `ScopedConnection` automatically disconnects on - /// scope exit. Safe to call regardless of how the Signal was allocated. - /// @return A `ScopedConnection`. Let it go out of scope to auto-disconnect, - /// or call `Disconnect()` manually. - [[nodiscard]] ScopedConnection Connect(const DelegateType& delegate) { - return detail::SignalConnect(m_state, m_mutex, delegate); - } - - /// @brief Subscribe a UnicastDelegate and return a RAII connection handle. - [[nodiscard]] ScopedConnection Connect(const UnicastDelegate& delegate) { - if (delegate.GetDelegate()) - return Connect(*delegate.GetDelegate()); - return {}; - } - - /// @brief Invoke all connected delegates. - void operator()(Args... args) { - auto snapshot = GetSnapshot(); - InvokeSnapshot(snapshot, std::forward(args)...); - } - - /// @brief Capture a snapshot of all current subscribers. - /// @details The snapshot holds shared_ptrs to the delegates, ensuring they - /// stay alive even if the Signal is destroyed. - Snapshot GetSnapshot() const { - return detail::SignalGetSnapshot(m_state, m_mutex); - } - - /// @brief Invoke a previously captured snapshot of delegates. - static void InvokeSnapshot(const Snapshot& s, Args... args) { - if (s.count <= SIGNAL_SBO_COUNT) { - for (size_t i = 0; i < s.count; ++i) { -#if defined(__clang__) -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wunsafe-buffer-usage" -#endif - if (s.small_buf[i]) - (*static_cast(s.small_buf[i].get()))(args...); -#if defined(__clang__) -#pragma clang diagnostic pop -#endif - } - } else { - for (auto& d : s.large_buf) { - if (d) - (*static_cast(d.get()))(args...); - } - } - } - - /// @brief Number of currently connected subscribers. - std::size_t Size() const { - return detail::SignalSize(m_state, m_mutex); - } - - bool Empty() const { return Size() == 0; } - - /// @brief Disconnect all subscribers. - void Clear() { - detail::SignalClear(m_state, m_mutex); - } - - XALLOCATOR - -private: - mutable RecursiveMutex m_mutex; - std::shared_ptr m_state = xmake_shared(); -}; - -} // namespace dmq - -DMQ_OPTIMIZE_OFF - -#endif // SIGNAL_H diff --git a/DelegateMQ/delegate/UnicastDelegate.h b/DelegateMQ/delegate/UnicastDelegate.h deleted file mode 100644 index 2f5a4dd..0000000 --- a/DelegateMQ/delegate/UnicastDelegate.h +++ /dev/null @@ -1,155 +0,0 @@ -#ifndef _UNICAST_DELEGATE_H -#define _UNICAST_DELEGATE_H - -/// @file -/// @brief Delegate container for storing an invoking a single delegate instance. -/// Class is not thread-safe. - -#include "Delegate.h" -#include - -DMQ_OPTIMIZE_ON - -namespace dmq { - -template -class UnicastDelegate; // Not defined - -namespace detail { - -/// @brief Clone `delegate` and wrap it in a shared_ptr, fully erased to the -/// non-templated `DelegateBase` at construction. `delegate.Clone()` is called -/// through a `const DelegateBase&`, so its return type here is `DelegateBase*` -/// -- the resulting shared_ptr control block is therefore not templated on -/// RetType/Args, and is shared by every `UnicastDelegate` in the program -/// instead of duplicated per signature. Non-templated: none of this logic -/// depends on the owning container's signature. -inline std::shared_ptr UnicastClone(const DelegateBase& delegate) { - auto delegateClone = delegate.Clone(); - if (!delegateClone) - BAD_ALLOC(); - return std::shared_ptr(delegateClone, std::default_delete(), ::dmq::stl_allocator()); -} - -} // namespace detail - -/// @brief A non-thread-safe delegate container storing one delegate. Void and -/// non-void return values supported. -template -class UnicastDelegate -{ -public: - using DelegateType = Delegate; - - UnicastDelegate() = default; - virtual ~UnicastDelegate() { Clear(); } - - /// @brief Copy constructor that creates a copy of the given instance. - /// @details This constructor initializes a new object as a copy of the - /// provided `rhs` (right-hand side) object. The `rhs` object is used to - /// set the state of the new instance. - /// @param[in] rhs The object to copy from. - UnicastDelegate(const UnicastDelegate& rhs) { - if (rhs.m_delegate) - m_delegate = detail::UnicastClone(*rhs.m_delegate); - } - - /// Move constructor that transfers ownership of resources. - /// @param[in] rhs The object to move from. - UnicastDelegate(UnicastDelegate&& rhs) noexcept : m_delegate(std::move(rhs.m_delegate)) { } - - /// Constructor to initialize from a Delegate (Copy) - UnicastDelegate(const DelegateType& d) { - *this = d; - } - - /// Constructor to initialize from a Delegate (Move) - UnicastDelegate(DelegateType&& d) { - *this = std::move(d); - } - - - /// Invoke the bound target. - /// @param[in] args The arguments used when invoking the target function - /// @return The target function return value. - RetType operator()(Args... args) const { - if (m_delegate) - return (*static_cast(m_delegate.get()))(args...); // Invoke delegate callback - else - return RetType(); - } - - /// Invoke the bound target functions. - /// @param[in] args The arguments used when invoking the target function - void Broadcast(Args... args) const { - (*this)(args...); - } - - /// Assign a delegate to the container. - /// @param[in] rhs A delegate target to assign - void operator=(const DelegateType& rhs) { - m_delegate = detail::UnicastClone(rhs); - } - - /// Assign a delegate to the container. - /// @param[in] rhs A delegate target to assign - void operator=(DelegateType&& rhs) { - // Clone() even on rvalue: no move API exists across the polymorphic delegate hierarchy. - m_delegate = detail::UnicastClone(rhs); - } - - /// @brief Assignment operator that assigns the state of one object to another. - /// @param[in] rhs The object whose state is to be assigned to the current object. - /// @return A reference to the current object. - UnicastDelegate& operator=(const UnicastDelegate& rhs) { - if (this != &rhs) { - m_delegate = rhs.m_delegate ? detail::UnicastClone(*rhs.m_delegate) : nullptr; - } - return *this; - } - - /// @brief Move assignment operator that transfers ownership of resources. - /// @param[in] rhs The object to move from. - /// @return A reference to the current object. - UnicastDelegate& operator=(UnicastDelegate&& rhs) noexcept { - if (this != &rhs) { - m_delegate = std::move(rhs.m_delegate); - } - return *this; - } - - /// @brief Clear the all target functions. - virtual void operator=(std::nullptr_t) noexcept { Clear(); } - - /// Any registered delegates? - /// @return `true` if delegate container is empty. - bool Empty() const { return !m_delegate; } - - /// Remove the registered delegate - void Clear() { m_delegate = nullptr; } - - /// Get the number of delegates stored. - /// @return The number of delegates stored. - std::size_t Size() const { return m_delegate == nullptr ? 0 : 1; } - - /// @brief Implicit conversion operator to `bool`. - /// @return `true` if the container is not empty, `false` if the container is empty. - explicit operator bool() const { return !Empty(); } - - /// @brief Get the underlying delegate. - /// @return The underlying delegate pointer, or nullptr if empty. - const DelegateType* GetDelegate() const { return static_cast(m_delegate.get()); } - -protected: - /// Registered delegate. Stored as `DelegateBase` (not `DelegateType`) so the - /// shared_ptr control block is shared across every `UnicastDelegate` - /// signature instead of duplicated per signature. Only `operator()`/ - /// `GetDelegate()`, which must return the concrete `DelegateType`, cast back. - std::shared_ptr m_delegate = nullptr; -}; - -} - -DMQ_OPTIMIZE_OFF - -#endif diff --git a/DelegateMQ/delegate/UnicastDelegateSafe.h b/DelegateMQ/delegate/UnicastDelegateSafe.h deleted file mode 100644 index 21d96b5..0000000 --- a/DelegateMQ/delegate/UnicastDelegateSafe.h +++ /dev/null @@ -1,169 +0,0 @@ -#ifndef _UNICAST_DELEGATE_SAFE_H -#define _UNICAST_DELEGATE_SAFE_H - -/// @file -/// @brief Delegate container for storing an invoking a single delegate instance. -/// Class is thread-safe. -/// -/// @note Invocation copies the delegate out under the lock and calls it after -/// releasing it, so a delegate cleared or replaced on one thread may still be -/// called once by an invocation already in progress on another. See the note in -/// Signal.h before destroying the target right after clearing. - -#include "UnicastDelegate.h" - -DMQ_OPTIMIZE_ON - -namespace dmq { - -template -class UnicastDelegateSafe; // Not defined - -namespace detail { - -/// @brief Copy the delegate pointer out under lock, then release. Non-templated: -/// entirely independent of the owning container's signature. The caller invokes -/// against the returned copy without holding the lock, avoiding circular lock -/// dependencies if the target function itself tries to acquire it. -inline std::shared_ptr UnicastSafeGet(const std::shared_ptr& delegate, RecursiveMutex& lock) { - const dmq::LockGuard g(lock); - return delegate; -} - -} // namespace detail - -/// @brief A thread-safe delegate container storing one delegate. Void and -/// non-void return values supported. -template -class UnicastDelegateSafe : public UnicastDelegate -{ -public: - using DelegateType = Delegate; - using BaseType = UnicastDelegate; - - UnicastDelegateSafe() = default; - virtual ~UnicastDelegateSafe() = default; - - UnicastDelegateSafe(const UnicastDelegateSafe& rhs) : BaseType() { - dmq::LockGuard lock(rhs.m_lock); - BaseType::operator=(rhs); - } - - UnicastDelegateSafe(UnicastDelegateSafe&& rhs) : BaseType() { - dmq::LockGuard lock(rhs.m_lock); - BaseType::operator=(std::move(rhs)); - } - - /// Constructor to initialize from a Delegate (Copy) - UnicastDelegateSafe(const DelegateType& d) { - dmq::LockGuard lock(m_lock); - BaseType::operator=(d); - } - - /// Constructor to initialize from a Delegate (Move) - UnicastDelegateSafe(DelegateType&& d) { - dmq::LockGuard lock(m_lock); - BaseType::operator=(std::move(d)); - } - - /// Invoke the bound target. - /// @param[in] args The arguments used when invoking the target function - /// @return The target function return value. - RetType operator()(Args... args) const { - // Lock only to fetch the delegate pointer. Release lock before - // invoking the delegate to prevent circular lock dependencies - // and deadlocks. - auto delegate = detail::UnicastSafeGet(this->m_delegate, m_lock); - - if (delegate) - return (*static_cast(delegate.get()))(args...); - return RetType(); - } - - /// Invoke the bound target functions. - /// @param[in] args The arguments used when invoking the target function - void Broadcast(Args... args) const { - operator()(args...); - } - - /// Assign a delegate to the container. - /// @param[in] rhs A delegate target to assign - void operator=(const DelegateType& rhs) { - const dmq::LockGuard lock(m_lock); - BaseType::operator=(rhs); - } - - /// Assign a delegate to the container. - /// @param[in] rhs A delegate target to assign - void operator=(DelegateType&& rhs) { - const dmq::LockGuard lock(m_lock); - BaseType::operator=(rhs); - } - - /// @brief Assignment operator that assigns the state of one object to another. - /// @param[in] rhs The object whose state is to be assigned to the current object. - /// @return A reference to the current object. - UnicastDelegateSafe& operator=(const UnicastDelegateSafe& rhs) { - if (this != &rhs) { - dmq::ScopedLock lock(m_lock, rhs.m_lock); - BaseType::operator=(rhs); - } - return *this; - } - - /// @brief Move assignment operator that transfers ownership of resources. - /// @param[in] rhs The object to move from. - /// @return A reference to the current object. - UnicastDelegateSafe& operator=(UnicastDelegateSafe&& rhs) noexcept { - if (this != &rhs) { - dmq::ScopedLock lock(m_lock, rhs.m_lock); - BaseType::operator=(std::move(rhs)); - } - return *this; - } - - /// @brief Clear the all target functions. - virtual void operator=(std::nullptr_t) noexcept { - const dmq::LockGuard lock(m_lock); - BaseType::Clear(); - } - - /// Any registered delegates? - /// @return `true` if delegate container is empty. - bool Empty() const { - const dmq::LockGuard lock(m_lock); - return BaseType::Empty(); - } - - /// Remove the registered delegate - void Clear() { - const dmq::LockGuard lock(m_lock); - BaseType::Clear(); - } - - /// Get the number of delegates stored. - /// @return The number of delegates stored. - std::size_t Size() const { - const dmq::LockGuard lock(m_lock); - return BaseType::Size(); - } - - /// @brief Implicit conversion operator to `bool`. - /// @return `true` if the container is not empty, `false` if the container is empty. - explicit operator bool() const { - const dmq::LockGuard lock(m_lock); - return BaseType::operator bool(); - } - -private: - /// Lock to make the class thread-safe. - /// Must be recursive to allow the callback to modify this delegate. - /// Must be mutable to allow locking in const methods. - mutable RecursiveMutex m_lock; -}; - -} - -DMQ_OPTIMIZE_OFF - -#endif diff --git a/DelegateMQ/delegate/make_tuple_heap.h b/DelegateMQ/delegate/make_tuple_heap.h deleted file mode 100644 index 81a109f..0000000 --- a/DelegateMQ/delegate/make_tuple_heap.h +++ /dev/null @@ -1,244 +0,0 @@ -#ifndef _MAKE_TUPLE_HEAP_H -#define _MAKE_TUPLE_HEAP_H - -// @see https://github.com/DelegateMQ/DelegateMQ -// David Lafreniere, Aug 2020. - -/// @file -/// @brief Helpers for storing the arguments of a non-blocking async call. -/// -/// @details `DelegateAsyncMsg` (`DelegateAsync.h`) builds its `std::tuple` of -/// arguments with `store_async_arg()`, one argument at a time, for transport through a -/// thread message queue. By-value arguments are stored in the tuple directly; for -/// pointer, pointer-to-pointer and reference arguments, `heap_copy_arg()` makes a heap -/// copy of the data, freed by a `heap_arg_deleter` once the call is done. -/// -/// The destination thread uses `std::apply()` to invoke the target function using -/// the tuple of arguments. - -#include -#include -#include -#include "DelegateOpt.h" -DMQ_OPTIMIZE_ON - -namespace dmq -{ -template -struct is_shared_ptr : std::false_type {}; - -template -struct is_shared_ptr> : std::true_type {}; - -template -struct is_shared_ptr&> : std::true_type {}; - -template -struct is_shared_ptr&> : std::true_type {}; - -template -struct is_shared_ptr*> : std::true_type {}; - -template -struct is_shared_ptr*> : std::true_type {}; - -template -struct is_unique_ptr : std::false_type {}; - -template -struct is_unique_ptr> : std::true_type {}; - -/// @brief Base class for all deleter's -class heap_arg_deleter_base -{ -public: - virtual ~heap_arg_deleter_base() = default; - - XALLOCATOR -}; - -/// @brief Forward declaration for heap argument deleter -template -class heap_arg_deleter; - -/// @brief Frees heap memory for pointer heap argument -template -class heap_arg_deleter : public heap_arg_deleter_base -{ -public: - heap_arg_deleter(T* arg) : m_arg(arg) { } - virtual ~heap_arg_deleter() { - xdelete(m_arg); - } -private: - T* m_arg; -}; - -/// @brief Frees heap memory for pointer to pointer heap argument -template -class heap_arg_deleter : public heap_arg_deleter_base -{ -public: - // Capture the original inner pointer at construction so the destructor always - // frees the xnew'd copy, regardless of whether the target function overwrites - // *arg (e.g. an outgoing-argument pattern like (*s) = new T). - heap_arg_deleter(T** arg) : m_arg(arg), m_inner(arg ? *arg : nullptr) {} - virtual ~heap_arg_deleter() { - if (m_arg && *m_arg != m_inner) { - xdelete(*m_arg); // free the newly assigned pointer if overwritten by target function - } - xdelete(m_inner); // free the original xnew'd inner copy (may be nullptr) - xdelete(m_arg); // free the outer pointer storage - } -private: - T** m_arg; - T* m_inner; // original value of *arg at dispatch time -}; - -// The three heap_copy_arg() overloads below make the heap copy for a pointer, -// pointer-to-pointer or reference argument and register a deleter for it in -// `heapArgs`; the deleter frees the copy when the message is destroyed. They are -// overloads (not one function with if constexpr) so the same overload is chosen for -// every argument type as when they were `tuple_append()`. -// -// Failure handling: BAD_ALLOC() never returns (DMQ_ASSERTS calls the noreturn -// FaultHandler, otherwise it throws std::bad_alloc), so code after it doesn't run. -// If heapArgs.push_back() throws, the local `deleter` going out of scope frees the copy. - -/// @brief Heap-copy a pointer-to-pointer argument: the pointee and the pointer. -/// @return The heap copy (a `nullptr` inner pointer if `arg` or `*arg` is null). -template -Arg** heap_copy_arg(xlist>& heapArgs, Arg** arg) -{ - Arg** heap_arg = nullptr; - Arg** del_arg = nullptr; - - if (arg != nullptr && *arg != nullptr) { - // Allocate memory for heap_arg and copy the value - heap_arg = xnew(); - if (!heap_arg) { - BAD_ALLOC(); - } else { - *heap_arg = xnew(**arg); - if (!*heap_arg) { - xdelete(heap_arg); - BAD_ALLOC(); - } else { - del_arg = heap_arg; - } - } - } - else { - // If arg is nullptr or *arg is nullptr, create heap_arg as nullptr - heap_arg = xnew(nullptr); - if (!heap_arg) { - BAD_ALLOC(); - } else { - del_arg = heap_arg; - } - } - - auto deleter = xmake_shared>(del_arg); - if (!deleter) { - if (del_arg) { - if (*del_arg) xdelete(*del_arg); - xdelete(del_arg); - } - BAD_ALLOC(); - } - heapArgs.push_back(deleter); - return heap_arg; -} - -/// @brief Heap-copy a pointer argument's pointee. -/// @return The heap copy, or `nullptr` if `arg` is null. -template -Arg* heap_copy_arg(xlist>& heapArgs, Arg* arg) -{ - Arg* heap_arg = nullptr; - Arg* del_arg = nullptr; - if (arg != nullptr) { - heap_arg = xnew(*arg); - if (!heap_arg) { - BAD_ALLOC(); - } else { - del_arg = heap_arg; - } - } - auto deleter = xmake_shared>(del_arg); - if (!deleter) { - if (del_arg) { - xdelete(del_arg); - } - BAD_ALLOC(); - } - heapArgs.push_back(deleter); - return heap_arg; -} - -/// @brief Heap-copy a reference argument. -/// @return A reference to the heap copy. -template -Arg& heap_copy_arg(xlist>& heapArgs, Arg& arg) -{ - Arg* heap_arg = xnew(arg); - Arg* del_arg = nullptr; - if (!heap_arg) { - BAD_ALLOC(); - } else { - del_arg = heap_arg; - } - auto deleter = xmake_shared>(del_arg); - if (!deleter) { - if (del_arg) { - xdelete(del_arg); - } - BAD_ALLOC(); - } - heapArgs.push_back(deleter); - return *heap_arg; -} - -/// @brief Store one argument of a non-blocking async call. Chooses by `Param`, the -/// bound function's declared parameter type, not by how the argument arrives. -/// @details -/// - By-value parameter: returned as-is (moved). The message's `std::tuple` -/// element holds its own copy, so a heap copy would only be copied again. -/// - Reference or pointer parameter: the caller's data is copied to the heap (freed -/// through `heapArgs` once the call is done) and a reference/pointer to that copy is -/// returned, using the `heap_copy_arg()` overloads above. -/// -/// This replaced `make_tuple_heap()`, which heap-copied every argument, by-value ones -/// too. An earlier attempt to skip the copy for values added an `Arg&&` overload of -/// `tuple_append()` (now `heap_copy_arg()`), i.e. chose by the argument's value -/// category. It silently stopped applying when `make_tuple_heap()` began passing its -/// arguments on as lvalues, and was later removed. Deciding from `Param` with -/// `if constexpr` doesn't depend on overload resolution. -/// @tparam Param The declared parameter type of the bound function. -/// @param heapArgs The list of deleters for heap-allocated arguments. -/// @param arg The argument, forwarded as `Param`. -/// @return The value (by-value `Param`), or a reference/pointer to the heap copy. -template -decltype(auto) store_async_arg(xlist>& heapArgs, A&& arg) -{ - static_assert(!std::is_same, void*>::value, "void* argument not allowed"); - if constexpr (std::is_reference_v) { - // Pass as an lvalue so heap_copy_arg()'s Arg& overload makes the heap copy; - // it returns a reference to that copy. - auto& lv = arg; - return heap_copy_arg(heapArgs, lv); - } else if constexpr (std::is_pointer_v) { - // Pointer and pointer-to-pointer: heap copy of the pointee, as before. - auto& lv = arg; - Param heapPtr = heap_copy_arg(heapArgs, lv); - return heapPtr; - } else { - return std::forward(arg); - } -} - -} - -DMQ_OPTIMIZE_OFF - -#endif diff --git a/DelegateMQ/delegate/src_dup.py b/DelegateMQ/delegate/src_dup.py deleted file mode 100644 index 31063e1..0000000 --- a/DelegateMQ/delegate/src_dup.py +++ /dev/null @@ -1,76 +0,0 @@ -# Script to keep common sections of the repetitive code and data -# synchronized within the same file. The code between the first -# pare of a tags within a source code file is automatically duplicated -# to all other tag locations. For instance, change MyClass1::Func() and -# classes below will be updated to match. -# -# -# class MyClass1 { -# public: -# // -# void Func() {} -# // -# } -# -# class MyClass2 { -# public: -# // -# void Func() {} -# // -# } -# -# Tags: -# -# -# Run: -# python src_dup.py -# -# python src_dup.py DelegateAsync.h -# python src_dup.py DelegateAsyncWait.h - -import re -import sys - -def copy_common_code(input_code, tag): - # Regular expression to match content within tag - common_pattern = re.compile(tag, re.DOTALL) - - # Find all the content inside the tag - common_code_match = re.search(common_pattern, input_code) - - if common_code_match: - common_code = common_code_match.group(0) - - # Replace the tags content - output_code = re.sub(common_pattern, f"{common_code}", input_code) - - return output_code - else: - return input_code - -def process_file(file_name): - try: - # Open the file and read the content - with open(file_name, 'r') as file: - input_code = file.read() - - # Process the code and get the modified version - modified_code = copy_common_code(input_code, r'// (.*?)// ') - - # Output the modified code - with open(file_name, 'w') as output_file: - output_file.write(modified_code) - - print(f"Modified code has been written to {file_name}") - - except FileNotFoundError: - print(f"Error: The file '{file_name}' was not found.") - except ValueError as e: - print(e) - -if __name__ == "__main__": - if len(sys.argv) != 2: - print("Usage: python script.py ") - else: - input_file_name = sys.argv[1] - process_file(input_file_name) diff --git a/DelegateMQ/extras/allocator/Allocator.cpp b/DelegateMQ/extras/allocator/Allocator.cpp deleted file mode 100644 index 5ed885d..0000000 --- a/DelegateMQ/extras/allocator/Allocator.cpp +++ /dev/null @@ -1,185 +0,0 @@ -// Compiles to nothing unless DMQ_ALLOCATOR is selected, so every DelegateMQ source -// file can be added to a build (see src/DelegateMQ.cpp). -#include "delegate/DelegateSelect.h" -#if defined(DMQ_ALLOCATOR) - -#include "Allocator.h" -#include "delegate/DelegateOpt.h" -#include - -namespace dmq { - -//------------------------------------------------------------------------------ -// Constructor -//------------------------------------------------------------------------------ -Allocator::Allocator(size_t size, uint32_t objects, char* memory, const char* name) : - m_blockSize(size < sizeof(long*) ? sizeof(long*):size), - m_objectSize(size), - m_maxObjects(objects), - m_pHead(NULL), - m_poolIndex(0), - m_blockCnt(0), - m_blocksInUse(0), - m_allocations(0), - m_deallocations(0), - m_name(name) -{ - // If using a fixed memory pool - if (m_maxObjects) - { - // If caller provided an external memory pool - if (memory) - { - m_pPool = memory; - m_allocatorMode = STATIC_POOL; - } - else - { - m_pPool = (char*)new char[m_blockSize * m_maxObjects]; - m_allocatorMode = HEAP_POOL; - } - } - else - { - m_pPool = NULL; - m_allocatorMode = HEAP_BLOCKS; - } -} - -//------------------------------------------------------------------------------ -// Destructor -//------------------------------------------------------------------------------ -Allocator::~Allocator() -{ - // If using pool then destroy it, otherwise traverse free-list and - // destroy each individual block - if (m_allocatorMode == HEAP_POOL) - delete [] m_pPool; - else if (m_allocatorMode == HEAP_BLOCKS) - { - while(m_pHead) - delete [] (char*)Pop(); - } -} - -//------------------------------------------------------------------------------ -// Allocate -//------------------------------------------------------------------------------ -void* Allocator::Allocate([[maybe_unused]] size_t size) -{ - DMQ_ASSERT_TRUE(size <= m_objectSize); - - // If can't obtain existing block then get a new one - void* pBlock = Pop(); - if (!pBlock) - { - // If using a pool method then get block from pool, - // otherwise using dynamic so get block from heap - if (m_maxObjects) - { - // If we have not exceeded the pool maximum - if(m_poolIndex < m_maxObjects) - { - pBlock = (void*)(m_pPool + (m_poolIndex++ * m_blockSize)); - } - else - { - // Get the pointer to the new handler - std::new_handler handler = std::set_new_handler(0); - std::set_new_handler(handler); - - while (!pBlock) - { - if (handler) - { - (*handler)(); - pBlock = Pop(); - } - else - { - BAD_ALLOC(); - } - } - } - } - else - { - m_blockCnt++; - pBlock = (void*)new char[m_blockSize]; - } - } - - if (pBlock) - { - m_blocksInUse++; - m_allocations++; - } - - return pBlock; -} - -//------------------------------------------------------------------------------ -// Deallocate -//------------------------------------------------------------------------------ -void Allocator::Deallocate(void* pBlock) -{ - // delete of a null pointer may call operator delete(NULL) (DECLARE_ALLOCATOR) - if (!pBlock) - return; - -#ifdef DMQ_ALLOCATOR_SAFEGUARDS - if (m_allocatorMode == STATIC_POOL || m_allocatorMode == HEAP_POOL) - { - // Check that pBlock is within the pool range - char* pCharBlock = (char*)pBlock; - DMQ_ASSERT_TRUE(pCharBlock >= m_pPool && pCharBlock < (m_pPool + (m_blockSize * m_maxObjects))); - - // Check that pBlock is aligned on a block boundary - DMQ_ASSERT_TRUE(((size_t)(pCharBlock - m_pPool) % m_blockSize) == 0); - } -#endif - - Push(pBlock); - m_blocksInUse--; - m_deallocations++; -} - -//------------------------------------------------------------------------------ -// AccountAlloc -//------------------------------------------------------------------------------ -void Allocator::AccountAlloc(bool newBlock) -{ - if (newBlock) m_blockCnt++; - m_blocksInUse++; - m_allocations++; -} - -//------------------------------------------------------------------------------ -// Push -//------------------------------------------------------------------------------ -void Allocator::Push(void* pMemory) -{ - Block* pBlock = (Block*)pMemory; - pBlock->pNext = m_pHead; - m_pHead = pBlock; -} - -//------------------------------------------------------------------------------ -// Pop -//------------------------------------------------------------------------------ -void* Allocator::Pop() -{ - Block* pBlock = NULL; - - if (m_pHead) - { - pBlock = m_pHead; - m_pHead = m_pHead->pNext; - } - - return (void*)pBlock; -} - -} // namespace dmq - -#endif // DMQ_ALLOCATOR diff --git a/DelegateMQ/extras/allocator/Allocator.h b/DelegateMQ/extras/allocator/Allocator.h deleted file mode 100644 index 50e0ad5..0000000 --- a/DelegateMQ/extras/allocator/Allocator.h +++ /dev/null @@ -1,134 +0,0 @@ -#ifndef __ALLOCATOR_H -#define __ALLOCATOR_H - -#include "../../delegate/DelegateOpt.h" -#include -#include -#include - -namespace dmq { - -/// @see https://github.com/endurodave/Allocator -/// David Lafreniere -class Allocator -{ -public: - /// Constructor - /// @param[in] size - size of the fixed blocks - /// @param[in] objects - maximum number of object. If 0, new blocks are - /// created off the heap as necessary. - /// @param[in] memory - pointer to a block of static memory for allocator or NULL - /// to obtain memory from global heap. If not NULL, the objects argument - /// defines the size of the memory block (size x objects = memory size in bytes). - /// @param[in] name - optional allocator name string. - Allocator(size_t size, uint32_t objects=0, char* memory = NULL, const char* name=NULL); - - /// Destructor - ~Allocator(); - - /// Get a pointer to a memory block. - /// @param[in] size - size of the block to allocate - /// @return Returns pointer to the block. Otherwise NULL if unsuccessful. - void* Allocate(size_t size); - - /// Return a pointer to the memory pool. - /// @param[in] pBlock - block of memory deallocate (i.e push onto free-list) - void Deallocate(void* pBlock); - - /// Update allocation stats when xmalloc bypasses Allocate() to avoid holding - /// the global lock during heap allocation. Must be called under the global lock. - /// @param[in] newBlock - true if a fresh block was obtained from the heap. - void AccountAlloc(bool newBlock); - - /// Push a memory block onto head of free-list. - /// @param[in] pMemory - block of memory to push onto free-list - void Push(void* pMemory); - - /// Pop a memory block from head of free-list. - /// @return Returns pointer to the block. Otherwise NULL if unsuccessful. - void* Pop(); - - /// Get the allocator name string. - /// @return A pointer to the allocator name or NULL if none was assigned. - const char* GetName() { return m_name; } - - /// Gets the fixed block memory size, in bytes, handled by the allocator. - /// @return The fixed block size in bytes. - size_t GetBlockSize() const { return m_blockSize; } - - /// Gets the maximum number of blocks created by the allocator. - /// @return The number of fixed memory blocks created. - uint32_t GetBlockCount() { return m_blockCnt; } - - /// Gets the number of blocks in use. - /// @return The number of fixed memory blocks in use. - uint32_t GetBlocksInUse() { return m_blocksInUse; } - - /// Gets the total number of allocations for this allocator instance. - /// @return The total number of allocations. - uint32_t GetAllocations() { return m_allocations; } - - /// Gets the total number of deallocations for this allocator instance. - /// @return The total number of deallocations. - uint32_t GetDeallocations() { return m_deallocations; } - -private: - struct Block - { - Block* pNext; - }; - - enum AllocatorMode { HEAP_BLOCKS, HEAP_POOL, STATIC_POOL }; - - const size_t m_blockSize; - const size_t m_objectSize; - const uint32_t m_maxObjects; - AllocatorMode m_allocatorMode; - Block* m_pHead; - char* m_pPool; - uint32_t m_poolIndex; - uint32_t m_blockCnt; - uint32_t m_blocksInUse; - uint32_t m_allocations; - uint32_t m_deallocations; - const char* m_name; -}; - -// Template class to create external memory pool -template -class AllocatorPool : public Allocator -{ -public: - AllocatorPool() : Allocator(sizeof(T), Objects, m_memory) - { - } -private: - alignas(std::max_align_t) char m_memory[sizeof(T) * Objects]; -}; - -} // namespace dmq - -// macro to provide header file interface -#define DECLARE_ALLOCATOR \ - public: \ - void* operator new(size_t size) { \ - dmq::LockGuard lock(_allocatorMutex); \ - return _allocator.Allocate(size); \ - } \ - void operator delete(void* pObject) { \ - dmq::LockGuard lock(_allocatorMutex); \ - _allocator.Deallocate(pObject); \ - } \ - private: \ - static dmq::Allocator _allocator; \ - static dmq::Mutex _allocatorMutex; - -// macro to provide source file interface -#define IMPLEMENT_ALLOCATOR(class, objects, memory) \ - dmq::Allocator class::_allocator(sizeof(class), objects, memory, #class); \ - dmq::Mutex class::_allocatorMutex; - -#endif - - - diff --git a/DelegateMQ/extras/allocator/README.md b/DelegateMQ/extras/allocator/README.md deleted file mode 100644 index 3f9aa09..0000000 --- a/DelegateMQ/extras/allocator/README.md +++ /dev/null @@ -1,64 +0,0 @@ -# Allocator Suite - -A robust, fixed-block memory allocator suite for C++ applications, designed for performance and deterministic behavior in resource-constrained or real-time systems. - -## Features - -- **Fixed-Block Allocation**: Prevents heap fragmentation by using pre-allocated pools of equal-sized blocks. -- **C++ Class Integration**: `DECLARE_ALLOCATOR` and `IMPLEMENT_ALLOCATOR` macros provide easy integration with custom classes. -- **XALLOCATOR Macro**: Overloads `operator new` and `operator delete` for seamless use. -- **STL Compatibility**: `stl_allocator` allows STL containers (`std::vector`, `std::list`, `std::map`, etc.) to use the fixed-block pool. -- **Smart Pointer Support**: `xmake_shared` creates `std::shared_ptr` with both the object and control block allocated from the pool. -- **C API**: `xmalloc`, `xfree`, and `xrealloc` functions for C-style memory management. - -## Components - -- **Allocator**: The core engine for fixed-block management. -- **AllocatorPool**: A template-based pool for specific types. -- **stl_allocator**: STL-compliant allocator wrapper. -- **xmake_shared**: Helper for pool-allocated shared pointers. -- **xnew / xdelete**: Helper templates for placement new/destroy in the pool. - -## Basic Usage - -### Using XALLOCATOR in a class - -```cpp -class MyClass { - XALLOCATOR -public: - int data; -}; - -// Now 'new MyClass' uses the fixed-block allocator -MyClass* obj = new MyClass(); -delete obj; -``` - -### Using STL containers - -```cpp -#include "xlist.h" - -// xlist is a typedef for std::list using stl_allocator -xlist myList; -myList.push_back(10); -``` - -### Using xmake_shared - -```cpp -auto sp = xmake_shared(args...); -``` - -## Memory Alignment - -The `xallocator` implementation ensures that all allocated blocks are correctly aligned for the target architecture: - -- **Power-of-Two Rounding**: All requested block sizes are rounded up to the next power of two (8, 16, 32, 64, etc.). This inherently satisfies the natural alignment requirements of all standard C++ types (`int`, `double`, `long long`, etc.) and modern SIMD/AVX vector instructions. -- **Header Alignment**: A `BLOCK_HEADER_SIZE` (16 bytes on 64-bit, 8 bytes on 32-bit) is added to each block to store metadata. Both the raw block and the user's data pointer remain aligned on 8 or 16-byte boundaries. -- **Efficiency vs. Safety**: This strategy prioritizes "automatic" alignment and safety over maximum memory density. While it may result in some internal fragmentation, it ensures that memory is always safe for any data type without manual alignment configuration. - -## Integration with DelegateMQ - -To enable the allocator suite within DelegateMQ, define `DMQ_ALLOCATOR` in your build configuration. This will cause DelegateMQ's internal containers and remote delegate marshalling to use the fixed-block pools instead of the standard heap. diff --git a/DelegateMQ/extras/allocator/stl_allocator.h b/DelegateMQ/extras/allocator/stl_allocator.h deleted file mode 100644 index 6d72cfd..0000000 --- a/DelegateMQ/extras/allocator/stl_allocator.h +++ /dev/null @@ -1,79 +0,0 @@ -#ifndef _STL_ALLOCATOR_H -#define _STL_ALLOCATOR_H - -// @see https://github.com/endurodave/stl_allocator -// David Lafreniere - -#include "xallocator.h" -#include "delegate/DelegateOpt.h" -#include // For std::allocator and std::allocator_traits -#include // For std::forward - -namespace dmq { - -// Forward declaration for stl_allocator -template -class stl_allocator; - -// Specialization for `void`, but we no longer need to define `pointer` and `const_pointer` -template <> -class stl_allocator -{ -public: - typedef void value_type; - - template - struct rebind { typedef stl_allocator other; }; -}; - -// Define the custom stl_allocator inheriting from std::allocator -template -class stl_allocator : public std::allocator -{ -public: - typedef size_t size_type; - typedef ptrdiff_t difference_type; - typedef T* pointer; - typedef const T* const_pointer; - typedef T& reference; - typedef const T& const_reference; - typedef T value_type; - - // Default constructor - stl_allocator() {} - - // Copy constructor - template - stl_allocator(const stl_allocator&) {} - - // Rebind struct - template - struct rebind { typedef stl_allocator other; }; - - // Override allocate method to use custom allocation function - pointer allocate(size_type n, typename std::allocator_traits>::const_pointer /*hint*/ = 0) - { - void* p = xmalloc(n * sizeof(T)); - if (!p) BAD_ALLOC(); - return static_cast(p); - } - - // Override deallocate method to use custom deallocation function - void deallocate(pointer p, size_type /*n*/) - { - xfree(p); - } - - // You can inherit other methods like construct and destroy from std::allocator -}; - -// Comparison operators for compatibility -template -inline bool operator==(const stl_allocator&, const stl_allocator&) { return true; } - -template -inline bool operator!=(const stl_allocator&, const stl_allocator&) { return false; } - -} // namespace dmq - -#endif diff --git a/DelegateMQ/extras/allocator/xallocator.cpp b/DelegateMQ/extras/allocator/xallocator.cpp deleted file mode 100644 index 8a27668..0000000 --- a/DelegateMQ/extras/allocator/xallocator.cpp +++ /dev/null @@ -1,493 +0,0 @@ -// Compiles to nothing unless DMQ_ALLOCATOR is selected, so every DelegateMQ source -// file can be added to a build (see src/DelegateMQ.cpp). -#include "delegate/DelegateSelect.h" -#if defined(DMQ_ALLOCATOR) - -#include "Allocator.h" -#include "xallocator.h" -#include "delegate/DelegateOpt.h" -#include -#include -#include -#include - - -#ifndef CHAR_BIT -#define CHAR_BIT 8 -#endif - -namespace dmq { - -// @TODO: Comment out to disable alignment check if desired after porting -//#define CHECK_ALIGNMENT - -// Logic: -// 1. We store a 'BlockHeader' at the start of the raw block. -// 2. The user's memory immediately follows this header. -// 3. To support types like 'long double' or SSE/AVX vectors, the user's memory -// must often be aligned to 16 bytes (on 64-bit) or 8 bytes (on 32-bit). -// -// Calculation: -// - Safeguards ON: BLOCK_HEADER_SIZE is fixed at 16 bytes to provide a -// robust guard area and maintain 16-byte alignment for the user. -// - Safeguards OFF: -// - 64-bit System: Ptrs are 8 bytes. Next aligned boundary is 16. Set to 16. -// - 32-bit System: Ptrs are 4 bytes. Next aligned boundary is 8. Set to 8. -// Single source of truth lives in xallocator.h; typed aliases for internal use. -static const size_t BLOCK_HEADER_SIZE = XALLOC_BLOCK_HEADER_SIZE; -static const size_t BLOCK_FOOTER_SIZE = XALLOC_BLOCK_FOOTER_SIZE; - -struct BlockHeader { - Allocator* allocator; -#ifdef DMQ_ALLOCATOR_SAFEGUARDS - uint32_t magic; - uint32_t canary; -#endif -}; - -// Define STATIC_POOLS to switch from heap blocks mode to static pools mode -//#define STATIC_POOLS -#ifdef STATIC_POOLS - // Update this section as necessary if you want to use static memory pools. - // See also xalloc_init() and xalloc_destroy() for additional updates required. - #define MAX_ALLOCATORS 10 - #define MAX_BLOCKS 32 - - // Create static storage for each static allocator instance - static alignas(std::max_align_t) char _allocator8 [sizeof(AllocatorPool)]; - static alignas(std::max_align_t) char _allocator16 [sizeof(AllocatorPool)]; - static alignas(std::max_align_t) char _allocator32 [sizeof(AllocatorPool)]; - static alignas(std::max_align_t) char _allocator64 [sizeof(AllocatorPool)]; - static alignas(std::max_align_t) char _allocator128 [sizeof(AllocatorPool)]; - static alignas(std::max_align_t) char _allocator256 [sizeof(AllocatorPool)]; - static alignas(std::max_align_t) char _allocator512 [sizeof(AllocatorPool)]; - static alignas(std::max_align_t) char _allocator1024 [sizeof(AllocatorPool)]; - static alignas(std::max_align_t) char _allocator2048 [sizeof(AllocatorPool)]; - static alignas(std::max_align_t) char _allocator4096 [sizeof(AllocatorPool)]; - - // Array of pointers to all allocator instances - static Allocator* _allocators[MAX_ALLOCATORS]; - -#else - #define MAX_ALLOCATORS DMQ_XALLOCATOR_MAX_ALLOCATORS - static Allocator* _allocators[MAX_ALLOCATORS]; -#endif // STATIC_POOLS - -// For C++ applications, must define AUTOMATIC_XALLOCATOR_INIT_DESTROY to -// correctly ensure allocators are initialized before any static user C++ -// construtor/destructor executes which might call into the xallocator API. -// This feature costs 1-byte of RAM per C++ translation unit. This feature -// can be disabled only under the following circumstances: -// -// 1) The xallocator is only used within C files. -// 2) STATIC_POOLS is undefined and the application never exits main (e.g. -// an embedded system). -// -// In either of the two cases above, call xalloc_init() in main at startup, -// and xalloc_destroy() before main exits. In all other situations -// XallocInitDestroy must be used to call xalloc_init() and xalloc_destroy(). -#ifdef AUTOMATIC_XALLOCATOR_INIT_DESTROY -std::atomic XallocInitDestroy::refCount(0); -XallocInitDestroy::XallocInitDestroy() -{ - // Track how many static instances of XallocInitDestroy are created - if (refCount++ == 0) - ::xalloc_init(); -} - -XallocInitDestroy::~XallocInitDestroy() -{ - // Last static instance to have destructor called? - if (--refCount == 0) - ::xalloc_destroy(); -} -#endif // AUTOMATIC_XALLOCATOR_INIT_DESTROY - -/// Returns the next higher powers of two. For instance, pass in 12 and -/// the value returned would be 16. -/// @param[in] k - numeric value to compute the next higher power of two. -/// @return The next higher power of two based on the input k. -template -T nexthigher(T k) -{ - k--; - for (size_t i=1; i> i); - return k+1; -} - -static dmq::Mutex& get_mutex() -{ - // Intentional immortal singleton: heap-allocate and never delete. - // A Meyers static would be destroyed during the static shutdown sequence; - // any static destructor that runs afterward and calls xalloc_* would then - // use-after-free the mutex. The heap pointer is never freed — the OS - // reclaims it at process exit, after all destructors have run. - static dmq::Mutex* _mutex = new dmq::Mutex(); - return *_mutex; -} - -#ifdef CHECK_ALIGNMENT -static void check_alignment(void* ptr) -{ - // Convert pointer to integer to perform bitwise check - uintptr_t address = reinterpret_cast(ptr); - - // Check if the address is a multiple of the pointer size. - // On 32-bit systems, we often only get 4-byte alignment from the heap. - // On 64-bit systems, we expect 8 or 16-byte alignment. - if ((address & (sizeof(void*) - 1)) != 0) - { - DMQ_ASSERT(); - } -} -#endif - -/// Stored a pointer to the allocator instance within the block region. -/// a pointer to the client's area within the block. -/// @param[in] block - a pointer to the raw memory block. -/// @param[in] allocator - the allocator instance. -/// @param[in] size - the client requested size of the memory block. -/// @return A pointer to the client's address within the raw memory block. -static inline void *set_block_allocator(void* block, Allocator* allocator) -{ - BlockHeader* pHeader = static_cast(block); - pHeader->allocator = allocator; -#ifdef DMQ_ALLOCATOR_SAFEGUARDS - pHeader->magic = XALLOC_MAGIC; - pHeader->canary = XALLOC_CANARY; - size_t userSize = allocator->GetBlockSize() - BLOCK_HEADER_SIZE - BLOCK_FOOTER_SIZE; - uint32_t* pFooter = (uint32_t*)((char*)block + BLOCK_HEADER_SIZE + userSize); - *pFooter = XALLOC_CANARY; -#endif - // Advance by BLOCK_HEADER_SIZE bytes (cast to char* first to do byte math) - return (char*)block + BLOCK_HEADER_SIZE; -} - -/// Gets the size of the memory block stored within the block. -/// @param[in] block - a pointer to the client's memory block. -/// @return The original allocator instance stored in the memory block. -static inline Allocator* get_block_allocator(void* block) -{ - BlockHeader* pHeader = (BlockHeader*)((char*)block - BLOCK_HEADER_SIZE); -#ifdef DMQ_ALLOCATOR_SAFEGUARDS - DMQ_ASSERT_TRUE(pHeader->magic != XALLOC_FREED); - DMQ_ASSERT_TRUE(pHeader->magic == XALLOC_MAGIC); - DMQ_ASSERT_TRUE(pHeader->canary == XALLOC_CANARY); - size_t userSize = pHeader->allocator->GetBlockSize() - BLOCK_HEADER_SIZE - BLOCK_FOOTER_SIZE; - uint32_t* pFooter = (uint32_t*)((char*)pHeader + BLOCK_HEADER_SIZE + userSize); - DMQ_ASSERT_TRUE(*pFooter == XALLOC_CANARY); -#endif - return pHeader->allocator; -} - -/// Returns the raw memory block pointer given a client memory pointer. -/// @param[in] block - a pointer to the client memory block. -/// @return A pointer to the original raw memory block address. -static inline void *get_block_ptr(void* block) -{ - return (char*)block - BLOCK_HEADER_SIZE; -} - -/// Returns an allocator instance matching the size provided -/// @param[in] size - allocator block size -/// @return Allocator instance handling requested block size or NULL -/// if no allocator exists. -static inline Allocator* find_allocator(size_t size) -{ - for (int i=0; iGetBlockSize() == size) - return _allocators[i]; - } - - return NULL; -} - -/// Insert an allocator into the first empty slot. Caller must hold get_mutex(). -/// @param[in] allocator - allocator instance to insert -/// @return true if inserted, false if the array is full -static inline bool insert_allocator(Allocator* allocator) -{ - for (int i = 0; i < MAX_ALLOCATORS; i++) - { - if (_allocators[i] == 0) - { - _allocators[i] = allocator; - return true; - } - } - return false; -} - -} // namespace dmq - -/// This function must be called exactly one time *before* any other xallocator -/// API is called. XallocInitDestroy constructor calls this function automatically. -extern "C" void xalloc_init() -{ -#ifdef STATIC_POOLS - dmq::get_mutex().lock(); - - // For STATIC_POOLS mode, the allocators must be initialized before any other - // static user class constructor is run. Therefore, use placement new to initialize - // each allocator into the previously reserved static memory locations. - new (&dmq::_allocator8) dmq::AllocatorPool(); - new (&dmq::_allocator16) dmq::AllocatorPool(); - new (&dmq::_allocator32) dmq::AllocatorPool(); - new (&dmq::_allocator64) dmq::AllocatorPool(); - new (&dmq::_allocator128) dmq::AllocatorPool(); - new (&dmq::_allocator256) dmq::AllocatorPool(); - new (&dmq::_allocator512) dmq::AllocatorPool(); - new (&dmq::_allocator1024) dmq::AllocatorPool(); - new (&dmq::_allocator2048) dmq::AllocatorPool(); - new (&dmq::_allocator4096) dmq::AllocatorPool(); - - // Populate allocator array with all instances - dmq::_allocators[0] = (dmq::Allocator*)&dmq::_allocator8; - dmq::_allocators[1] = (dmq::Allocator*)&dmq::_allocator16; - dmq::_allocators[2] = (dmq::Allocator*)&dmq::_allocator32; - dmq::_allocators[3] = (dmq::Allocator*)&dmq::_allocator64; - dmq::_allocators[4] = (dmq::Allocator*)&dmq::_allocator128; - dmq::_allocators[5] = (dmq::Allocator*)&dmq::_allocator256; - dmq::_allocators[6] = (dmq::Allocator*)&dmq::_allocator512; - dmq::_allocators[7] = (dmq::Allocator*)&dmq::_allocator1024; - dmq::_allocators[8] = (dmq::Allocator*)&dmq::_allocator2048; - dmq::_allocators[9] = (dmq::Allocator*)&dmq::_allocator4096; - - dmq::get_mutex().unlock(); -#endif -} - -/// Called one time when the application exits to cleanup any allocated memory. -/// ~XallocInitDestroy destructor calls this function automatically. -extern "C" void xalloc_destroy() -{ - dmq::get_mutex().lock(); - -#ifdef STATIC_POOLS - for (int i=0; i~Allocator(); - dmq::_allocators[i] = 0; - } -#else - for (int i=0; i(-1) >> 1) + 1; - if (size > maxBlockSize - dmq::BLOCK_HEADER_SIZE - dmq::BLOCK_FOOTER_SIZE) - return NULL; - - // Based on the size, find the next higher powers of two value. - size_t blockSize = size + dmq::BLOCK_HEADER_SIZE + dmq::BLOCK_FOOTER_SIZE; - blockSize = dmq::nexthigher(blockSize); - - dmq::get_mutex().lock(); - dmq::Allocator* allocator = dmq::find_allocator(blockSize); - dmq::get_mutex().unlock(); - -#ifdef STATIC_POOLS - DMQ_ASSERT_TRUE(allocator != NULL); -#else - // If there is not an allocator already created to handle this block size - if (allocator == NULL) - { - // Note: Creating the Allocator object is done OUTSIDE the lock to avoid - // AB/BA deadlocks with the system standard library locks. - // nothrow: an exception must not leave this extern "C" function - allocator = new (std::nothrow) dmq::Allocator(blockSize, 0, 0, "xallocator"); - if (allocator == NULL) - return NULL; - - // Re-check and insert atomically under the same lock — eliminates the TOCTOU - // window where two concurrent threads could each insert an Allocator for - // the same block size, yielding duplicate entries and a use-after-free at shutdown. - dmq::get_mutex().lock(); - dmq::Allocator* existing = dmq::find_allocator(blockSize); - if (!existing) - { - if (!dmq::insert_allocator(allocator)) - { - dmq::get_mutex().unlock(); - delete allocator; - DMQ_ASSERT(); - } - existing = allocator; - } - dmq::get_mutex().unlock(); - - if (existing != allocator) - delete allocator; - allocator = existing; - } -#endif - - return allocator; -} - -/// Allocates a memory block of the requested size. The blocks are created from -/// the fixed block allocators. -/// @param[in] size - the client requested size of the block. -/// @return A pointer to the client's memory block. -extern "C" void *xmalloc(size_t size) -{ - // 1. Get the bucket (surgical global locking inside). NULL: size too large. - dmq::Allocator* allocator = xallocator_get_allocator(size); - if (allocator == NULL) - return NULL; - size_t blockSize = allocator->GetBlockSize(); - - void* blockMemoryPtr = NULL; - -#ifdef STATIC_POOLS - // STATIC_POOLS: Allocate() handles pool slot distribution, exhaustion detection, - // and stat tracking. Must be called under the lock. - dmq::get_mutex().lock(); - blockMemoryPtr = allocator->Allocate(blockSize); - dmq::get_mutex().unlock(); -#else - // 2. Fast Path: pop a recycled block from the free-list under the lock. - dmq::get_mutex().lock(); - blockMemoryPtr = allocator->Pop(); - if (blockMemoryPtr != NULL) - allocator->AccountAlloc(false); - dmq::get_mutex().unlock(); - - if (blockMemoryPtr == NULL) - { - // 3. Slow Path: fetch from heap OUTSIDE the lock to prevent AB/BA deadlocks - // with standard library internal locks (e.g., MSVC _Lockit in debug builds). - // nothrow: an exception must not leave this extern "C" function (see - // CLAUDE.md). Callers (XALLOCATOR, stl_allocator) report NULL with BAD_ALLOC(). - blockMemoryPtr = (void*)new (std::nothrow) char[blockSize]; - if (blockMemoryPtr != NULL) - { - dmq::get_mutex().lock(); - allocator->AccountAlloc(true); - dmq::get_mutex().unlock(); - } - } -#endif - - if (blockMemoryPtr == NULL) - return NULL; - - // Set the block Allocator* within the raw memory block region - void* userPtr = dmq::set_block_allocator(blockMemoryPtr, allocator); - -#ifdef CHECK_ALIGNMENT - // Verify memory alignment before returning to the user - dmq::check_alignment(blockMemoryPtr); - dmq::check_alignment(userPtr); -#endif - - return userPtr; -} - -/// Frees a memory block previously allocated with xalloc. The blocks are returned -/// to the fixed block allocator that originally created it. -/// @param[in] ptr - a pointer to a block created with xalloc. -extern "C" void xfree(void* ptr) -{ - if (ptr == 0) - return; - - // Extract the original allocator instance from the caller's block pointer - dmq::Allocator* allocator = dmq::get_block_allocator(ptr); - - // Convert the client pointer into the original raw block pointer - void* blockPtr = dmq::get_block_ptr(ptr); - -#ifdef DMQ_ALLOCATOR_SAFEGUARDS - dmq::BlockHeader* pHeader = (dmq::BlockHeader*)blockPtr; - pHeader->magic = XALLOC_FREED; -#endif - - dmq::get_mutex().lock(); - allocator->Deallocate(blockPtr); - dmq::get_mutex().unlock(); -} - -/// Reallocates a memory block previously allocated with xalloc. -/// @param[in] ptr - a pointer to a block created with xalloc. -/// @param[in] size - the client requested block size to create. -extern "C" void *xrealloc(void *oldMem, size_t size) -{ - if (oldMem == 0) - return xmalloc(size); - - if (size == 0) - { - xfree(oldMem); - return 0; - } - else - { - // Create a new memory block - void* newMem = xmalloc(size); - if (newMem != 0) - { - // Get the original allocator instance from the old memory block - dmq::Allocator* oldAllocator = dmq::get_block_allocator(oldMem); - size_t oldSize = oldAllocator->GetBlockSize() - dmq::BLOCK_HEADER_SIZE - dmq::BLOCK_FOOTER_SIZE; - - // Copy the bytes from the old memory block into the new (as much as will fit) - memcpy(newMem, oldMem, (oldSize < size) ? oldSize : size); - - // Free the old memory block - xfree(oldMem); - - // Return the client pointer to the new memory block - return newMem; - } - return 0; - } -} - -/// Output xallocator usage statistics -extern "C" void xalloc_stats() -{ - dmq::get_mutex().lock(); - - for (int i=0; iGetName() != NULL) - std::cout << dmq::_allocators[i]->GetName(); - std::cout << " Block Size: " << dmq::_allocators[i]->GetBlockSize(); - std::cout << " Block Count: " << dmq::_allocators[i]->GetBlockCount(); - std::cout << " Blocks In Use: " << dmq::_allocators[i]->GetBlocksInUse(); - std::cout << std::endl; - } - - dmq::get_mutex().unlock(); -} - -#endif // DMQ_ALLOCATOR diff --git a/DelegateMQ/extras/allocator/xallocator.h b/DelegateMQ/extras/allocator/xallocator.h deleted file mode 100644 index 495e3c6..0000000 --- a/DelegateMQ/extras/allocator/xallocator.h +++ /dev/null @@ -1,153 +0,0 @@ -#ifndef _XALLOCATOR_H -#define _XALLOCATOR_H - -#include -#include -#include - -// @see https://github.com/endurodave/xallocator -// David Lafreniere - -#ifdef __cplusplus -// Define AUTOMATIC_XALLOCATOR_INIT_DESTROY to automatically call xalloc_init() and -// xalloc_destroy() when using xallocator in C++ projects. On embedded systems that -// never exit, you can save 1-byte of RAM storage per translation unit by undefining -// AUTOMATIC_XALLOCATOR_INIT_DESTROY and calling xalloc_init() manually before the OS -// starts. -#define AUTOMATIC_XALLOCATOR_INIT_DESTROY -#ifdef AUTOMATIC_XALLOCATOR_INIT_DESTROY -/// If a C++ translation unit, create a static instance of XallocInitDestroy. Any C++ -/// file including xallocator.h will have the xallocDestroy instance declared first -/// within the translation unit and thus will be constructed first. Destruction -/// will occur in the reverse order so xallocInitDestroy is called last. This way, -/// any static user objects relying on xallocator will be destroyed first before -/// xalloc_destroy() is called. -/// Embedded systems that never exit can remove the XallocInitDestroy class entirely. -namespace dmq { -class XallocInitDestroy -{ -public: - XallocInitDestroy(); - ~XallocInitDestroy(); -private: - static std::atomic refCount; -}; -} // namespace dmq -static dmq::XallocInitDestroy xallocInitDestroy; -#endif // AUTOMATIC_XALLOCATOR_INIT_DESTROY -#endif // __cplusplus - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef DMQ_ALLOCATOR_SAFEGUARDS -#define XALLOC_BLOCK_HEADER_SIZE 16 -#define XALLOC_BLOCK_FOOTER_SIZE 4 -#define XALLOC_MAGIC 0x414C4C4F // "ALLO" -#define XALLOC_FREED 0xDEADBEEF -#define XALLOC_CANARY 0xAA55AA55 -#else -#define XALLOC_BLOCK_HEADER_SIZE (sizeof(void*) > 4 ? 16 : 8) -#define XALLOC_BLOCK_FOOTER_SIZE 0 -#endif - -/// Forward declaration of Allocator class -#ifdef __cplusplus -namespace dmq { - class Allocator; -} -#endif - -/// This function must be called exactly one time before the operating system -/// threading starts. If using xallocator exclusively in C files within your application -/// code, you must call this function before the OS starts. If using C++, client code -/// does not call xalloc_init. Let XallocInitDestroy() call xalloc_init automatically. -/// Embedded systems that never exit can call xalloc_init() manually at startup -/// and eliminate XallocInitDestroy usage. When the system is still single threaded at -/// startup, the xallocator API does not need mutex protection. -void xalloc_init(); - -/// This function must be called once when the application exits. Never call xalloc_destroy() -/// manually except if using xallocator in a C-only application. If using xallocator -/// exclusively in C files within your application code, you must call this function before -/// the program exits. If using C++, ~XallocInitDestroy() must call xalloc_destroy automatically. -/// Embedded systems that never exit need not call this function at all. -void xalloc_destroy(); - -/// Get an Allocator instance based upon the client's requested block size. -/// @param[in] size - the client's requested block size. -/// @return An Allocator instance that handles blocks of the requested size. -#ifdef __cplusplus -dmq::Allocator* xallocator_get_allocator(size_t size); -#endif - -/// Allocate a block of memory -/// @param[in] size - the size of the block to allocate. -void *xmalloc(size_t size); - -/// Frees a previously xalloc allocated block -/// @param[in] ptr - a pointer to a previously allocated memory using xalloc. -void xfree(void* ptr); - -/// Reallocates an existing xalloc block to a new size -/// @param[in] ptr - a pointer to a previously allocated memory using xalloc. -/// @param[in] size - the size of the new block -void *xrealloc(void *ptr, size_t size); - -/// Output allocator statistics to the standard output -void xalloc_stats(); - -#ifdef DMQ_ALLOCATOR - // Macro to overload new/delete with xalloc/xfree. Add macro to any class to enable - // fixed-block memory allocation. Add to a base class provides fixed-block memory - // for the base and all derived classes. - // - // While std::make_shared is usually recommended for standard C++, in a fixed-block - // memory architecture, explicit 'new' is required to trigger the overloaded operator. - // - // Example: - // class MyMsg { - // XALLOCATOR - // }; - // - // // BAD: Allocates global memory (Bypasses XALLOCATOR) - // auto msg = std::make_shared(); - // - // // GOOD: Allocates fixed-block memory (Uses XALLOCATOR) - // std::shared_ptr msg(new MyMsg()); - #include "delegate/DelegateOpt.h" - #define XALLOCATOR \ - public: \ - void* operator new(size_t size) { \ - void* p = xmalloc(size); \ - if (!p) BAD_ALLOC(); \ - return p; \ - } \ - void* operator new(size_t /*size*/, void* mem) { \ - return mem; \ - } \ - void* operator new(size_t size, const std::nothrow_t& /*nt*/) { \ - return xmalloc(size); \ - } \ - void* operator new[](size_t size) { \ - void* p = xmalloc(size); \ - if (!p) BAD_ALLOC(); \ - return p; \ - } \ - void operator delete(void* pObject) { \ - xfree(pObject); \ - } \ - void operator delete(void* pObject, const std::nothrow_t& /*nt*/) { \ - xfree(pObject); \ - } \ - void operator delete[](void* pData) { \ - xfree(pData); \ - } -#endif - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/DelegateMQ/extras/allocator/xlist.h b/DelegateMQ/extras/allocator/xlist.h deleted file mode 100644 index 04e11de..0000000 --- a/DelegateMQ/extras/allocator/xlist.h +++ /dev/null @@ -1,23 +0,0 @@ -#ifndef _XLIST_H -#define _XLIST_H - -#include "stl_allocator.h" -#include - -namespace dmq { - // xlist uses a fix-block memory allocator - template > - using xlist = std::list; -} - -#if 0 // Deprecated -template > - class xlist - : public std::list<_Ty, _Ax> - { - }; -#endif - -#endif - diff --git a/DelegateMQ/extras/allocator/xmake_shared.h b/DelegateMQ/extras/allocator/xmake_shared.h deleted file mode 100644 index 9c5ce8f..0000000 --- a/DelegateMQ/extras/allocator/xmake_shared.h +++ /dev/null @@ -1,18 +0,0 @@ -#ifndef _XMAKE_SHARED_H -#define _XMAKE_SHARED_H - -#include "stl_allocator.h" -#include -#include - -/// @brief Create a shared_ptr with both the object and control block allocated -/// from the fixed-block pool. -namespace dmq { - template - inline std::shared_ptr xmake_shared(Args&&... args) - { - return std::allocate_shared(stl_allocator(), std::forward(args)...); - } -} - -#endif // _XMAKE_SHARED_H diff --git a/DelegateMQ/extras/allocator/xmap.h b/DelegateMQ/extras/allocator/xmap.h deleted file mode 100644 index 7d99d32..0000000 --- a/DelegateMQ/extras/allocator/xmap.h +++ /dev/null @@ -1,39 +0,0 @@ -#ifndef _XMAP_H -#define _XMAP_H - -#include "stl_allocator.h" -#include - -namespace dmq { - -// xmap uses a fix-block memory allocator -template >> -using xmap = std::map, Alloc>; - -template >> -using xmultimap = std::multimap, Alloc>; - -} // namespace dmq - -#if 0 // Deprecated -template, - class _Alloc = stl_allocator > > - class xmap - : public std::map<_Kty, _Ty, _Pr, _Alloc> - { - }; - -template, - class _Alloc = stl_allocator > > - class xmultimap - : public std::multimap<_Kty, _Ty, _Pr, _Alloc> - { - }; -#endif - -#endif - diff --git a/DelegateMQ/extras/allocator/xnew.h b/DelegateMQ/extras/allocator/xnew.h deleted file mode 100644 index 883c8a2..0000000 --- a/DelegateMQ/extras/allocator/xnew.h +++ /dev/null @@ -1,58 +0,0 @@ -#ifndef _XNEW_H -#define _XNEW_H - -// @see https://github.com/DelegateMQ/DelegateMQ -// David Lafreniere, 2026. - -/// @file xnew.h -/// @brief Fixed-block pool equivalents of operator new / delete. -/// -/// @details -/// xnew(args...) allocates from the xallocator fixed-block pool and -/// constructs T in-place via placement new. xdelete(p) calls the -/// destructor then returns the memory to the pool via xfree(). -/// -/// These are the pool-aware counterparts of new(std::nothrow) / delete -/// for types that do not carry the XALLOCATOR macro (e.g. user argument -/// types copied for async delegates, see store_async_arg()). - -#include "xallocator.h" - -namespace dmq { - /// @brief Allocate and construct T in the fixed-block pool. - /// @return Pointer to the constructed object, or nullptr if xmalloc fails. - template - inline T* xnew(Args&&... args) - { - void* mem = xmalloc(sizeof(T)); - if (!mem) return nullptr; - -#if !defined(__cpp_exceptions) || defined(DMQ_ASSERTS) - // Exceptions unavailable/disabled: T's constructor is assumed not to throw. - return ::new(mem) T(std::forward(args)...); -#else - try { - return ::new(mem) T(std::forward(args)...); - } - catch (...) { - // Return the block to the pool before propagating -- otherwise a - // throwing T constructor permanently leaks a fixed-block-pool slot. - xfree(mem); - throw; - } -#endif - } - - /// @brief Destroy T and return its memory to the fixed-block pool. - template - inline void xdelete(T* p) - { - if (p) - { - p->~T(); - xfree(const_cast(static_cast(p))); - } - } -} - -#endif // _XNEW_H diff --git a/DelegateMQ/extras/allocator/xqueue.h b/DelegateMQ/extras/allocator/xqueue.h deleted file mode 100644 index 9936194..0000000 --- a/DelegateMQ/extras/allocator/xqueue.h +++ /dev/null @@ -1,26 +0,0 @@ -#ifndef _XQUEUE_H -#define _XQUEUE_H - -#include "stl_allocator.h" -#include -#include - -namespace dmq { - -// xqueue uses a fix-block memory allocator -template > -using xqueue = std::queue>; - -} // namespace dmq - -#if 0 // Deprecated -template > > - class xqueue - : public std::queue<_Tp, _Sequence> - { - }; -#endif - -#endif - diff --git a/DelegateMQ/extras/allocator/xset.h b/DelegateMQ/extras/allocator/xset.h deleted file mode 100644 index dd42340..0000000 --- a/DelegateMQ/extras/allocator/xset.h +++ /dev/null @@ -1,37 +0,0 @@ -#ifndef _XSET_H -#define _XSET_H - -#include "stl_allocator.h" -#include - -namespace dmq { - -// xset uses a fix-block memory allocator -template , typename Alloc = stl_allocator> -using xset = std::set; - -template , typename Alloc = stl_allocator> -using xmultiset = std::multiset; - -} // namespace dmq - -#if 0 // Deprecated -template, - class _Alloc = stl_allocator<_Kty> > - class xset - : public std::set<_Kty, _Pr, _Alloc> - { - }; - -/// @see xset -template, - class _Alloc = stl_allocator<_Kty> > - class xmultiset - : public std::multiset<_Kty, _Pr, _Alloc> - { - }; -#endif - -#endif diff --git a/DelegateMQ/extras/allocator/xsstream.h b/DelegateMQ/extras/allocator/xsstream.h deleted file mode 100644 index 83467a7..0000000 --- a/DelegateMQ/extras/allocator/xsstream.h +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef _XSSTREAM_H -#define _XSSTREAM_H - -#include "stl_allocator.h" -#include - -// std::string::traits_type, not std::char_traits: GCC with libc++ 17+ -// warns on naming std::char_traits (its primary template is deprecated). -namespace dmq { - typedef std::basic_stringstream > xstringstream; - typedef std::basic_ostringstream > xostringstream; -} -// xwstringstream/xwostringstream are unused by DelegateMQ. Uncomment if wide string support is needed by the application. -// typedef std::basic_stringstream > xwstringstream; -// typedef std::basic_ostringstream > xwostringstream; - - -#endif - diff --git a/DelegateMQ/extras/allocator/xstring.h b/DelegateMQ/extras/allocator/xstring.h deleted file mode 100644 index 31b7e36..0000000 --- a/DelegateMQ/extras/allocator/xstring.h +++ /dev/null @@ -1,16 +0,0 @@ -#ifndef _XSTRING_H -#define _XSTRING_H - -#include "stl_allocator.h" -#include - -// std::string::traits_type, not std::char_traits: GCC with libc++ 17+ -// warns on naming std::char_traits (its primary template is deprecated). -namespace dmq { - typedef std::basic_string > xstring; -} -// xwstring is unused by DelegateMQ. Uncomment if wide string support is needed by the application. -// typedef std::basic_string > xwstring; - -#endif - diff --git a/DelegateMQ/extras/databus/DataBus.h b/DelegateMQ/extras/databus/DataBus.h deleted file mode 100644 index 93a8227..0000000 --- a/DelegateMQ/extras/databus/DataBus.h +++ /dev/null @@ -1,903 +0,0 @@ -#ifndef DMQ_DATABUS_H -#define DMQ_DATABUS_H - -/// @file -/// @brief Publish/subscribe message bus built on top of DelegateMQ's Signal -/// and remote delegate infrastructure. Routes typed topics to local -/// subscribers and, via Participant, to remote nodes. -/// -/// @details -/// `DataBus` is a process-wide singleton: components publish and subscribe by -/// topic string rather than holding direct references to each other. A topic's -/// C++ type is fixed by its first use and enforced afterward (see -/// `DataBus::SubscribeError`'s `ERR_TYPE_MISMATCH`). -/// -/// @code -/// auto conn = dmq::databus::DataBus::Subscribe( -/// "sensor/temperature", -/// [](const TemperatureMsg& msg) { /* handle it */ }); -/// -/// dmq::databus::DataBus::Publish("sensor/temperature", msg); -/// @endcode -/// -/// To span multiple processes/machines, see `NetworkNode` (this directory) -/// or manually wire a `Participant` — either way, see `docs/DATABUS.md` for -/// the full guide and `extras/databus/README.md` for a quickstart. - -#include "delegate/Signal.h" -#include "delegate/DelegateRemote.h" -#include "delegate/DelegateAsync.h" -#include "delegate/IThread.h" -#include "delegate/DelegateOpt.h" -#include "Participant.h" -#include "DataBusQos.h" -#include "SpyPacket.h" -#include "extras/util/Fault.h" -#include "extras/util/NetworkConnect.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace dmq::databus { - -namespace detail { - // Helper class to implement QoS rate limiting without lambda captures. - template - class RateLimiter { - XALLOCATOR - public: - RateLimiter(dmq::UnicastDelegate func, uint32_t minSepRep) - : m_func(std::move(func)), m_minSepRep(minSepRep), m_lastDeliveryRep(0) {} - - void Invoke(const T& data) { - auto nowRep = static_cast(std::chrono::duration_cast(dmq::Clock::now().time_since_epoch()).count()); - auto lastRep = m_lastDeliveryRep.load(std::memory_order_relaxed); - if (nowRep - lastRep >= m_minSepRep) { - m_lastDeliveryRep.store(nowRep, std::memory_order_relaxed); - m_func(data); - } - } - - private: - dmq::UnicastDelegate m_func; - uint32_t m_minSepRep; - std::atomic m_lastDeliveryRep; - }; - - // Helper class to implement QoS filtering without heavy lambda captures. - template - class Filter { - XALLOCATOR - public: - Filter(dmq::UnicastDelegate func, dmq::UnicastDelegate predicate) - : m_func(std::move(func)), m_predicate(std::move(predicate)) {} - - void Invoke(const T& data) { - if (m_predicate(data)) { - m_func(data); - } - } - - private: - dmq::UnicastDelegate m_func; - dmq::UnicastDelegate m_predicate; - }; - - // Holds an async subscriber's delegate for the life of its subscription. - // - // An async subscription is connected as a DelegateMemberAsync holding a - // shared_ptr to this holder. Every publish clones that delegate to queue the - // call; the clone copies only the shared_ptr. The subscriber used to be - // wrapped in a std::function (DelegateFunctionAsync) instead, and each clone - // then copied the std::function. libstdc++ (and libc++) keep a callable - // inline only if it's trivially copyable, which UnicastDelegate isn't, so on - // GCC/Clang toolchains every publish to an async subscriber made a global - // heap allocation outside DMQ_ALLOCATOR. MSVC kept it inline, which hid it. - // - // The holder is allocated once per subscription (xmake_shared). Every clone - // runs on the subscriber's own thread, so calls through it are sequential. - template - class AsyncSubscriber { - XALLOCATOR - public: - explicit AsyncSubscriber(dmq::UnicastDelegate func) - : m_func(std::move(func)) {} - - void Invoke(const Arg& data) { m_func(data); } - - private: - dmq::UnicastDelegate m_func; - }; - - // Build the async delegate for a subscriber on `thread` (see AsyncSubscriber). - template - dmq::DelegateMemberAsync, void(const Arg&)> - MakeAsyncSubscriber(dmq::UnicastDelegate func, dmq::IThread& thread) { - auto holder = dmq::xmake_shared>(std::move(func)); - return dmq::DelegateMemberAsync, void(const Arg&)>( - holder, &AsyncSubscriber::Invoke, thread); - } - -} - -// The DataBus is a central registry for topic-based communication. -// It allows components to publish and subscribe to data topics identified by strings. -// -// LIFETIME NOTE: This class assumes that any external ISerializer or ITransport objects -// passed to it (e.g., via AddParticipant or RegisterSerializer) will outlive -// the DataBus instance or its Reset() calls. -class DataBus { -public: - /// @brief Subscribe to a topic, with optional thread dispatch and QoS. - /// @tparam T Message type published to this topic. Must match the type - /// used by every other Publish/Subscribe/RegisterSerializer - /// call on the same topic string, or DataBus::SubscribeError - /// reports ERR_TYPE_MISMATCH. - /// @tparam F Callable type — a lambda, function pointer, member delegate, - /// or UnicastDelegate. Deduced from `func`. - /// @param topic Topic string to subscribe to. - /// @param func Called with each delivered T. Accepts any callable matching - /// void(const T&). - /// @param thread Optional. If non-null, `func` is dispatched asynchronously - /// on this thread instead of firing synchronously on the - /// publisher's thread. - /// @param qos Optional quality-of-service settings (e.g. last-value - /// cache, rate limiting). Defaults to no special behavior. - /// @return A ScopedConnection owning the subscription. [[nodiscard]] — - /// letting it go out of scope immediately unsubscribes with no - /// callbacks ever firing. Store it in a member variable or - /// container for as long as the subscription should stay active. - /// @note Signal connection is established before LVC delivery to ensure - /// no messages are missed. - /// @note Unsubscribing does not wait for a delivery already in progress on - /// a publisher's thread, and a message already queued on `thread` still - /// runs. If `func` captures an object, guard its lifetime before destroying - /// it right after unsubscribing (see the note in Signal.h). - template - [[nodiscard]] static dmq::ScopedConnection Subscribe(const dmq::xstring& topic, F&& func, dmq::IThread* thread = nullptr, QoS qos = {}) { - dmq::UnicastDelegate typedFunc; - if constexpr (std::is_base_of_v, std::decay_t>) - typedFunc = std::forward(func); // pre-formed delegate — direct assignment, no std::function - else - typedFunc = dmq::DelegateFunction(std::forward(func)); // bridge callable → const T& signature - return GetInstance().InternalSubscribe(topic, std::move(typedFunc), thread, qos); - } - - /// @brief Subscribe to a topic, but only receive deliveries for which - /// `predicate` returns true — messages that fail the predicate are - /// dropped before reaching `func`, without disconnecting the subscription. - /// @tparam T Message type published to this topic. Must match the - /// type used by every other Publish/Subscribe/ - /// RegisterSerializer call on the same topic string, or - /// DataBus::SubscribeError reports ERR_TYPE_MISMATCH. - /// @tparam F Callable type for `func` — a lambda, function pointer, - /// member delegate, or UnicastDelegate. - /// Deduced from `func`. - /// @tparam P Callable type for `predicate` — a lambda, function - /// pointer, member delegate, or - /// UnicastDelegate. Deduced from - /// `predicate`. - /// @param topic Topic string to subscribe to. - /// @param func Called with each delivered T for which `predicate` - /// returned true. Accepts any callable matching - /// void(const T&). - /// @param predicate Evaluated for every delivery on this topic, before - /// `func`. Accepts any callable matching - /// bool(const T&); returning false silently skips that - /// delivery. - /// @param thread Optional. `predicate` and `func` are evaluated - /// together as one unit: with no `thread`, both run - /// synchronously on the publisher's thread; with a - /// `thread`, both are dispatched there together instead. - /// @param qos Optional quality-of-service settings (e.g. last-value - /// cache, rate limiting). Defaults to no special - /// behavior. - /// @return A ScopedConnection owning the subscription. [[nodiscard]] — - /// letting it go out of scope immediately unsubscribes with no - /// callbacks ever firing. Store it in a member variable or - /// container for as long as the subscription should stay active. - template - [[nodiscard]] static dmq::ScopedConnection SubscribeFilter(const dmq::xstring& topic, F&& func, P&& predicate, dmq::IThread* thread = nullptr, QoS qos = {}) { - dmq::UnicastDelegate funcUD; - if constexpr (std::is_base_of_v, std::decay_t>) - funcUD = std::forward(func); - else - funcUD = dmq::DelegateFunction(std::forward(func)); - - dmq::UnicastDelegate predUD; - if constexpr (std::is_base_of_v, std::decay_t

>) - predUD = std::forward

(predicate); - else - predUD = dmq::DelegateFunction(std::forward

(predicate)); - - auto filter = dmq::xmake_shared>(std::move(funcUD), std::move(predUD)); - // DelegateMember holds the shared_ptr strongly, so the Filter lives as long as the - // connection. No lambda: wrapping one that captures a shared_ptr in a std::function - // heap-allocates on GCC/Clang (not trivially copyable), see detail::AsyncSubscriber. - return GetInstance().InternalSubscribe(topic, - dmq::DelegateMember, void(const T&)>(std::move(filter), &detail::Filter::Invoke), - thread, qos); - } - - /// @brief Publish data to a topic — delivered to every local subscriber - /// (synchronously, or asynchronously if they registered with a thread), - /// then forwarded to any remote participants interested in this topic. - /// @tparam T Message type. Must match every other Publish/Subscribe/ - /// RegisterSerializer call on this topic string. - /// @param topic Topic string to publish to. - /// @param data The message payload, copied to each subscriber/participant. - template - static void Publish(const dmq::xstring& topic, const T& data) { - GetInstance().InternalPublish(topic, data, false); - } - - /// @brief Publish data to local subscribers only — does NOT forward to - /// remote participants. - /// @tparam T Message type. Must match every other Publish/Subscribe/ - /// RegisterSerializer call on this topic string. - /// @param topic Topic string to publish to. - /// @param data The message payload, copied to each local subscriber. - /// @note Used by AddIncomingTopic to prevent relay loops when a topic is - /// both incoming and outgoing on the same node. - template - static void PublishLocal(const dmq::xstring& topic, const T& data) { - GetInstance().InternalPublish(topic, data, true); - } - - // Add a remote participant to the bus. - static void AddParticipant(std::shared_ptr participant) { - GetInstance().InternalAddParticipant(participant); - } - - static void RemoveParticipant(std::shared_ptr participant) { - GetInstance().InternalRemoveParticipant(participant); - } - - // Register a serializer for a topic (required for remote distribution). - // Use this overload if the serializer is a long-lived object (e.g., static or - // global). The DataBus does NOT take ownership. - template - static void RegisterSerializer(const dmq::xstring& topic, dmq::ISerializer& serializer) { - auto shared = std::shared_ptr(&serializer, [](void*) {}, ::dmq::stl_allocator()); - GetInstance().InternalRegisterSerializer(topic, std::move(shared)); - } - - // Register a serializer for a topic with ownership. - // Use this overload to allow the DataBus to manage the serializer's lifetime - // through a shared_ptr. - template - static void RegisterSerializer(const dmq::xstring& topic, std::shared_ptr> serializer) { - GetInstance().InternalRegisterSerializer(topic, std::static_pointer_cast(serializer)); - } - - // Register an incoming remote topic and republish received data to the local bus only. - // Uses PublishLocal — the message reaches local subscribers, the spy, and the LVC, but is - // NOT re-forwarded to remote participants. This prevents relay loops when the same topic - // is registered as both incoming and outgoing on the same node. - // - // For bridge/relay nodes that must forward incoming data to other remote participants, - // use AddRelayTopic instead. - template - static void AddIncomingTopic(const dmq::xstring& topic, dmq::DelegateRemoteId remoteId, Participant& participant, dmq::ISerializer& serializer) { - participant.RegisterHandler(remoteId, serializer, [topic](const T& data) { - PublishLocal(topic, data); - }); - } - - // Register an incoming remote topic and re-publish received data to ALL local subscribers - // AND all registered remote participants (full Publish). Use this only on bridge/relay nodes - // where the explicit intent is to forward incoming data to other remote nodes. - // - // The relay forwards only to participants that already list the topic as outgoing - // (AddRemoteTopic on the downstream participants, plus RegisterSerializer). The inbound - // participant is NOT made outgoing for the topic, so on a duplex link (one participant - // that both receives and is registered with AddParticipant) relayed data is not echoed - // back out the link it arrived on. - // - // WARNING: Using AddRelayTopic on a node that also has the same topic as an outgoing - // (RegisterSerializer + AddParticipant) AND receives from a node that also relays will - // create an infinite relay loop. Use AddIncomingTopic instead for subscriber-only nodes. - template - static void AddRelayTopic(const dmq::xstring& topic, dmq::DelegateRemoteId remoteId, Participant& participant, dmq::ISerializer& serializer) { - participant.RegisterHandler(remoteId, serializer, [topic](const T& data) { - Publish(topic, data); - }); - } - - // Register a stringifier for a topic to enable spying/logging. - template - static void RegisterStringifier(const dmq::xstring& topic, F&& func) { - dmq::UnicastDelegate ud; - if constexpr (std::is_base_of_v, std::decay_t>) - ud = std::forward(func); - else - ud = dmq::DelegateFunction(std::forward(func)); - GetInstance().InternalRegisterStringifier(topic, std::move(ud)); - } - - // Enable/Disable Last Value Cache (LVC) for a topic. - static void LastValueCache(const dmq::xstring& topic, bool enabled) { - GetInstance().InternalLastValueCache(topic, enabled); - } - - // Subscribe to all bus traffic (topic and stringified value). - // NOTE: priority is only applied when thread != nullptr; passing a non-default - // priority without a thread is a programming error and triggers FaultHandler. - template - [[nodiscard]] static dmq::ScopedConnection Monitor(F&& func, dmq::IThread* thread = nullptr, dmq::Priority priority = dmq::Priority::NORMAL) { - DMQ_ASSERT_TRUE(thread || priority == dmq::Priority::NORMAL); - - dmq::UnicastDelegate ud; - if constexpr (std::is_base_of_v, std::decay_t>) - ud = std::forward(func); - else - ud = dmq::DelegateFunction(std::forward(func)); - - DataBus& instance = GetInstance(); - - // Establish connection OUTSIDE the global DataBus lock to prevent - // lock inversion deadlocks. Signal::Connect() is already thread-safe. - if (thread) { - auto del = detail::MakeAsyncSubscriber(std::move(ud), *thread); // see detail::AsyncSubscriber - del.SetPriority(priority); - return instance.m_monitorSignal.Connect(std::move(del)); - } else { - return instance.m_monitorSignal.Connect(std::move(ud)); - } - } - - /// Fired when a message is published but has no local or remote subscribers. - template - [[nodiscard]] static dmq::ScopedConnection SubscribeUnhandled(F&& func) { - dmq::UnicastDelegate ud; - if constexpr (std::is_base_of_v, std::decay_t>) - ud = std::forward(func); - else - ud = dmq::DelegateFunction(std::forward(func)); - return GetInstance().m_unhandledSignal.Connect(std::move(ud)); - } - - /// Fired when a message is published but a technical error occurs (e.g. serialization failure). - template - [[nodiscard]] static dmq::ScopedConnection SubscribeError(F&& func) { - dmq::UnicastDelegate ud; - if constexpr (std::is_base_of_v, std::decay_t>) - ud = std::forward(func); - else - ud = dmq::DelegateFunction(std::forward(func)); - return GetInstance().m_errorSignal.Connect(std::move(ud)); - } - - // Reset the DataBus (mostly for testing). - static void ResetForTesting() { - GetInstance().InternalReset(); - } - - // Enable or disable continuous error mode (disables error latching). - static void EnableContinuousErrors(bool enable) { - GetInstance().InternalEnableContinuousErrors(enable); - } - -private: - void InternalEnableContinuousErrors(bool enable) { - dmq::LockGuard lock(m_mutex); - m_continuousErrors = enable; - for (size_t i = 0; i < m_participantCount; ++i) { - if (m_participants[i]) { - m_participants[i]->EnableContinuousErrors(enable); - } - } - } - - void InternalReportLatchedError(const dmq::xstring& topic, dmq::DelegateError error) { - bool shouldFire = false; - { - dmq::LockGuard lock(m_mutex); - uint16_t bit = uint16_t(1u << static_cast(error)); - auto& bits = m_reportedErrors[topic]; - if (!(bits & bit)) { - bits |= bit; - shouldFire = true; - } else if (m_continuousErrors) { - shouldFire = true; - } - } - if (shouldFire) { - m_errorSignal(topic, error); - } - } - - void InternalReportError(const dmq::xstring& topic, dmq::DelegateError error) { - m_errorSignal(topic, error); - } - - void InternalLastValueCache(const dmq::xstring& topic, bool enabled) { - dmq::LockGuard lock(m_mutex); - m_topicQos[topic].lastValueCache = enabled; - } - - DataBus() = default; - ~DataBus() = default; - - DataBus(const DataBus&) = delete; - DataBus& operator=(const DataBus&) = delete; - - static DataBus& GetInstance() { - static DataBus instance; - return instance; - } - - template - using SignalPtr = std::shared_ptr>; - - template - [[nodiscard]] dmq::ScopedConnection InternalSubscribe(const dmq::xstring& topic, dmq::UnicastDelegate typedFunc, dmq::IThread* thread, QoS qos) { - SignalPtr signal; - - // Wrap with min separation rate limiter if requested. Each subscriber gets its - // own independent last-delivery timestamp, so different subscribers on the same - // topic can have different (or no) rate limits without affecting each other. - if (qos.minSeparation.has_value()) { - auto minSepRep = static_cast(std::chrono::duration_cast(qos.minSeparation.value()).count()); - auto limiter = dmq::xmake_shared>(std::move(typedFunc), minSepRep); - // DelegateMember holds the shared_ptr strongly (not MakeDelegate(limiter.get(), ...), - // which would store a raw pointer), so the RateLimiter lives as long as the - // connection. No lambda/std::function, as for the Filter above. - typedFunc = dmq::DelegateMember, void(const T&)>( - std::move(limiter), &detail::RateLimiter::Invoke); - } - - T* cachedValPtr = nullptr; - std::optional cachedVal; - dmq::ScopedConnection conn; - - { - dmq::LockGuard lock(m_mutex); - - // 1. Enable LVC if requested (persists for topic lifetime until ResetForTesting) - if (qos.lastValueCache) { - m_topicQos[topic].lastValueCache = true; - } - - // 2. Get or create signal with type safety check (std::type_index) - signal = GetOrCreateSignal(topic); - } - - if (!signal) { - // Type mismatch: report through the error signal for diagnosability, - // then hard fault (wrong type is an invariant violation). - InternalReportLatchedError(topic, dmq::DelegateError::ERR_TYPE_MISMATCH); - DMQ_ASSERT(); - return {}; - } - - // 3. Establish connection OUTSIDE the lock to prevent deadlock with Timer/Signal locks. - // NOTE: There is a theoretical race where a publish happens between releasing the - // DataBus lock and acquiring the Signal lock. However, both use RecursiveMutex - // and InternalPublish also snapshots signals outside its lock, so this is - // architecturally consistent with the "lock-free dispatch" pattern used elsewhere. - using AsyncDelType = dmq::DelegateMemberAsync, void(const T&)>; - std::optional asyncDel; - if (thread) { - // No std::function here: see detail::AsyncSubscriber. - asyncDel.emplace(detail::MakeAsyncSubscriber(std::move(typedFunc), *thread)); - conn = signal->Connect(*asyncDel); - } else { - conn = signal->Connect(typedFunc); - } - - { - dmq::LockGuard lock(m_mutex); - // 4. Prepare LVC delivery if enabled and available - if (qos.lastValueCache) { - auto it = m_lastValues.find(topic); - if (it != m_lastValues.end()) { - // Check lifespan: skip delivery if the cached value is too old - bool expired = false; - if (qos.lifespan.has_value()) { - auto age = dmq::Clock::now() - it->second.timestamp; - expired = (age > qos.lifespan.value()); - } - if (!expired) { - cachedVal.emplace(*std::static_pointer_cast(it->second.value)); - cachedValPtr = &cachedVal.value(); - } - } - } - } - - // 5. Dispatch LVC outside the lock to prevent deadlocks. - // IMPORTANT: Because this happens after releasing the lock, a high-frequency - // publisher on another thread could have already sent a new value to the - // connected signal. The subscriber might receive the fresh value FIRST, - // followed by this stale LVC value — a "rewind" to an older state. - // - // Recommended mitigation: embed a monotonic sequence number in every message - // (see MessageBase) and reject stale arrivals in the subscriber using - // dmq::util::MonotonicGuard::IsNewer(). This is an application-level guard - // and is the correct fix — resolving the race inside the DataBus lock would - // require holding the lock across the async dispatch, which deadlocks. - if (cachedValPtr) { - if (asyncDel) - asyncDel->AsyncInvoke(*cachedValPtr); - else - typedFunc(*cachedValPtr); - } - - return conn; - } - - template - void InternalPublish(const dmq::xstring& topic, const T& data, bool localOnly) { - // Capture timestamp before lock acquisition for maximum accuracy and - // monotonic ordering using dmq::Clock. - auto now = dmq::Clock::now(); - uint64_t timestamp = std::chrono::duration_cast(now.time_since_epoch()).count(); - - std::shared_ptr signalVoid; - std::shared_ptr serializerPtr; - dmq::ISerializer* serializer = nullptr; - std::array, dmq::MAX_PARTICIPANTS> participantsSnapshot; - size_t participantSnapshotCount = 0; - dmq::xstring strVal = "?"; - bool hasMonitor = false; - - bool typeMismatch; - { - dmq::LockGuard lock(m_mutex); - - // 1. Type safety: verify T matches the registered type for this topic. - // Must be first — before any writes — so a mismatch never corrupts LVC. - // Also establishes the topic's type on first use (mirrors GetOrCreateSignal - // and the serializer registration paths). Without this, a topic that's - // never been subscribed to or serializer-registered would let a later - // Publish with a different U reach the LVC reuse block below and - // reinterpret a live T object as U. - typeMismatch = CheckOrEstablishType(topic, std::type_index(typeid(T))); - - if (!typeMismatch) { - // 2. Update LVC ONLY if enabled for this topic to save memory. - // NOTE: QoS lastValueCache is currently "sticky" per topic. Once enabled - // by any subscriber, it remains active for that topic until ResetForTesting(). - if (IsLvcEnabledLocked(topic)) { - if (LvcEntry* entry = FindLvcEntryLocked(topic)) { - // Avoid hot-path allocation: reuse the existing memory block by - // destroying and copy-constructing in place, rather than - // copy-assigning. This only requires T to be copy-constructible - // (the same requirement as every other T published through - // DataBus) instead of also requiring T to be copy-assignable. - // The copy is built on the stack first so that if T's copy - // constructor throws, the cached slot is untouched rather than - // left destroyed with nothing reconstructed in its place. - T* cachedObj = static_cast(entry->value.get()); - T replacement(data); - cachedObj->~T(); -#if !defined(__cpp_exceptions) || defined(DMQ_ASSERTS) - ::new (static_cast(cachedObj)) T(std::move(replacement)); -#else - try { - ::new (static_cast(cachedObj)) T(std::move(replacement)); - } - catch (...) { - // The move constructor threw, leaving cachedObj's memory - // destroyed with no live object in it -- but the shared_ptr - // from xmake_shared still expects to destroy a live T at - // this address whenever the entry is later replaced or the - // topic is reset/torn down. Reconstruct a valid object in - // place from a fresh copy of `data` (T is already required - // to be copy-constructible for use with DataBus) so that - // invariant holds again, then propagate the original - // exception to the caller. - try { - ::new (static_cast(cachedObj)) T(data); - } - catch (...) { - // Recovery copy also failed: the slot cannot be safely - // restored to a valid state. This is an unrecoverable - // invariant violation, not a normal operational error. - DMQ_ASSERT(); - } - throw; - } -#endif - entry->timestamp = now; - } else { - // First publish for this topic: perform the initial allocation - StoreLvcEntryLocked(topic, dmq::xmake_shared(data), now); - } - } - - // 3. Prepare monitor data - hasMonitor = HasMonitorLocked(); - if (hasMonitor) { - if (auto strf = FindStringifierLocked(topic)) { - auto func = static_cast*>(strf.get()); - strVal = (*func)(data); - } - } - - // 4. Get signal and remote info. Only create Signal if there is local interest. - signalVoid = FindSignalLocked(topic); - - serializerPtr = FindSerializerLocked(topic); - if (serializerPtr) { - serializer = static_cast*>(serializerPtr.get()); - } - - // 5. Snapshot participants while locked to ensure atomicity between - // local and remote dispatch sets. - participantSnapshotCount = SnapshotParticipantsLocked(participantsSnapshot); - } - } - - if (typeMismatch) { - InternalReportLatchedError(topic, dmq::DelegateError::ERR_TYPE_MISMATCH); - DMQ_ASSERT(); - return; - } - - // 6. Dispatch Monitor outside lock to allow re-entry/prevent deadlocks - if (hasMonitor) { - DispatchMonitor(topic, strVal, timestamp); - } - - // 7. Local distribution - bool handled = false; - if (signalVoid) { - auto signal = std::static_pointer_cast>(signalVoid); - (*signal)(data); - handled = true; - } - - // 8. Remote distribution using the snapshot - if (!localOnly) { - bool anyInterested = false; - for (size_t i = 0; i < participantSnapshotCount; ++i) { - if (participantsSnapshot[i]->DispatchIfInterested(topic, data, serializer)) { - anyInterested = true; - } - } - - if (anyInterested) { - if (!serializer) { - // Topic has remote interest but no serializer — fire once per topic. - InternalReportLatchedError(topic, dmq::DelegateError::ERR_NO_SERIALIZER); - } - handled = true; - } - } - - // 9. Notify if no one received the message - if (!handled) { - m_unhandledSignal(topic); - } - } - - void InternalRemoveParticipant(std::shared_ptr participant) { - dmq::LockGuard lock(m_mutex); - for (size_t i = 0; i < m_participantCount; ++i) { - if (m_participants[i] == participant) { - m_participantErrorConnections[i].Disconnect(); - for (size_t j = i; j < m_participantCount - 1; ++j) { - m_participants[j] = std::move(m_participants[j + 1]); - m_participantErrorConnections[j] = std::move(m_participantErrorConnections[j + 1]); - } - --m_participantCount; - m_participants[m_participantCount].reset(); - break; - } - } - } - - void InternalAddParticipant(std::shared_ptr participant) { - // Establish connection OUTSIDE the global DataBus lock to prevent - // lock inversion deadlocks. Signal::Connect() is already thread-safe. - auto conn = participant->SubscribeError( - dmq::MakeDelegate(this, &DataBus::InternalReportLatchedError)); - - dmq::LockGuard lock(m_mutex); - if (m_participantCount >= dmq::MAX_PARTICIPANTS) { - // Report via the error signal for diagnosability, then hard fault — - // same "report, then fault" hybrid as the ERR_TYPE_MISMATCH sites - // above. Recursive mutex allows re-entry into InternalReportLatchedError - // while m_mutex is already held. - InternalReportLatchedError("", dmq::DelegateError::ERR_CAPACITY_EXCEEDED); - DMQ_ASSERT(); - return; - } - m_participantErrorConnections[m_participantCount] = std::move(conn); - participant->EnableContinuousErrors(m_continuousErrors); - m_participants[m_participantCount++] = participant; - } - - template - void InternalRegisterSerializer(const dmq::xstring& topic, std::shared_ptr serializer) { - bool typeMismatch; - { - dmq::LockGuard lock(m_mutex); - typeMismatch = CheckOrEstablishType(topic, std::type_index(typeid(T))); - if (!typeMismatch) { - m_serializers[topic] = std::move(serializer); - } - } - if (typeMismatch) { - InternalReportLatchedError(topic, dmq::DelegateError::ERR_TYPE_MISMATCH); - DMQ_ASSERT(); - } - } - - template - void InternalRegisterStringifier(const dmq::xstring& topic, dmq::UnicastDelegate func) { - bool typeMismatch; - { - dmq::LockGuard lock(m_mutex); - typeMismatch = CheckOrEstablishType(topic, std::type_index(typeid(T))); - if (!typeMismatch) { - // Use shared_ptr with custom deleter and stl_allocator. - // Allocate function object from fixed-block pool using xnew. - using DelegateType = dmq::UnicastDelegate; - m_stringifiers[topic] = std::shared_ptr( - dmq::xnew(std::move(func)), - [](void* ptr) { dmq::xdelete(static_cast(ptr)); }, - ::dmq::stl_allocator() - ); - } - } - if (typeMismatch) { - InternalReportLatchedError(topic, dmq::DelegateError::ERR_TYPE_MISMATCH); - DMQ_ASSERT(); - } - } - - void InternalReset() { - dmq::LockGuard lock(m_mutex); - m_signals.clear(); - for (size_t i = 0; i < m_participantCount; ++i) { - if (m_participants[i]) m_participants[i]->ResetErrors(); - m_participants[i].reset(); - m_participantErrorConnections[i].Disconnect(); - } - m_participantCount = 0; - m_serializers.clear(); - m_lastValues.clear(); - m_topicQos.clear(); - m_stringifiers.clear(); - m_typeIndices.clear(); - m_monitorSignal.Clear(); - m_unhandledSignal.Clear(); - m_errorSignal.Clear(); - m_reportedErrors.clear(); - } - - // Type-instantiated but non-templated-TYPE deleter: &DeleteSignal decays to the - // same void(*)(void*) regardless of T, so the shared_ptr control block built - // from it in GetOrCreateSignal below is not templated on T either. Same trick as - // Participant::DeleteRemoteChannel. - template - static void DeleteSignal(void* p) { - delete static_cast*>(p); - } - - template - SignalPtr GetOrCreateSignal(const dmq::xstring& topic) { - // Assume lock is held by caller - if (CheckOrEstablishType(topic, std::type_index(typeid(T)))) - return nullptr; - - if (auto sig = FindSignalLocked(topic)) { - return std::static_pointer_cast>(sig); - } - - // Erase to void* BEFORE constructing the shared_ptr (rather than - // xmake_shared>) so the control block's deduced - // pointer/deleter types are non-templated -- one control-block type is then - // shared across every distinct topic message type instead of duplicated per - // signature. Signal's own XALLOCATOR-overridden operator new already checks - // for allocation failure and calls BAD_ALLOC() internally (see xallocator.h), - // same as Participant::GetOrCreateChannelLocked's plain `new` for RemoteChannel. - auto* raw = new dmq::Signal(); - std::shared_ptr signalVoid(static_cast(raw), &DeleteSignal, ::dmq::stl_allocator()); - m_signals[topic] = signalVoid; - return std::static_pointer_cast>(signalVoid); - } - - struct LvcEntry { - std::shared_ptr value; - dmq::TimePoint timestamp; - }; - - // --- Non-templated helpers shared by every InternalPublish/InternalRegister*/ - // GetOrCreateSignal instantiation. None of this logic depends on the message - // type -- it operates purely on the already type-erased xmap storage below -- so - // living here as ordinary member functions means it's compiled once for the whole - // program instead of once per distinct topic type. "*Locked" methods assume - // m_mutex is already held by the caller. - - // Look up topic's registered type; if none yet, establish it as `expected`. - // Returns true if topic was already registered with a DIFFERENT type -- a - // programming-error type mismatch the caller must report/DMQ_ASSERT on. - bool CheckOrEstablishType(const dmq::xstring& topic, std::type_index expected) { - auto it = m_typeIndices.find(topic); - if (it != m_typeIndices.end()) - return it->second != expected; - m_typeIndices.emplace(topic, expected); - return false; - } - - bool IsLvcEnabledLocked(const dmq::xstring& topic) const { - auto it = m_topicQos.find(topic); - return it != m_topicQos.end() && it->second.lastValueCache; - } - - // Returns a pointer to topic's existing LVC entry, or nullptr if none exists yet. - // The returned pointer is only valid until the next m_lastValues mutation -- - // callers must use it within the same locked scope it was obtained in. - LvcEntry* FindLvcEntryLocked(const dmq::xstring& topic) { - auto it = m_lastValues.find(topic); - return it != m_lastValues.end() ? &it->second : nullptr; - } - - void StoreLvcEntryLocked(const dmq::xstring& topic, std::shared_ptr value, dmq::TimePoint ts) { - m_lastValues[topic] = LvcEntry{ std::move(value), ts }; - } - - bool HasMonitorLocked() const { return !m_monitorSignal.Empty(); } - - std::shared_ptr FindStringifierLocked(const dmq::xstring& topic) const { - auto it = m_stringifiers.find(topic); - return it != m_stringifiers.end() ? it->second : nullptr; - } - - std::shared_ptr FindSignalLocked(const dmq::xstring& topic) const { - auto it = m_signals.find(topic); - return it != m_signals.end() ? it->second : nullptr; - } - - std::shared_ptr FindSerializerLocked(const dmq::xstring& topic) const { - auto it = m_serializers.find(topic); - return it != m_serializers.end() ? it->second : nullptr; - } - - // Copies the live participant list into `out`, up to m_participantCount entries. - // Called while locked to keep the snapshot atomic with the rest of a publish. - size_t SnapshotParticipantsLocked(std::array, dmq::MAX_PARTICIPANTS>& out) const { - for (size_t i = 0; i < m_participantCount; ++i) - out[i] = m_participants[i]; - return m_participantCount; - } - - // Fires the monitor signal with a freshly-built SpyPacket. Called outside the - // lock, same as the code it replaces. - void DispatchMonitor(const dmq::xstring& topic, const dmq::xstring& strVal, uint64_t timestamp) { - SpyPacket packet{ topic, strVal, timestamp }; - m_monitorSignal(packet); - } - - bool m_continuousErrors = false; - dmq::RecursiveMutex m_mutex; - dmq::xmap m_reportedErrors; - dmq::xmap> m_signals; - dmq::xmap m_typeIndices; - std::array, dmq::MAX_PARTICIPANTS> m_participants{}; - size_t m_participantCount = 0; - dmq::xmap> m_serializers; - dmq::xmap m_lastValues; - dmq::xmap m_topicQos; - dmq::xmap> m_stringifiers; - dmq::Signal m_monitorSignal; - dmq::Signal m_unhandledSignal; - dmq::Signal m_errorSignal; - std::array m_participantErrorConnections; -}; - -} // namespace dmq::databus - - -#endif // DMQ_DATABUS_H diff --git a/DelegateMQ/extras/databus/DataBusQos.h b/DelegateMQ/extras/databus/DataBusQos.h deleted file mode 100644 index 23869e2..0000000 --- a/DelegateMQ/extras/databus/DataBusQos.h +++ /dev/null @@ -1,28 +0,0 @@ -#ifndef DMQ_DATABUSQOS_H -#define DMQ_DATABUSQOS_H - -#include "delegate/DelegateOpt.h" -#include - -namespace dmq::databus { - -// Quality of Service settings for a topic subscription. -struct QoS { - // If true, new subscribers receive the last published value immediately on subscribe. - bool lastValueCache = false; - - // Maximum age of a cached LVC value. If the cached value is older than this duration - // when a new subscriber connects, it is considered stale and not delivered. - // Only meaningful when lastValueCache = true. - std::optional lifespan; - - // Minimum time between deliveries to this subscriber. Publishes that arrive faster - // than this interval are silently dropped for this subscriber only. Other subscribers - // with a different (or no) minSeparation are unaffected. - std::optional minSeparation; -}; - -} // namespace dmq::databus - - -#endif // DMQ_DATABUSQOS_H diff --git a/DelegateMQ/extras/databus/DeadlineSubscription.h b/DelegateMQ/extras/databus/DeadlineSubscription.h deleted file mode 100644 index ec2ebf9..0000000 --- a/DelegateMQ/extras/databus/DeadlineSubscription.h +++ /dev/null @@ -1,149 +0,0 @@ -#ifndef DMQ_DEADLINE_SUBSCRIPTION_H -#define DMQ_DEADLINE_SUBSCRIPTION_H - -/// @file DeadlineSubscription.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// @brief RAII helper that combines a DataBus subscription with a deadline timer. -/// -/// @details -/// `DeadlineSubscription` monitors a DataBus topic and fires a user callback -/// if no message arrives within a configurable deadline window. It is built -/// entirely from existing DelegateMQ primitives — `DataBus::Subscribe`, `Timer`, -/// and `ScopedConnection` — and adds no library-internal mechanism. -/// -/// **How it works:** -/// A `Timer` is started at construction time. Every incoming message resets the -/// timer. If the timer fires before the next message arrives, the `onMissed` -/// callback is invoked. Both the data handler and the deadline callback are -/// dispatched to the same optional worker thread. -/// -/// **Lifetime:** -/// The object is non-copyable and non-movable. All resources — the DataBus -/// connection, the timer expiry connection, and the timer itself — are released -/// automatically when the object is destroyed. Members are destroyed in reverse -/// declaration order, so the DataBus connection disconnects before the timer is -/// torn down. -/// -/// When a `thread` argument is supplied, stop or join that thread before -/// destroying this object. `ScopedConnection` prevents new callbacks from being -/// queued, but any callback already waiting in the thread's message queue will -/// still execute and will access members of this object. This is the same rule -/// that applies to any async delegate that captures a raw pointer. -/// -/// **`Timer::ProcessTimers()` requirement:** -/// The deadline timer fires only when `Timer::ProcessTimers()` is called. On -/// platforms with a running `Thread`, this is typically driven by the thread's -/// internal timer. On bare-metal targets, call `ProcessTimers()` from the main -/// super-loop or a SysTick handler. If `ProcessTimers()` is not called, the -/// deadline callback silently never fires. -/// -/// **`onMissed` callback context:** -/// - With a `thread` argument: the callback is dispatched asynchronously to -/// that thread, matching the delivery context of the data handler. -/// - Without a `thread` argument: the callback fires synchronously on whatever -/// thread calls `Timer::ProcessTimers()`. On bare-metal this may be an ISR — -/// keep the callback short and non-blocking. -/// -/// **Usage:** -/// @code -/// dmq::DeadlineSubscription m_watch{ -/// "sensor/temp", -/// std::chrono::milliseconds(500), -/// [](const SensorData& d) { /* handle data */ }, -/// []() { /* deadline missed — sensor silent */ }, -/// &m_workerThread -/// }; -/// @endcode - -#include "DataBus.h" -#include "extras/util/Timer.h" -#include "delegate/UnicastDelegate.h" -#include - -namespace dmq::databus { - -template -class DeadlineSubscription { - XALLOCATOR -public: - /// Construct a deadline-monitored DataBus subscription. - /// - /// @param topic DataBus topic to subscribe to. - /// @param deadline Maximum allowed interval between deliveries. Must be > 0. - /// @param handler Called on each data delivery. Accepts any callable (lambda, - /// function pointer, member delegate, UnicastDelegate). - /// @param onMissed Called when no delivery arrives within the deadline window. - /// Accepts any callable with signature void(). - /// @param thread Optional worker thread for both callbacks. If nullptr, - /// handler fires on the publisher's thread and onMissed fires - /// on the Timer::ProcessTimers() thread. - template - DeadlineSubscription( - const dmq::xstring& topic, - dmq::Duration deadline, - H&& handler, - M&& onMissed, - dmq::IThread* thread = nullptr) - : m_deadline(deadline) - { - if constexpr (std::is_base_of_v, std::decay_t>) - m_handler = std::forward(handler); - else - m_handler = dmq::DelegateFunction(std::forward(handler)); - - if constexpr (std::is_base_of_v, std::decay_t>) - m_onMissed = std::forward(onMissed); - else - m_onMissed = dmq::DelegateFunction(std::forward(onMissed)); - - // Connect onMissed to the timer expiry signal, dispatching to thread if provided - if (thread) { - m_timerConn = m_timer.OnExpired.Connect( - dmq::util::MakeTimerDelegate(this, &DeadlineSubscription::OnTimerExpired, *thread)); - } else { - m_timerConn = m_timer.OnExpired.Connect( - dmq::MakeDelegate(this, &DeadlineSubscription::OnTimerExpired)); - } - - // Arm the timer immediately. It fires if no delivery arrives within deadline. - m_timer.Start(m_deadline, false); - - // Subscribe and reset the timer on every delivery - m_conn = DataBus::Subscribe(topic, dmq::MakeDelegate(this, &DeadlineSubscription::OnDataReceived), thread); - } - - ~DeadlineSubscription() = default; - - DeadlineSubscription(const DeadlineSubscription&) = delete; - DeadlineSubscription& operator=(const DeadlineSubscription&) = delete; - DeadlineSubscription(DeadlineSubscription&&) = delete; - DeadlineSubscription& operator=(DeadlineSubscription&&) = delete; - -private: - void OnDataReceived(const T& data) { - m_timer.Start(m_deadline, false); // reset deadline window - m_handler(data); - } - - void OnTimerExpired() { - m_onMissed(); - } - - // Declaration order controls destruction order (reverse). - // m_conn disconnects first (no more timer resets via the data lambda), - // then m_timerConn disconnects (onMissed removed from timer signal), - // then m_timer destructs (removed from global timer list). - dmq::Duration m_deadline; - dmq::UnicastDelegate m_handler; - dmq::UnicastDelegate m_onMissed; - dmq::util::Timer m_timer; - dmq::ScopedConnection m_timerConn; - dmq::ScopedConnection m_conn; -}; - -} // namespace dmq::databus - - -#endif // DMQ_DEADLINE_SUBSCRIPTION_H diff --git a/DelegateMQ/extras/databus/NetworkNode.h b/DelegateMQ/extras/databus/NetworkNode.h deleted file mode 100644 index 2628d08..0000000 --- a/DelegateMQ/extras/databus/NetworkNode.h +++ /dev/null @@ -1,527 +0,0 @@ -#ifndef DMQ_NETWORK_NODE_H -#define DMQ_NETWORK_NODE_H - -/// @file NetworkNode.h -/// @brief Generic multi-peer DataBus network node for any ITransport type. -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// @details -/// NetworkNode wraps the full DataBus networking plumbing — transport setup, -/// Participant creation, reliability stacking, receive-loop thread — behind -/// a five-method API. A new user brings up a multi-process distributed DataBus -/// system by writing only a SetupNetwork() function: -/// -/// @code -/// // In your node's System.cpp: -/// void System::SetupNetwork() { -/// m_network.Start("GUI", 5010); -/// -/// m_network.Receive(topics::SAFETY_HB, RID_SAFETY_HB, serHB); -/// m_network.Receive (topics::FAULT, RID_FAULT, serFault); -/// -/// m_network.AddPeer("Safety", "127.0.0.1", 5013); -/// -/// m_network.Send(topics::GUI_HB, RID_GUI_HB, serHB); -/// m_network.Send (topics::FAULT, RID_FAULT, serFault, -/// dmq::databus::Reliability::RELIABLE); -/// } -/// // From here, use DataBus::Subscribe / DataBus::Publish normally. -/// @endcode -/// -/// A node can run several links on its one DataBus, e.g. a NetworkNode to Ethernet -/// peers and a serial link to each MCU. Each link sends only the topics registered -/// on it with Send(). A received topic reaches this node's subscribers only, unless -/// it is received with Delivery::RELAY, which also forwards it out the other links -/// that Send() it. Each peer takes two DataBus participants (reliable and -/// unreliable) out of dmq::MAX_PARTICIPANTS, shared by all links in the process. -/// -/// Topic ordering: Receive() and Send() may be called before or after Start() / -/// AddPeer() in any order. NetworkNode defers registration and applies it -/// retroactively when the participant is created. -/// -/// @tparam Transport Any ITransport-derived class with a nested Type enum -/// providing Type::PUB (sender) and Type::SUB (receiver). -/// @tparam MaxPeers Maximum remote peers (fixed allocation). Defaults to -/// dmq::NETWORK_NODE_MAX_PEERS (DMQ_NETWORK_NODE_MAX_PEERS -/// in delegatemqconfig.h). -/// @tparam MaxTopics Maximum in- or out-topics each (fixed allocation). Defaults -/// to dmq::NETWORK_NODE_MAX_TOPICS (DMQ_NETWORK_NODE_MAX_TOPICS -/// in delegatemqconfig.h). - -#include "DataBus.h" -#include "extras/util/TransportMonitor.h" -#include "extras/util/RetryMonitor.h" -#include "extras/util/ReliableTransport.h" -#include "extras/util/Timer.h" -#include "extras/util/TimerDelegate.h" -#include "extras/util/Fault.h" -#include -#include -#include -#include -#include -#include - -// Select the OS thread implementation based on the build configuration. -#if defined(DMQ_THREAD_STDLIB) - #include "port/os/stdlib/StdlibThread.h" -#elif defined(DMQ_THREAD_WIN32) - #include "port/os/win32/Win32Thread.h" -#elif defined(DMQ_THREAD_POSIX) - #include "port/os/posix/PosixThread.h" -#elif defined(DMQ_THREAD_FREERTOS) - #include "port/os/freertos/FreeRTOSThread.h" -#elif defined(DMQ_THREAD_THREADX) - #include "port/os/threadx/ThreadXThread.h" -#elif defined(DMQ_THREAD_ZEPHYR) - #include "port/os/zephyr/ZephyrThread.h" -#elif defined(DMQ_THREAD_CMSIS_RTOS2) - #include "port/os/cmsis-rtos2/CmsisRtos2Thread.h" -#elif defined(DMQ_THREAD_QT) - #include "port/os/qt/QtThread.h" -#endif - -namespace dmq::databus { - -/// Reliability tier for outgoing topics registered via NetworkNode::Send(). -enum class Reliability { - UNRELIABLE, ///< Raw transport send — no ACK, no retry. - RELIABLE, ///< Transport send with ACK and automatic retry (RetryMonitor stack). -}; - -/// Where an incoming topic registered via NetworkNode::Receive() is delivered. -enum class Delivery { - LOCAL, ///< This node's subscribers only (DataBus::AddIncomingTopic). The default; can't loop. - RELAY, ///< This node's subscribers, and forwarded out every link that Send()s the topic - ///< (DataBus::AddRelayTopic). For gateway nodes. Wire the topic one way: Send() it - ///< on the other link(s), not on the link it arrives on, or the originator gets - ///< it back (a duplicate, not a loop, as long as it receives the topic LOCAL). -}; - -namespace detail { -/// Registers an incoming topic on a participant with the requested delivery. -/// Shared by NetworkNode and other links with the same Receive() API. -template -void AddReceivedTopic(void* serializer, const dmq::xstring& topic, dmq::DelegateRemoteId remoteId, - Participant& participant, Delivery delivery) -{ - auto& ser = *static_cast*>(serializer); - if (delivery == Delivery::RELAY) - DataBus::AddRelayTopic(topic, remoteId, participant, ser); - else - DataBus::AddIncomingTopic(topic, remoteId, participant, ser); -} -} // namespace detail - -/// @brief Generic multi-peer DataBus network node. -/// -/// All member functions are safe to call before Start() or AddPeer(); registrations -/// are stored and applied when the relevant participant is created. -template -class NetworkNode { - using TransportMonitor = dmq::util::TransportMonitor; - using RetryMonitor = dmq::util::RetryMonitor; - using ReliableTransport = dmq::util::ReliableTransport; - -public: - /// Fired when a peer's unacked-message cap is exceeded (TransportMonitor::OnCapExceeded). - /// Subscribers receive: (peerName, count). - dmq::Signal OnPeerCapExceeded; - - /// Fired when TransportMonitor::Process() can't drain a peer's expired entries - /// fast enough in one pass. Subscribers receive: (peerName, remaining). - dmq::Signal OnPeerPendingExceeded; - - /// Fired when a RELIABLE message to a peer exhausts its retry budget without - /// being ACKed — the message is now permanently abandoned. - /// Subscribers receive: (peerName, remoteId, seqNum). - dmq::Signal OnDeliveryFailed; - - /// Fired on every per-attempt send status for a RELIABLE message to a peer - /// (TransportMonitor::OnSendStatus): SUCCESS when an ACK arrives, or TIMEOUT - /// on each retry attempt before the budget is exhausted. A message may report - /// TIMEOUT several times while still being retried before either succeeding - /// or finally firing OnDeliveryFailed once -- see OnDeliveryFailed for the - /// permanent-abandonment signal this is deliberately kept separate from. - /// Subscribers receive: (peerName, remoteId, seqNum, status). - dmq::Signal OnPeerSendStatus; - - NetworkNode() = default; - ~NetworkNode() { Stop(); } - - NetworkNode(const NetworkNode&) = delete; - NetworkNode& operator=(const NetworkNode&) = delete; - - /// @brief Open the inbound transport and start the receive thread. - /// - /// @param nodeName Human-readable name used for thread naming and logging. - /// @param listenPort Port this node receives all incoming traffic on. - /// @param watchdog Watchdog timeout for the receive thread (0 = disabled). - /// @param tickPeriod Interval between receive-loop polls. - /// @return true on success. - bool Start(const char* nodeName, - uint16_t listenPort, - dmq::Duration watchdog = std::chrono::seconds(30), - dmq::Duration tickPeriod = std::chrono::milliseconds(10)) - { - dmq::LockGuard lock(m_mutex); - if (m_running) return true; - - char threadName[64]; - snprintf(threadName, sizeof(threadName), "%s_NetworkThread", nodeName); - - // Listen on all interfaces so peers on other machines can reach this node. - // (LinuxUdpTransport binds the address it's given; the other UDP ports - // already bind INADDR_ANY for SUB and ignore it.) - if (m_recvTransport.Create(Transport::Type::SUB, "0.0.0.0", listenPort) != 0) { - printf("NetworkNode [%s]: ERROR - failed to open recv port %u\n", nodeName, listenPort); - return false; - } - m_recvTransport.SetRecvTimeout(std::chrono::milliseconds(1)); - // Allow the SUB socket to send ACKs back to senders of RELIABLE messages. - // The `else if (m_sendTransport)` gate in Receive() requires a non-null - // m_sendTransport; using self means ACKs go out via sendto on this socket. - m_recvTransport.SetSendTransport(&m_recvTransport); - - m_recvParticipant = dmq::xmake_shared(m_recvTransport); - - // Apply incoming topics registered before Start(). - for (size_t i = 0; i < m_inCount; ++i) - m_inTopics[i].adder(m_inTopics[i].serializer, - m_inTopics[i].topic, - m_inTopics[i].remoteId, - *m_recvParticipant, - m_inTopics[i].delivery); - - m_thread.emplace( - threadName, 100, dmq::os::FullPolicy::FAULT, dmq::DEFAULT_DISPATCH_TIMEOUT); - - m_running = true; - m_tickPeriod = tickPeriod; - - std::optional wd = (watchdog.count() > 0) - ? std::optional{watchdog} - : std::nullopt; - m_thread->CreateThread(wd); - - m_recvConn = m_recvTimer.OnExpired.Connect( - dmq::util::MakeTimerDelegate(this, &NetworkNode::ReceiverThread, *m_thread)); - m_recvTimer.Start(tickPeriod); - - return true; - } - - /// @brief Stop all transports and exit the receive thread. - void Stop() - { - { - dmq::LockGuard lock(m_mutex); - if (!m_running) return; - m_running = false; - - m_recvTimer.Stop(); - m_recvTransport.Close(); - } - - // Exit the receive thread with no lock held. ReceiverThread() is dispatched - // asynchronously via TimerDelegate, so a tick may already be queued on - // m_thread when Stop() is called; ExitThread() blocks (join()) until the - // thread's dispatch loop drains its queue, which includes running any - // already-queued ReceiverThread() tick to completion. That tick acquires - // m_mutex too, so holding it here while blocked in join() would deadlock. - if (m_thread) - m_thread->ExitThread(); - - // Disconnect only after ExitThread() above has drained m_thread's queue. - // Neither m_recvTimer.Stop() nor Disconnect() stops a tick that's already - // running, and a ProcessTimers() emit racing Stop() can still queue one. - // Draining first guarantees no ReceiverThread() call on `this` is left - // once Stop() returns, so the NetworkNode can be destroyed safely. - m_recvConn.Disconnect(); - - dmq::LockGuard lock(m_mutex); - for (size_t i = m_peerCount; i > 0; --i) { - RemoteNode& node = m_peers[i - 1]; - if (!node.active) continue; - DataBus::RemoveParticipant(node.reliableParticipant); - DataBus::RemoveParticipant(node.unreliableParticipant); - if (node.reliableParticipant) node.reliableParticipant->SetSendThread(nullptr); - if (node.unreliableParticipant) node.unreliableParticipant->SetSendThread(nullptr); - node.capConn.Disconnect(); - node.pendingConn.Disconnect(); - node.deliveryFailedConn.Disconnect(); - node.sendStatusConn.Disconnect(); - node.rawTransport.Close(); - node.active = false; - } - m_peerCount = 0; - } - - /// @brief Add a remote peer. - /// - /// Outgoing topics already registered via Send() are applied immediately. - /// May be called before or after Start(). - /// - /// @param name Peer name (for logging, up to 47 chars). - /// @param addr IP address of the peer. - /// @param port UDP port the peer listens on. - void AddPeer(const char* name, const char* addr, uint16_t port) - { - dmq::LockGuard lock(m_mutex); - DMQ_ASSERT_TRUE(m_peerCount < MaxPeers); - - RemoteNode& node = m_peers[m_peerCount]; - size_t nameLen = strlen(name); - if (nameLen >= sizeof(node.name)) nameLen = sizeof(node.name) - 1; - memcpy(node.name, name, nameLen); - node.name[nameLen] = '\0'; - - if (node.rawTransport.Create(Transport::Type::PUB, addr, port) != 0) { - printf("NetworkNode: ERROR - failed to connect to peer '%s' at %s:%u\n", name, addr, port); - return; - } - - // Wire the transport monitor so Send() calls TransportMonitor::Add(seqNum) - // and incoming ACKs call TransportMonitor::Remove(seqNum). Without this, - // m_pending stays empty, Process() never fires timeouts, and RetryMonitor - // entries are never erased. - node.rawTransport.SetTransportMonitor(&node.transportMonitor); - - // Allow Receive() to be called on the PUB socket so ReceiverThread can drain - // ACKs. Remote peers send ACKs to our PUB socket's OS-assigned ephemeral port - // (the source address they saw when the message arrived), not to our SUB listen - // port. Without this, Remove() is never called and m_pending fills to cap. - node.rawTransport.SetRecvTransport(&node.rawTransport); - - // Two-phase init: wire the reliability stack using stable member addresses. - // RemoteNode is stored by value in std::array — elements never relocate. - node.retryMonitor.Init(node.rawTransport, node.transportMonitor); - node.reliableTransport.Init(node.rawTransport, node.retryMonitor); - - dmq::xstring peerName(name); - node.capConn = node.transportMonitor.OnCapExceeded.Connect( - dmq::MakeDelegate([this, peerName](size_t n) { - printf("NetworkNode [%s]: cap exceeded (%zu unacked messages)\n", - peerName.c_str(), n); - this->OnPeerCapExceeded(peerName, n); - })); - node.pendingConn = node.transportMonitor.OnPendingExceeded.Connect( - dmq::MakeDelegate([this, peerName](size_t n) { - printf("NetworkNode [%s]: pending exceeded (%zu entries remain)\n", - peerName.c_str(), n); - this->OnPeerPendingExceeded(peerName, n); - })); - node.deliveryFailedConn = node.retryMonitor.OnDeliveryFailed.Connect( - dmq::MakeDelegate([this, peerName](dmq::DelegateRemoteId id, uint16_t seq) { - printf("NetworkNode [%s]: delivery failed id=%u seq=%u (retries exhausted)\n", - peerName.c_str(), id, seq); - this->OnDeliveryFailed(peerName, id, seq); - })); - node.sendStatusConn = node.transportMonitor.OnSendStatus.Connect( - dmq::MakeDelegate([this, peerName](dmq::DelegateRemoteId id, uint16_t seq, TransportMonitor::Status status) { - // Only TIMEOUT is print-worthy here -- SUCCESS fires on every - // acked RELIABLE message and would flood the log under normal load. - if (status == TransportMonitor::Status::TIMEOUT) { - printf("NetworkNode [%s]: send status TIMEOUT id=%u seq=%u (retry pending)\n", - peerName.c_str(), id, seq); - } - this->OnPeerSendStatus(peerName, id, seq, status); - })); - - node.reliableParticipant = dmq::xmake_shared(node.reliableTransport); - node.unreliableParticipant = dmq::xmake_shared(node.rawTransport); - - if (m_thread.has_value()) { - node.reliableParticipant->SetSendThread(&*m_thread); - node.unreliableParticipant->SetSendThread(&*m_thread); - } - - DataBus::AddParticipant(node.reliableParticipant); - DataBus::AddParticipant(node.unreliableParticipant); - - // Apply outgoing topics registered before this peer was added. - for (size_t i = 0; i < m_outCount; ++i) { - const OutgoingTopic& out = m_outTopics[i]; - if (out.reliability == Reliability::RELIABLE) - node.reliableParticipant->AddRemoteTopic(out.topic, out.remoteId); - else - node.unreliableParticipant->AddRemoteTopic(out.topic, out.remoteId); - } - - node.active = true; - m_peerCount++; - } - - /// @brief Register a topic this node publishes to all peers. - /// - /// Registers the serializer with DataBus and maps the topic to the correct - /// reliability-tier participant on every existing and future peer. - /// - /// @param topic DataBus topic string. - /// @param remoteId Wire ID embedded in the serialized frame. - /// @param serializer Serializer instance for type T. - /// @param rel Reliability tier (default UNRELIABLE). - template - void Send(const dmq::xstring& topic, - dmq::DelegateRemoteId remoteId, - dmq::ISerializer& serializer, - Reliability rel = Reliability::UNRELIABLE) - { - dmq::LockGuard lock(m_mutex); - DMQ_ASSERT_TRUE(m_outCount < MaxTopics); - DataBus::RegisterSerializer(topic, serializer); - m_outTopics[m_outCount++] = {topic, remoteId, rel}; - - // Apply to peers already added. - for (size_t i = 0; i < m_peerCount; ++i) { - RemoteNode& node = m_peers[i]; - if (!node.active) continue; - if (rel == Reliability::RELIABLE) - node.reliableParticipant->AddRemoteTopic(topic, remoteId); - else - node.unreliableParticipant->AddRemoteTopic(topic, remoteId); - } - } - - /// @brief Register a topic this node receives from the network. - /// - /// Registers an incoming topic on the receive-side participant. May be called - /// before or after Start(); applied immediately if Start() has already run. - /// - /// @param topic DataBus topic string. - /// @param remoteId Wire ID embedded in the serialized frame. - /// @param serializer Serializer instance for type T. - /// @param delivery LOCAL (default): this node's subscribers only. RELAY: also - /// forwarded out every link that Send()s the topic, e.g. a - /// gateway passing Ethernet commands on to a serial MCU. See Delivery. - template - void Receive(const dmq::xstring& topic, - dmq::DelegateRemoteId remoteId, - dmq::ISerializer& serializer, - Delivery delivery = Delivery::LOCAL) - { - dmq::LockGuard lock(m_mutex); - DMQ_ASSERT_TRUE(m_inCount < MaxTopics); - - // Store a type-erased adder so it can be replayed when Start() creates the participant. - m_inTopics[m_inCount++] = { - topic, remoteId, static_cast(&serializer), - &detail::AddReceivedTopic, delivery - }; - - // Apply immediately if Start() has already run. - if (m_recvParticipant) - detail::AddReceivedTopic(&serializer, topic, remoteId, *m_recvParticipant, delivery); - } - -private: - void ReceiverThread() - { - dmq::LockGuard lock(m_mutex); - // Override via DMQ_NETWORK_NODE_MAX_WORK in delegatemqconfig.h. - constexpr int MAX_WORK = dmq::NETWORK_NODE_MAX_WORK; - - if (m_recvParticipant) { - for (int i = 0; i < MAX_WORK; ++i) - if (m_recvParticipant->ProcessIncoming() != 0) break; - } - - // Drain ACKs that arrived on each peer's PUB socket (ephemeral source port). - // Remote peers send ACKs to the source address they received from, which is - // our PUB socket's OS-assigned port — not our SUB listen port. Receive() on - // the PUB socket calls TransportMonitor::Remove(seqNum) when an ACK arrives, - // firing SUCCESS so RetryMonitor erases the entry. The 2 ms recv timeout on - // PUB sockets keeps each poll fast when there is nothing to receive. - for (size_t i = 0; i < m_peerCount; ++i) { - if (!m_peers[i].active) continue; - for (int k = 0; k < MAX_WORK; ++k) { - dmq::transport::DmqHeader ackHeader; - dmq::xstringstream ackStream(std::ios::in | std::ios::out | std::ios::binary); - if (m_peers[i].rawTransport.Receive(ackStream, ackHeader) != 0) break; - } - } - - // Throttled: run TransportMonitor::Process() ~10 times per second. - auto now = dmq::Clock::now(); - if (now - m_lastMonitorCheck >= std::chrono::milliseconds(100)) { - for (size_t i = 0; i < m_peerCount; ++i) { - if (m_peers[i].active) - m_peers[i].transportMonitor.Process(); - } - m_lastMonitorCheck = now; - } - } - - // ----------------------------------------------------------------------- - // RemoteNode — fully by-value storage; no heap for transport objects. - // - // std::array guarantees elements are never relocated after construction, - // so Init() references between sibling members remain valid for the - // lifetime of this NetworkNode: - // retryMonitor refs rawTransport + transportMonitor - // reliableTransport refs rawTransport + retryMonitor - // ----------------------------------------------------------------------- - struct RemoteNode { - Transport rawTransport; - TransportMonitor transportMonitor; - RetryMonitor retryMonitor; // Init(rawTransport, transportMonitor) - ReliableTransport reliableTransport; // Init(rawTransport, retryMonitor) - dmq::ScopedConnection capConn; - dmq::ScopedConnection pendingConn; - dmq::ScopedConnection deliveryFailedConn; - dmq::ScopedConnection sendStatusConn; - std::shared_ptr reliableParticipant; // xmake_shared on construction - std::shared_ptr unreliableParticipant; // xmake_shared on construction - bool active = false; - char name[48] = {}; - }; - - // Type-erased incoming-topic record. Avoids storing template arguments past - // the Receive() call site while preserving type-safe AddIncomingTopic. - using TopicAdder = void(*)(void*, const dmq::xstring&, dmq::DelegateRemoteId, Participant&, Delivery); - - struct IncomingTopic { - dmq::xstring topic; - dmq::DelegateRemoteId remoteId = 0; - void* serializer = nullptr; - TopicAdder adder = nullptr; - Delivery delivery = Delivery::LOCAL; - }; - - struct OutgoingTopic { - dmq::xstring topic; - dmq::DelegateRemoteId remoteId = 0; - Reliability reliability = Reliability::UNRELIABLE; - }; - - // Inbound path — one participant handles all incoming traffic on listenPort. - Transport m_recvTransport; - std::shared_ptr m_recvParticipant; - - // Peer table — fixed-size; no heap for transport or reliability-stack objects. - std::array m_peers{}; - size_t m_peerCount = 0; - - // Topic tables — fixed-size. - std::array m_inTopics{}; - size_t m_inCount = 0; - std::array m_outTopics{}; - size_t m_outCount = 0; - - // Receive thread. Delay construction until Start() via std::optional to - // avoid heap allocation while allowing runtime thread naming. - std::optional m_thread; - dmq::util::Timer m_recvTimer; - dmq::ScopedConnection m_recvConn; - dmq::Duration m_tickPeriod{}; - dmq::TimePoint m_lastMonitorCheck{}; - bool m_running = false; - mutable dmq::RecursiveMutex m_mutex; -}; - -} // namespace dmq::databus - -#endif // DMQ_NETWORK_NODE_H diff --git a/DelegateMQ/extras/databus/Participant.h b/DelegateMQ/extras/databus/Participant.h deleted file mode 100644 index 2ebb8a0..0000000 --- a/DelegateMQ/extras/databus/Participant.h +++ /dev/null @@ -1,421 +0,0 @@ -#ifndef DMQ_PARTICIPANT_H -#define DMQ_PARTICIPANT_H - -#include "delegate/DelegateRemote.h" -#include "delegate/DelegateAsync.h" -#include "delegate/DelegateOpt.h" -#include "port/transport/common/ITransport.h" -#include "port/transport/common/DmqHeader.h" -#include "extras/dispatcher/RemoteChannel.h" -#include "extras/util/Fault.h" -#include -#include -#include -#include -#include - -namespace dmq::databus { - -// A Participant represents a remote node in the DataBus network. -// It manages the transport and the remote channels for different signatures. -// -// LIFETIME NOTE: This class assumes that the ITransport object passed to the constructor -// will outlive the Participant instance. -class Participant { - XALLOCATOR - friend class DataBus; -public: - Participant(dmq::transport::ITransport& transport) : m_transport(&transport) {} - - // Set a thread to serialize all outgoing sends. - // When set, Send() posts the channel invocation to this thread rather than - // executing inline on the caller's thread. This provides two benefits: - // 1. Thread safety: concurrent Publish() calls from multiple threads are - // safe — each send is queued rather than racing on the shared stream. - // 2. Non-blocking callers: blocking I/O in the transport cannot stall - // unrelated publishing threads. - // Without a send thread, concurrent calls to Send() for the same remote ID - // are a data race on the channel's internal stream buffer. - void SetSendThread(dmq::IThread* thread) { m_sendThread = thread; } - - /// @brief How long a received sequence number counts toward duplicate - /// detection. Defaults to dmq::SEQ_HISTORY_EXPIRY (DMQ_SEQ_HISTORY_EXPIRY_MS). - /// Set it to cover the sender's retry window if that differs from the default. - void SetSeqHistoryExpiry(dmq::Duration expiry) { - dmq::LockGuard lock(m_mutex); - m_seqHistoryExpiry = expiry; - } - - /// @brief Map a topic string to a remote ID for outbound sends to this - /// participant. - /// @details When local `DataBus::Publish()` sends to `topic`, it is - /// serialized and sent to this participant using `remoteId` on the wire. - /// Required for the sending side of remote distribution — see - /// `docs/DATABUS.md`'s "Setup Checklist". - /// @param topic Topic string to map. - /// @param remoteId Wire identifier this topic is sent as. Must match the - /// ID the receiving node registers via - /// `DataBus::AddIncomingTopic()` for the same topic. - void AddRemoteTopic(const dmq::xstring& topic, dmq::DelegateRemoteId remoteId) { - dmq::LockGuard lock(m_mutex); - m_topicToRemoteId[topic] = remoteId; - } - - // Enable or disable continuous error mode (disables error latching). -private: - void EnableContinuousErrors(bool enable) { - m_continuousErrors = enable; - } -public: - - // Subscribe to technical errors (serialization/dispatch) for this participant. - [[nodiscard]] dmq::ScopedConnection SubscribeError(std::function func) { - return m_errorSignal.Connect(dmq::MakeDelegate(std::move(func))); - } - - // Process incoming data from the transport. - // Must not be called concurrently — m_receiveMutex serializes the transport read. - // @return The result code from ITransport::Receive. - int ProcessIncoming() { - dmq::transport::DmqHeader header; - dmq::xstringstream inputStream(std::ios::in | std::ios::out | std::ios::binary); - - int result; - { - // Serialize access to the transport read - dmq::LockGuard receiveLock(m_receiveMutex); - result = m_transport->Receive(inputStream, header); - } - - if (result == 0) { - // Validate header marker and protocol version - if (!header.IsValid()) { - OnChannelError(dmq::INVALID_REMOTE_ID, dmq::DelegateError::ERR_TRANSPORT_RECEIVE, 0); - return -1; // Protocol error - } - - dmq::DelegateRemoteId id = header.GetId(); - uint16_t seqNum = header.GetSeqNum(); - - // An ACK was already handled inside the transport (it cleared the - // pending entry in the transport monitor). It has no channel, so - // it isn't an ERR_NO_DISPATCHER. - if (id == dmq::ACK_REMOTE_ID) - return 0; - - dmq::IRemoteInvoker* invoker = nullptr; - std::shared_ptr channelLifetime; // keeps channel alive across lock gap - { - dmq::LockGuard lock(m_mutex); - auto it = m_channels.find(id); - if (it != m_channels.end()) { - // Filter out duplicate messages (retries) - if (id != dmq::ACK_REMOTE_ID && - m_history[HistoryKey(header.GetNodeId(), id)].is_duplicate(seqNum, dmq::Clock::now(), m_seqHistoryExpiry)) { - return 0; // Silently drop duplicate - } - channelLifetime = it->second.channel; - invoker = it->second.invoker; - } - } - - // Invoke outside the lock to prevent deadlocks and allow re-entry - if (invoker) { - invoker->Invoke(inputStream); - } else { - OnChannelError(id, dmq::DelegateError::ERR_NO_DISPATCHER, 0); - } - } - return result; - } - - // Send data for a topic. - // If a send thread was set via SetSendThread(), the channel invocation is - // dispatched asynchronously to that thread. Otherwise it executes inline. - template - bool DispatchIfInterested(const dmq::xstring& topic, const T& data, dmq::ISerializer* serializer) { - std::shared_ptr> channel; - bool typeMismatch = false; - dmq::DelegateRemoteId remoteId = 0; - - { - dmq::LockGuard lock(m_mutex); - auto it = m_topicToRemoteId.find(topic); - if (it != m_topicToRemoteId.end()) { - if (!serializer) { - return true; - } - remoteId = it->second; - channel = GetOrCreateChannelLocked(remoteId, *serializer, typeMismatch); - } else { - return false; - } - } - - if (typeMismatch) { - OnChannelError(remoteId, dmq::DelegateError::ERR_TYPE_MISMATCH, 0); - DMQ_ASSERT(); - return true; - } - - if (channel) { - if (m_sendThread) { - // Static function, not a lambda (no capture to allocate) and not - // a member (the queued message must not hold a raw `this`; the - // Participant may be destroyed before the send thread runs it). - // The channel shared_ptr keeps the channel alive until then. - (void)dmq::MakeDelegate(&Participant::AsyncSend, *m_sendThread).AsyncInvoke(channel, data); - } else { - (*channel)(data); - } - } - return true; - } - - template - void Send(const dmq::xstring& topic, const T& data, dmq::ISerializer& serializer) { - DispatchIfInterested(topic, data, &serializer); - } - - /// @brief Internal helper to execute a remote send on a background thread. - /// @details Static so the queued message holds no `this`: the channel - /// shared_ptr is all it needs, and the Participant may be gone by then. - template - static void AsyncSend(std::shared_ptr> channel, T data) { - if (channel) { - (*channel)(data); - } - } - - /// @brief Register a local handler invoked when data arrives from this - /// participant for `remoteId`, using a `std::function`. - /// @details Required for the receiving side of remote distribution — see - /// `docs/DATABUS.md`'s "Setup Checklist". Creates the participant's - /// `RemoteChannel` for `remoteId` if one doesn't already exist. - /// @tparam T Message type this handler expects. Must match the - /// type the sending node publishes as `remoteId`, or - /// this reports ERR_TYPE_MISMATCH via - /// `Participant::SubscribeError`/`DataBus::SubscribeError` - /// and asserts. - /// @param remoteId Wire identifier to handle incoming data for. - /// @param serializer Deserializes the incoming wire bytes into a `T`. - /// @param func Called with each deserialized `T`. - template - void RegisterHandler(dmq::DelegateRemoteId remoteId, dmq::ISerializer& serializer, std::function func) { - bool typeMismatch = false; - { - dmq::LockGuard lock(m_mutex); - auto channel = GetOrCreateChannelLocked(remoteId, serializer, typeMismatch); - if (channel) { - // Use Bind() to register the callback for incoming calls. - channel->Bind(func, remoteId); - } - } - if (typeMismatch) { - OnChannelError(remoteId, dmq::DelegateError::ERR_TYPE_MISMATCH, 0); - DMQ_ASSERT(); - } - } - - /// @brief Register a local handler invoked when data arrives from this - /// participant for `remoteId`, using a raw lambda or functor. - /// @details Same behavior as the `std::function` overload above, just - /// without the `std::function` wrapping overhead for a plain callable. - /// @tparam T Message type this handler expects. Must match the - /// type the sending node publishes as `remoteId`, or - /// this reports ERR_TYPE_MISMATCH via - /// `Participant::SubscribeError`/`DataBus::SubscribeError` - /// and asserts. - /// @tparam F Callable type, deduced from `func`. Must be invocable - /// as `void(T)`. - /// @param remoteId Wire identifier to handle incoming data for. - /// @param serializer Deserializes the incoming wire bytes into a `T`. - /// @param func Called with each deserialized `T`. - template ::value>> - void RegisterHandler(dmq::DelegateRemoteId remoteId, dmq::ISerializer& serializer, F&& func) { - bool typeMismatch = false; - { - dmq::LockGuard lock(m_mutex); - auto channel = GetOrCreateChannelLocked(remoteId, serializer, typeMismatch); - if (channel) { - // Use Bind() to register the callback for incoming calls. - channel->Bind(std::forward(func), remoteId); - } - } - if (typeMismatch) { - OnChannelError(remoteId, dmq::DelegateError::ERR_TYPE_MISMATCH, 0); - DMQ_ASSERT(); - } - } - -private: - // Get the remote ID for a topic. - bool GetRemoteId(const dmq::xstring& topic, dmq::DelegateRemoteId& remoteId) { - dmq::LockGuard lock(m_mutex); - auto it = m_topicToRemoteId.find(topic); - if (it != m_topicToRemoteId.end()) { - remoteId = it->second; - return true; - } - return false; - } - - // Get the topic name for a remote ID (error path only — linear scan is fine). - bool GetTopicName(dmq::DelegateRemoteId remoteId, dmq::xstring& topic) { - dmq::LockGuard lock(m_mutex); - for (auto& [t, id] : m_topicToRemoteId) { - if (id == remoteId) { topic = t; return true; } - } - return false; - } - - template - void AttachErrorHandler(dmq::RemoteChannel* channel) { - channel->SetErrorHandler(dmq::MakeDelegate(this, &Participant::OnChannelError)); - } - - // Type-instantiated but non-templated-TYPE deleter: &DeleteRemoteChannel decays - // to the same void(*)(void*) regardless of T, so the shared_ptr control block - // built from it in GetOrCreateChannelLocked below is not templated on T either. - template - static void DeleteRemoteChannel(void* p) { - delete static_cast*>(p); - } - - void OnChannelError(dmq::DelegateRemoteId id, dmq::DelegateError error, dmq::DelegateErrorAux) { - if (error == dmq::DelegateError::SUCCESS) return; - bool shouldFire = false; - dmq::xstring topic; - { - dmq::LockGuard lock(m_mutex); - for (auto& [t, rid] : m_topicToRemoteId) { - if (rid == id) { topic = t; break; } - } - if (topic.empty()) { - // xostringstream keeps this portable: under DMQ_ALLOCATOR, xstring and - // std::string are different types, so std::to_string concatenation - // would not compile. - dmq::xostringstream os; - os << "UnknownRemoteId:" << id; - topic = os.str(); - } - uint16_t bit = uint16_t(1u << static_cast(error)); - auto& bits = m_reportedErrors[topic]; - if (!(bits & bit)) { - bits |= bit; - shouldFire = true; - } else if (m_continuousErrors) { - shouldFire = true; - } - } - if (shouldFire) - m_errorSignal(topic, error); - } - - void ResetErrors() { - dmq::LockGuard lock(m_mutex); - m_reportedErrors.clear(); - } - - struct ChannelInvoker { - std::shared_ptr channel; - dmq::IRemoteInvoker* invoker = nullptr; - }; - - template - std::shared_ptr> GetOrCreateChannelLocked(dmq::DelegateRemoteId remoteId, dmq::ISerializer& serializer, bool& outTypeMismatch) { - std::shared_ptr> channel; - outTypeMismatch = false; - - auto it = m_channels.find(remoteId); - if (it != m_channels.end()) { - // Type safety: catch remoteId reused with a different T - auto itType = m_channelTypes.find(remoteId); - if (itType != m_channelTypes.end()) { - if (itType->second != std::type_index(typeid(T))) { - outTypeMismatch = true; - return nullptr; - } - } - channel = std::static_pointer_cast>(it->second.channel); - } else { - auto* raw = new dmq::RemoteChannel(*m_transport, serializer); - - // Establish the remote ID for sending via operator(). - raw->SetRemoteId(remoteId); - - // Ensure error handler is attached to the new channel - AttachErrorHandler(raw); - - // Erase to void* BEFORE constructing the shared_ptr, so the control block's - // deduced pointer type is void (non-templated) rather than - // RemoteChannel* -- this is what lets the control block be shared - // across every distinct T instead of duplicated per signature. - std::shared_ptr channelVoid(static_cast(raw), &DeleteRemoteChannel, ::dmq::stl_allocator()); - channel = std::static_pointer_cast>(channelVoid); - - m_channels[remoteId] = { channelVoid, raw->GetEndpoint() }; - m_channelTypes.emplace(remoteId, std::type_index(typeid(T))); - } - - return channel; - } - - dmq::transport::ITransport* m_transport; - dmq::IThread* m_sendThread = nullptr; - dmq::Duration m_seqHistoryExpiry = dmq::SEQ_HISTORY_EXPIRY; - bool m_continuousErrors = false; - dmq::RecursiveMutex m_mutex; - dmq::Mutex m_receiveMutex; - dmq::xmap m_topicToRemoteId; - dmq::xmap m_channels; - dmq::xmap m_channelTypes; - dmq::xmap m_reportedErrors; - dmq::Signal m_errorSignal; - - // --- Duplicate Filtering --- - // Retries reuse the original sequence number, so a recently seen number from - // the same sender and remote ID is a duplicate. Sequence numbers are per - // sender, so history is kept per (sender node ID, remote ID); senders that - // leave their node ID unset (0) share one history per remote ID. - // Entries expire after m_seqHistoryExpiry, which covers the sender's whole - // retry window: an older match is a restarted sender reusing the number, - // not a retry. - static uint32_t HistoryKey(uint8_t nodeId, dmq::DelegateRemoteId id) { - return (static_cast(nodeId) << 16) | id; - } - - struct SeqHistory { - static constexpr size_t SIZE = DMQ_SEQ_HISTORY_SIZE; - std::array buffer; - std::array received; - std::array valid; - size_t head = 0; - - SeqHistory() { valid.fill(false); } - - bool is_duplicate(uint16_t seq, dmq::TimePoint now, dmq::Duration expiry) { - for (size_t i = 0; i < SIZE; ++i) { - if (valid[i] && buffer[i] == seq) { - if (now - received[i] < expiry) - return true; - // Expired: a new message reusing the number. Refresh this - // slot rather than take a second one for the same number. - received[i] = now; - return false; - } - } - buffer[head] = seq; - received[head] = now; - valid[head] = true; - head = (head + 1) % SIZE; - return false; - } - }; - dmq::xmap m_history; -}; - -} // namespace dmq::databus - - -#endif // DMQ_PARTICIPANT_H diff --git a/DelegateMQ/extras/databus/README.md b/DelegateMQ/extras/databus/README.md deleted file mode 100644 index 73cfb66..0000000 --- a/DelegateMQ/extras/databus/README.md +++ /dev/null @@ -1,201 +0,0 @@ -# DataBus - -The `dmq::databus::DataBus` is a central registry for topic-based communication within DelegateMQ. It provides a flexible publish-subscribe (Pub/Sub) architecture that decouples data producers from consumers. - -## DataBus vs. RemoteDispatcher — Data Distribution vs. Remote Function Invoke - -DelegateMQ has two distinct patterns for talking across threads/processes/machines. Picking the wrong one for the job shows up as awkward code, not a compile error, so it's worth knowing which is which before starting: - -| | **DataBus** (this directory) | **RemoteDispatcher** ([`extras/rpc`](../rpc/README.md)) | -|---|---|---| -| Pattern | Publish/subscribe (data distribution) | Point-to-point RPC (remote function invoke) | -| Addressing | Topic string, many-to-many | Remote ID → one specific registered endpoint | -| Who receives | Any number of subscribers (0, 1, or many) — the publisher doesn't know or care who | Exactly one endpoint per remote ID | -| Call semantics | `Publish()` is always fire-and-forget from the caller's side; delivery outcome (if any) arrives later via signals (`OnPeerSendStatus`, `OnDeliveryFailed`) | `RemoteInvokeWait()` blocks the caller until the remote ACKs or times out, returning success/failure directly — plus a fire-and-forget mode too | -| How you use it | Compose: hold an `ITransport&` (`Participant`), or instantiate `NetworkNode` — no subclassing required | Compose: hold a `dmq::rpc::RemoteDispatcher` as a member (`NetworkMgr`), connect to its `OnError`/`OnStatus`/`OnDeliveryFailed` Signals — no subclassing required | -| Reliability opt-in | Per-message — pass `Reliability::RELIABLE` or `UNRELIABLE` to `Send()` | Per-connection — the owning class decides once whether to wrap its transport in `ReliableTransport` | -| Multi-peer topology | Built in — `NetworkNode` manages any number of peers | One connection per `RemoteDispatcher` instance; the app manages multiple peers itself if it needs more than one | -| Typical use | Sensor data, telemetry, status broadcasts, state that should reach whoever's currently interested | Commands, remote function calls, request/response where the caller needs to know the call landed | - -**Rule of thumb:** if you're asking "who needs to know this happened?" reach for DataBus. If you're asking "did that specific call succeed?" reach for RemoteDispatcher. - -## Quickstart - -Three steps to send data between components: - -**1. Define a message type** -```cpp -// Any serializable struct (the Cellutron/Pumptron examples derive from their own -// MessageBase to add sequence numbers) -struct TemperatureMsg : public serialize::I { - float celsius = 0.0f; - std::ostream& write(serialize& ms, std::ostream& os) override { return ms.write(os, celsius); } - std::istream& read (serialize& ms, std::istream& is) override { return ms.read (is, celsius); } -}; -``` - -**2. Subscribe** -```cpp -// Connection owns the subscription — must stay in scope while callbacks are wanted -auto conn = dmq::databus::DataBus::Subscribe( - "sensor/temperature", - [](const TemperatureMsg& msg) { - printf("Temp: %.1f C\n", msg.celsius); - }); -``` - -**3. Publish** -```cpp -TemperatureMsg msg; -msg.celsius = 36.6f; -dmq::databus::DataBus::Publish("sensor/temperature", msg); -// → subscriber lambda fires immediately on the calling thread -``` - -> **Connection lifetime**: `Subscribe` returns a `dmq::ScopedConnection`. Letting it go out of scope silently unsubscribes — store it in a member variable. - -To dispatch to a specific thread instead of the caller's thread: -```cpp -auto conn = dmq::databus::DataBus::Subscribe( - "sensor/temperature", - dmq::MakeDelegate(this, &MySensor::OnTemp), - &m_workerThread); // callback executes on m_workerThread, not the publisher's thread -``` - -To span multiple processes over a network, see [Multi-Process Quickstart — `NetworkNode`](#multi-process-quickstart--networknode) below. - ---- - -## Features - -- **Topic-Based Communication**: Components interact via named string topics rather than direct object references. -- **Thread Dispatching**: Subscribers can specify an `dmq::IThread` to have their callbacks executed on a specific thread. -- **Quality of Service (QoS)**: Supports Last Value Cache (LVC) to provide the most recent data to new subscribers immediately upon connection. -- **Filtering**: `SubscribeFilter` allows subscribers to receive only the data that matches a specific predicate. -- **Remote Distribution**: `dmq::databus::Participant` integration allows the `dmq::databus::DataBus` to span multiple physical nodes over any supported transport (UDP, TCP, ZeroMQ, etc.). -- **Monitoring & Spying**: The `Monitor` API allows for global observation of all bus traffic, useful for logging, debugging, or UI dashboards. -- **Type Safety**: Built on C++ templates to ensure type-safe data transmission. - -## Basic Usage - -### Subscribing to a Topic - -```cpp -// Simple subscription on the current thread -auto conn = dmq::databus::DataBus::Subscribe("Temperature", [](const int& value) { - std::cout << "Temp changed: " << value << std::endl; -}); - -// Subscription dispatched to a specific worker thread -auto conn2 = dmq::databus::DataBus::Subscribe("Temperature", - dmq::MakeDelegate(&myObj, &MyClass::OnTempChange), &workerThread); -``` - -### Publishing to a Topic - -```cpp -dmq::databus::DataBus::Publish("Temperature", 25); -``` - ---- - -## Multi-Process Quickstart — `NetworkNode` - -`dmq::databus::NetworkNode` is a ready-made multi-peer network layer. -It handles transport setup, Participant creation, reliability stacking, and the -receive-loop thread. A new user writes only a `SetupNetwork()` function. - -### Minimal two-node example - -**`shared/Topics.h`** — shared between all nodes: -```cpp -#include "DelegateMQ.h" -#include "messages/TemperatureMsg.h" -#include "messages/AlarmMsg.h" - -namespace myapp { - // Remote IDs — unique per message type, consistent across nodes - static constexpr dmq::DelegateRemoteId RID_TEMPERATURE = 1; - static constexpr dmq::DelegateRemoteId RID_ALARM = 2; - - namespace topics { - static constexpr const char* TEMPERATURE = "sensor/temperature"; - static constexpr const char* ALARM = "sys/alarm"; - } - - // Serializer instances (defined in one .cpp, extern everywhere else) - extern dmq::serialization::serializer::Serializer serTemp; - extern dmq::serialization::serializer::Serializer serAlarm; -} -``` - -**`node_a/System.cpp`** — the sensor node (publishes temperature, receives alarms): -```cpp -#include "extras/databus/NetworkNode.h" -#include "port/transport/win32-udp/Win32UdpTransport.h" // or LinuxUdpTransport -#include "Topics.h" - -using Network = dmq::databus::NetworkNode; -static Network g_net; - -void SetupNetwork() { - g_net.Start("SensorNode", /*listenPort=*/6000); - - g_net.Receive(myapp::topics::ALARM, myapp::RID_ALARM, myapp::serAlarm); - - g_net.AddPeer("DisplayNode", "127.0.0.1", /*udpPort=*/6001); - - g_net.Send(myapp::topics::TEMPERATURE, myapp::RID_TEMPERATURE, - myapp::serTemp); -} - -// From here: DataBus::Publish(topics::TEMPERATURE, reading) routes -// automatically over the network to DisplayNode. -``` - -**`node_b/System.cpp`** — the display node (receives temperature, publishes alarms): -```cpp -void SetupNetwork() { - g_net.Start("DisplayNode", /*listenPort=*/6001); - - g_net.Receive(myapp::topics::TEMPERATURE, myapp::RID_TEMPERATURE, - myapp::serTemp); - - g_net.AddPeer("SensorNode", "127.0.0.1", /*udpPort=*/6000); - - g_net.Send(myapp::topics::ALARM, myapp::RID_ALARM, myapp::serAlarm, - dmq::databus::Reliability::RELIABLE); // ACK + retry -} -``` - -### Key points - -- **Order-independent**: `Receive()` and `Send()` may be called before or after `Start()` / `AddPeer()`. Registrations are stored and applied retroactively. -- **Reliability tiers**: `Reliability::UNRELIABLE` (default) sends raw UDP; `Reliability::RELIABLE` adds ACK + automatic retry via `RetryMonitor`. -- **Transport-agnostic**: Pass any `ITransport`-derived type as the template argument — `Win32UdpTransport`, `LinuxUdpTransport`, `ZephyrUdpTransport`, etc. -- **Local delivery by default**: a topic registered with `Receive()` reaches this node's subscribers only. Pass `Delivery::RELAY` (`Receive(topic, id, ser, Delivery::RELAY)`) on a gateway node to also forward it out every other link that `Send()`s it. See [Relay Nodes](../../../../docs/DATABUS.md#relay-nodes). -- **Fixed allocation**: `MaxPeers` and `MaxTopics` template parameters control pre-allocated capacity. No heap for transport objects (`RemoteNode` members are by-value in `std::array`). -- **Participant budget**: each peer registers two participants with the DataBus (reliable and unreliable), and every link in the process draws from the same `dmq::MAX_PARTICIPANTS` (`DMQ_MAX_PARTICIPANTS`, default 8). The defaults already meet: 4 peers × 2 = 8. A process with more links needs a larger `DMQ_MAX_PARTICIPANTS`; going over reports `ERR_CAPACITY_EXCEEDED` and calls `FaultHandler`. -- **`Participant` allocation**: Uses `xmake_shared` — fixed-block allocator on embedded targets. -- **Error & status signals**: `OnDeliveryFailed(peerName, remoteId, seqNum)` fires once when a RELIABLE message exhausts its retry budget; `OnPeerSendStatus(peerName, remoteId, seqNum, status)` fires on every per-attempt outcome (SUCCESS or TIMEOUT) leading up to that, so an app can tell "still retrying" apart from "permanently abandoned"; `OnPeerCapExceeded`/`OnPeerPendingExceeded(peerName, count)` are backpressure health signals. None of these overlap `DataBus::SubscribeError` — see [Error & Status Reporting](../../../../docs/DATABUS.md#error--status-reporting) in the full DataBus doc for the complete picture (including `DelegateError` codes) and usage examples. - -### Template parameters - -```cpp -template // maximum Send() or Receive() calls each -class NetworkNode; -``` - -`dmq::NETWORK_NODE_MAX_PEERS` (default 4) and `dmq::NETWORK_NODE_MAX_TOPICS` (default 16) come from `DMQ_NETWORK_NODE_MAX_PEERS` / `DMQ_NETWORK_NODE_MAX_TOPICS` in `DelegateMQConfig_Default.h` — override there to change the default for all instantiations, or pass explicit template arguments to override per-instantiation (e.g. `NetworkNode`). - ---- - -For the range of network topologies `NetworkNode` supports (star, mesh, broadcast/multicast, heterogeneous-transport gateways, broker-mediated, etc.), see [Topologies](../../../../docs/DATABUS.md#topologies) in the full DataBus doc. - ---- - -## Internal Mechanics - -The `dmq::databus::DataBus` utilizes DelegateMQ's `dmq::MulticastDelegate` system internally. When you `Publish`, the bus identifies all local and remote subscribers for that topic and invokes them. Remote subscribers are handled via `dmq::IDispatcher` and `dmq::transport::ITransport` layers, making the network boundary transparent to the application logic. diff --git a/DelegateMQ/extras/databus/SpyPacket.h b/DelegateMQ/extras/databus/SpyPacket.h deleted file mode 100644 index d127fce..0000000 --- a/DelegateMQ/extras/databus/SpyPacket.h +++ /dev/null @@ -1,44 +0,0 @@ -#ifndef DMQ_SPY_PACKET_H -#define DMQ_SPY_PACKET_H - -#include "delegate/DelegateOpt.h" -#include "port/serialize/serialize/msg_serialize.h" - -namespace dmq::databus { - -/// @brief Standardized packet containing bus traffic metadata. -/// @details This struct is passed to DataBus::Monitor subscribers and is -/// designed to be serialized for transmission to external diagnostic tools. -/// -/// The timestamp_us field uses dmq::Clock::now(), which typically provides -/// monotonic time since boot. -struct SpyPacket : public ::serialize::I { - XALLOCATOR - SpyPacket() = default; - virtual ~SpyPacket() = default; - SpyPacket(const dmq::xstring& t, const dmq::xstring& v, uint64_t ts, const dmq::xstring& id = "") - : topic(t), value(v), timestamp_us(ts), nodeId(id) {} - - dmq::xstring topic; ///< The name of the data topic. - dmq::xstring value; ///< Stringified representation of the data (or "?" if no stringifier registered). - uint64_t timestamp_us = 0; ///< Microseconds (usually since boot) when the message was published. - dmq::xstring nodeId; ///< Unique identifier for the sending node. - - std::ostream& write(::serialize& ms, std::ostream& os) override { - ms.write(os, topic); - ms.write(os, value); - ms.write(os, timestamp_us); - return ms.write(os, nodeId); - } - - std::istream& read(::serialize& ms, std::istream& is) override { - ms.read(is, topic); - ms.read(is, value); - ms.read(is, timestamp_us); - return ms.read(is, nodeId); - } -}; -} // namespace dmq::databus - - -#endif // DMQ_SPY_PACKET_H diff --git a/DelegateMQ/extras/dispatcher/Dispatcher.h b/DelegateMQ/extras/dispatcher/Dispatcher.h deleted file mode 100644 index 327c7b7..0000000 --- a/DelegateMQ/extras/dispatcher/Dispatcher.h +++ /dev/null @@ -1,79 +0,0 @@ -#ifndef DISPATCHER_H -#define DISPATCHER_H - -/// @file Dispatcher.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// @brief The bridge between the serialization layer and the physical transport layer. -/// -/// @details -/// The `Dispatcher` class is responsible for packaging serialized function arguments -/// into a valid DelegateMQ message and handing it off to the transport. -/// -/// **Key Responsibilities:** -/// 1. **Message Construction:** Creates the protocol header (`DmqHeader`) containing -/// the Remote ID and a monotonic Sequence Number. -/// 2. **Stream Management:** Validates that the output stream is compatible -/// (expects `xostringstream`). -/// 3. **Dispatch:** Forwards the header and the serialized payload (stream) to the -/// registered `ITransport::Send()` method. -/// -/// **Usage:** -/// This class is typically used internally by `DelegateRemote` to finalize a remote -/// procedure call before transmission. - -#include "delegate/IDispatcher.h" -#include "port/transport/common/DmqHeader.h" -#include "port/transport/common/ITransport.h" -#include -#include - -namespace dmq { - -/// @brief Dispatcher sends data to the transport for transmission to the endpoint. -class Dispatcher : public dmq::IDispatcher -{ - XALLOCATOR -public: - Dispatcher() = default; - ~Dispatcher() override = default; - - void SetTransport(transport::ITransport* transport) - { - m_transport = transport; - } - - // Send argument data to the transport - int Dispatch(dmq::xostringstream& os, dmq::DelegateRemoteId id, uint16_t* outSeqNum = nullptr) override - { - dmq::xostringstream* ss = &os; - - if (m_transport) - { - uint16_t seq = m_seqNum.fetch_add(1); - if (outSeqNum) *outSeqNum = seq; - transport::DmqHeader header(id, seq); - int err = m_transport->Send(*ss, header); - - // Reset the stream content and error state for the next use. - // This prevents the stream from growing indefinitely. - ss->str(dmq::xstring()); - ss->clear(); - ss->seekp(0); - - LOG_INFO("Dispatcher::Dispatch id={} seqNum={} err={}", header.GetId(), header.GetSeqNum(), err); - return err; - } - return -1; - } - -private: - transport::ITransport* m_transport = nullptr; - inline static std::atomic m_seqNum{0}; -}; - -} // namespace dmq - - -#endif \ No newline at end of file diff --git a/DelegateMQ/extras/dispatcher/README.md b/DelegateMQ/extras/dispatcher/README.md deleted file mode 100644 index 38ad4dc..0000000 --- a/DelegateMQ/extras/dispatcher/README.md +++ /dev/null @@ -1,52 +0,0 @@ -# Dispatcher Layer - -This directory contains the dispatch logic for **DelegateMQ**, serving as the critical bridge between the high-level serialization layer and the low-level physical transport. - -## Overview - -The `dmq::Dispatcher` is responsible for taking the serialized payload (function arguments) and preparing it for transmission over the network or IPC link. It decouples the "what" (serialized data) from the "how" (transport mechanism). - -## Key Components - -* **`Dispatcher.h`**: The concrete implementation of the `dmq::IDispatcher` interface. -* **`RemoteChannel.h`**: An aggregator that owns a `dmq::Dispatcher`, an `dmq::xostringstream` (serialization buffer), and borrows an `dmq::ISerializer` for a single function signature. Use `dmq::RemoteChannel` to configure `dmq::DelegateMemberRemote` endpoints without manually wiring each component. - -### Responsibilities - -#### dmq::Dispatcher -1. **Protocol Framing**: It constructs the `dmq::transport::DmqHeader` for every message, assigning the correct **Remote ID** and generating a monotonic **Sequence Number**. -2. **Stream Validation**: It ensures the output stream (`dmq::xostringstream`) contains valid data before transmission. -3. **Transport Handoff**: It forwards the framed message (Header + Payload) to the registered `dmq::transport::ITransport` instance for physical transmission. - -#### dmq::RemoteChannel -`dmq::RemoteChannel` owns a `dmq::DelegateFunctionRemote` internally and handles all wiring automatically. Call `Bind()` once to configure the channel (for receiving), or pass the ID to the constructor (for sending), then invoke it with `operator()`. - -```cpp -// Create one channel per message signature -dmq::RemoteChannel alarmChannel(transport, alarmSerializer); - -// Bind a member function and remote ID — channel owns the delegate internally -alarmChannel.Bind(this, &MyClass::ForwardAlarm, ALARM_MSG_ID); - -// Optionally register an error handler -alarmChannel.SetErrorHandler(dmq::MakeDelegate(this, &MyClass::OnError)); - -// Register the receive endpoint with the dmq::rpc::RemoteDispatcher -dispatcher.RegisterEndpoint(ALARM_MSG_ID, alarmChannel); - -// Invoke (fire-and-forget) -AlarmMsg msg; AlarmNote note; -alarmChannel(msg, note); - -// Or invoke with blocking wait -bool ok = dispatcher.RemoteInvokeWait(alarmChannel, msg, note); -``` - -Key accessors: -- `Bind(obj, func, id)` — binds a member function and configures all internal plumbing. -- `operator()(args...)` — invokes (sends) the remote message. -- `GetEndpoint()` — returns `dmq::IRemoteInvoker*` for `RemoteDispatcher::RegisterEndpoint()`. -- `GetError()` / `GetRemoteId()` — query last error and remote ID. -- `SetErrorHandler(delegate)` — register an error notification callback. - -> **Legacy accessors** (`GetDispatcher()`, `GetSerializer()`, `GetStream()`) remain available for code that manually wires a `dmq::DelegateMemberRemote`. diff --git a/DelegateMQ/extras/dispatcher/RemoteChannel.h b/DelegateMQ/extras/dispatcher/RemoteChannel.h deleted file mode 100644 index 1b4498e..0000000 --- a/DelegateMQ/extras/dispatcher/RemoteChannel.h +++ /dev/null @@ -1,391 +0,0 @@ -#ifndef REMOTE_CHANNEL_H -#define REMOTE_CHANNEL_H - -/// @file RemoteChannel.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief Aggregates transport, serializer, dispatcher, and stream into a single -/// object, mirroring how `IThread`/`Thread` hides async delegate wiring. -/// -/// @details -/// Setting up a remote delegate currently requires three separate objects: -/// @code -/// Dispatcher dispatcher; -/// dispatcher.SetTransport(&transport); -/// Serializer serializer; -/// dmq::xostringstream stream(std::ios::in | std::ios::out | std::ios::binary); -/// -/// DelegateFreeRemote remote(REMOTE_ID); -/// remote.SetSerializer(&serializer); -/// remote.SetDispatcher(&dispatcher); -/// remote.SetStream(&stream); -/// @endcode -/// -/// `RemoteChannel` collapses this into one setup object: -/// @code -/// MyTransport transport; -/// Serializer serializer; -/// RemoteChannel channel(transport, serializer); -/// -/// // Mirrors the async pattern exactly: -/// auto async = MakeDelegate(&MyFunc, thread); // async -/// auto remote = MakeDelegate(&MyFunc, REMOTE_ID, channel); // remote -/// @endcode -/// -/// @tparam Sig The function signature (e.g. `void(int, float)`) that matches both -/// the serializer and the remote delegates that use this channel. One channel -/// instance is required per distinct function signature. - -#include "Dispatcher.h" -#include "delegate/DelegateRemote.h" -#include "delegate/Signal.h" -#include "port/transport/common/ITransport.h" - -namespace dmq { - -template -class RemoteChannel; // Not defined - -/// @brief Aggregates dispatcher, stream, serializer, and delegate binding for a single -/// function signature. The canonical way to configure a remote endpoint. -/// -/// @details `RemoteChannel` is the single object a user needs to declare per message -/// signature. It owns the `Dispatcher`, the serialization stream, and the internal -/// `DelegateFunctionRemote` that handles both sending and receiving. -/// -/// **Receive-side usage (preferred):** -/// @code -/// // Declare per signature — one channel replaces channel + separate delegate -/// std::optional> m_alarmChannel; -/// -/// // In Create(): -/// m_alarmChannel.emplace(GetRecvTransport(), m_alarmSer); -/// m_alarmChannel->Bind(this, &MyClass::OnAlarm, ALARM_ID); -/// m_alarmChannel->SetErrorHandler(MakeDelegate(this, &MyClass::OnError)); -/// RegisterEndpoint(ALARM_ID, m_alarmChannel->GetEndpoint()); -/// @endcode -/// -/// **Send-side usage — no Bind() required:** -/// @code -/// m_alarmChannel.emplace(GetSendTransport(), m_alarmSer, ALARM_ID); -/// -/// // Send (fire-and-forget): -/// (*m_alarmChannel)(msg); -/// -/// // Send (blocking wait): -/// RemoteInvokeWait(*m_alarmChannel, msg); -/// @endcode -/// -/// **Legacy MakeDelegate pattern (still supported):** -/// @code -/// auto d = MakeDelegate(&MyFunc, REMOTE_ID, channel); -/// @endcode -/// -/// `RemoteChannel` is non-copyable because it owns mutable stream state and the internal -/// delegate holds raw pointers into the channel. -/// -/// @tparam RetType The return type of the remote function. -/// @tparam Args The argument types of the remote function. -template -class RemoteChannel -{ - XALLOCATOR -public: - /// @brief Construct a RemoteChannel. - /// @details A send-only channel needs no `Bind()` — pass the remote ID here and - /// invoke the channel directly. The receive side must invoke `Bind()` to attach the - /// target function invoked on message arrival (`Bind()` overwrites the ID with the - /// same value). - /// @param[in] transport The transport used to send serialized data. Caller owns it. - /// @param[in] serializer The serializer matching the delegate signature. Caller owns it. - /// @param[in] id The remote delegate identifier shared with the receiver. - /// Optional for receive channels where `Bind()` supplies the ID. - RemoteChannel(transport::ITransport& transport, dmq::ISerializer& serializer, - DelegateRemoteId id = INVALID_REMOTE_ID) - : m_stream(std::ios::in | std::ios::out | std::ios::binary) - , m_serializer(&serializer) - { - m_dispatcher.SetTransport(&transport); - m_delegate.SetRemoteId(id); - m_delegate.SetDispatcher(&m_dispatcher); - m_delegate.SetSerializer(m_serializer); - m_delegate.SetStream(&m_stream); - m_delegate.SetSendMutex(&m_sendMutex); - } - - ~RemoteChannel() = default; - - // Non-copyable: owns stream state and internal delegate holds raw pointers into this object. - RemoteChannel(const RemoteChannel&) = delete; - RemoteChannel& operator=(const RemoteChannel&) = delete; - - // ----------------------------------------------------------------------- - // Delegate binding — preferred user-facing API (Item 2 / Item 4) - // ----------------------------------------------------------------------- - - /// @brief Bind a non-const member function as the receive-side handler. - /// @details Wires the internal delegate (dispatcher, serializer, stream) and sets - /// the target function in one call. Call this once in your Create()/Initialize(). - /// @param[in] object Raw pointer to the target object. - /// @param[in] func The non-const member function to call on receive. - /// @param[in] id The remote delegate identifier shared with the sender. - template - void Bind(TClass* object, RetType(TClass::* func)(Args...), DelegateRemoteId id) { - m_delegate.Bind([object, func](Args... args) -> RetType { - return (object->*func)(args...); - }, id); - ReconnectDelegate(); - } - - /// @brief Bind a const member function as the receive-side handler. - template - void Bind(const TClass* object, RetType(TClass::* func)(Args...) const, DelegateRemoteId id) { - m_delegate.Bind([object, func](Args... args) -> RetType { - return (object->*func)(args...); - }, id); - ReconnectDelegate(); - } - - /// @brief Bind a `std::function` as the receive-side handler. - void Bind(std::function func, DelegateRemoteId id) { - m_delegate.Bind(func, id); - ReconnectDelegate(); - } - - /// @brief Bind a raw lambda or functor as the receive-side handler. - template ::value>> - void Bind(F&& func, DelegateRemoteId id) { - m_delegate.Bind(std::forward(func), id); - ReconnectDelegate(); - } - - /// @brief Invoke the channel (fire-and-forget send). - /// @pre A remote ID is set: passed to the constructor, or set by SetRemoteId() or - /// Bind(). A send-only channel needs no Bind(). - /// Thread-safe: the internal delegate holds `m_sendMutex` while it sends. - void operator()(Args... args) { - m_delegate(std::forward(args)...); - } - - /// @brief Register an error handler delegate. - template - void SetErrorHandler(Handler&& handler) { - m_delegate.SetErrorHandler(std::forward(handler)); - } - - /// @brief Set the remote ID for outbound messages. - /// @param[in] id The remote delegate identifier. - void SetRemoteId(DelegateRemoteId id) noexcept { m_delegate.SetRemoteId(id); } - - /// @brief The remote ID set by the most recent Bind() or SetRemoteId() call. - DelegateRemoteId GetRemoteId() noexcept { return m_delegate.GetRemoteId(); } - - /// @brief The error status of the most recent invocation. - DelegateError GetError() noexcept { return m_delegate.GetError(); } - - /// @brief The sequence number assigned to the most recent send. - uint16_t GetLastSeqNum() const noexcept { return m_delegate.GetLastSeqNum(); } - - /// @brief Returns the internal delegate as an IRemoteInvoker* for RegisterEndpoint(). - IRemoteInvoker* GetEndpoint() noexcept { return &m_delegate; } - -private: - template - friend auto MakeDelegate(R(*)(A...), DelegateRemoteId, RemoteChannel&); - - template - friend auto MakeDelegate(C*, R(C::*)(A...), DelegateRemoteId, RemoteChannel&); - - template - friend auto MakeDelegate(C*, R(C::*)(A...) const, DelegateRemoteId, RemoteChannel&); - - template - friend auto MakeDelegate(const C*, R(C::*)(A...) const, DelegateRemoteId, RemoteChannel&); - - template - friend auto MakeDelegate(std::shared_ptr, R(C::*)(A...), DelegateRemoteId, RemoteChannel&); - - template - friend auto MakeDelegate(std::shared_ptr, R(C::*)(A...) const, DelegateRemoteId, RemoteChannel&); - - template - friend auto MakeDelegate(std::function, DelegateRemoteId, RemoteChannel&); - - template - friend auto MakeDelegate(F_&&, DelegateRemoteId, RemoteChannel&); - - /// @internal Used by MakeDelegate overloads. Prefer Bind() in application code. - dmq::IDispatcher* GetDispatcher() noexcept { return &m_dispatcher; } - - /// @internal Used by MakeDelegate overloads. Prefer Bind() in application code. - dmq::ISerializer* GetSerializer() noexcept { return m_serializer; } - - /// @internal Used by MakeDelegate overloads. Prefer Bind() in application code. - dmq::xostringstream& GetStream() noexcept { return m_stream; } - - /// @internal Used by MakeDelegate overloads. Every delegate sharing `m_stream` - /// must hold this mutex while it sends. - dmq::Mutex& GetSendMutex() noexcept { return m_sendMutex; } - -private: - void ReconnectDelegate() { - m_delegate.SetDispatcher(&m_dispatcher); - m_delegate.SetSerializer(m_serializer); - m_delegate.SetStream(&m_stream); - m_delegate.SetSendMutex(&m_sendMutex); - } - - /// Guards `m_stream` (and the dispatcher) for the channel's own delegate and - /// every delegate made from it by MakeDelegate(). - dmq::Mutex m_sendMutex; - Dispatcher m_dispatcher; - dmq::xostringstream m_stream; - dmq::ISerializer* m_serializer = nullptr; - DelegateFunctionRemote m_delegate; -}; - -/// @brief C++17 deduction guide — lets the compiler deduce `Sig` from the serializer type. -/// @details Enables `RemoteChannel channel(transport, serializer)` and -/// `RemoteChannel channel(transport, serializer, id)` without an explicit template argument. -template -RemoteChannel(transport::ITransport&, dmq::ISerializer&, DelegateRemoteId = INVALID_REMOTE_ID) -> RemoteChannel; - -// ---- MakeDelegate overloads for RemoteChannel ---------------------------------- -// -// These mirror the MakeDelegate(func, thread) async overloads exactly, but accept -// a RemoteChannel instead of an IThread, wiring up serializer, dispatcher, and -// stream in one step. - -/// @brief Creates a remote delegate bound to a free function via a RemoteChannel. -/// @param[in] func The free function to bind. -/// @param[in] id The remote delegate identifier shared with the receiver. -/// @param[in] channel The channel that provides dispatcher, serializer, and stream. -/// @return A fully configured `DelegateFreeRemote` ready to invoke remotely. -template -auto MakeDelegate(RetType(*func)(Args...), DelegateRemoteId id, RemoteChannel& channel) -{ - DelegateFreeRemote d(func, id); - d.SetDispatcher(channel.GetDispatcher()); - d.SetSerializer(channel.GetSerializer()); - d.SetStream(&channel.GetStream()); - d.SetSendMutex(&channel.GetSendMutex()); - return d; -} - -/// @brief Creates a remote delegate bound to a non-const member function via a RemoteChannel. -/// @param[in] object Raw pointer to the target object instance. -/// @param[in] func The non-const member function to bind. -/// @param[in] id The remote delegate identifier. -/// @param[in] channel The channel that provides dispatcher, serializer, and stream. -/// @return A fully configured `DelegateMemberRemote`. -template -auto MakeDelegate(TClass* object, RetType(TClass::* func)(Args...), DelegateRemoteId id, RemoteChannel& channel) -{ - DelegateMemberRemote d(object, func, id); - d.SetDispatcher(channel.GetDispatcher()); - d.SetSerializer(channel.GetSerializer()); - d.SetStream(&channel.GetStream()); - d.SetSendMutex(&channel.GetSendMutex()); - return d; -} - -/// @brief Creates a remote delegate bound to a const member function via a RemoteChannel. -/// @param[in] object Raw pointer to the target object instance. -/// @param[in] func The const member function to bind. -/// @param[in] id The remote delegate identifier. -/// @param[in] channel The channel that provides dispatcher, serializer, and stream. -/// @return A fully configured `DelegateMemberRemote`. -template -auto MakeDelegate(TClass* object, RetType(TClass::* func)(Args...) const, DelegateRemoteId id, RemoteChannel& channel) -{ - DelegateMemberRemote d(object, func, id); - d.SetDispatcher(channel.GetDispatcher()); - d.SetSerializer(channel.GetSerializer()); - d.SetStream(&channel.GetStream()); - d.SetSendMutex(&channel.GetSendMutex()); - return d; -} - -/// @brief Creates a remote delegate bound to a const member function on a const object. -/// @param[in] object Raw const pointer to the target object instance. -/// @param[in] func The const member function to bind. -/// @param[in] id The remote delegate identifier. -/// @param[in] channel The channel that provides dispatcher, serializer, and stream. -/// @return A fully configured `DelegateMemberRemote`. -template -auto MakeDelegate(const TClass* object, RetType(TClass::* func)(Args...) const, DelegateRemoteId id, RemoteChannel& channel) -{ - DelegateMemberRemote d(object, func, id); - d.SetDispatcher(channel.GetDispatcher()); - d.SetSerializer(channel.GetSerializer()); - d.SetStream(&channel.GetStream()); - d.SetSendMutex(&channel.GetSendMutex()); - return d; -} - -/// @brief Creates a remote delegate bound to a non-const member function via shared_ptr. -/// @param[in] object Shared pointer to the target object instance. -/// @param[in] func The non-const member function to bind. -/// @param[in] id The remote delegate identifier. -/// @param[in] channel The channel that provides dispatcher, serializer, and stream. -/// @return A fully configured `DelegateMemberRemote`. -template -auto MakeDelegate(std::shared_ptr object, RetType(TClass::* func)(Args...), DelegateRemoteId id, RemoteChannel& channel) -{ - DelegateMemberRemote d(object, func, id); - d.SetDispatcher(channel.GetDispatcher()); - d.SetSerializer(channel.GetSerializer()); - d.SetStream(&channel.GetStream()); - d.SetSendMutex(&channel.GetSendMutex()); - return d; -} - -/// @brief Creates a remote delegate bound to a const member function via shared_ptr. -/// @param[in] object Shared pointer to the target object instance. -/// @param[in] func The const member function to bind. -/// @param[in] id The remote delegate identifier. -/// @param[in] channel The channel that provides dispatcher, serializer, and stream. -/// @return A fully configured `DelegateMemberRemote`. -template -auto MakeDelegate(std::shared_ptr object, RetType(TClass::* func)(Args...) const, DelegateRemoteId id, RemoteChannel& channel) -{ - DelegateMemberRemote d(object, func, id); - d.SetDispatcher(channel.GetDispatcher()); - d.SetSerializer(channel.GetSerializer()); - d.SetStream(&channel.GetStream()); - d.SetSendMutex(&channel.GetSendMutex()); - return d; -} - -/// @brief Creates a remote delegate bound to a `std::function` via a RemoteChannel. -/// @param[in] func The `std::function` to bind. -/// @param[in] id The remote delegate identifier. -/// @param[in] channel The channel that provides dispatcher, serializer, and stream. -/// @return A fully configured `DelegateFunctionRemote`. -template -auto MakeDelegate(std::function func, DelegateRemoteId id, RemoteChannel& channel) -{ - DelegateFunctionRemote d(func, id); - d.SetDispatcher(channel.GetDispatcher()); - d.SetSerializer(channel.GetSerializer()); - d.SetStream(&channel.GetStream()); - d.SetSendMutex(&channel.GetSendMutex()); - return d; -} - -/// @brief Creates a remote delegate bound to a raw lambda or functor via a RemoteChannel. -template ::value>> -auto MakeDelegate(F&& func, DelegateRemoteId id, RemoteChannel& channel) -{ - DelegateFunctionRemote d(std::forward(func), id); - d.SetDispatcher(channel.GetDispatcher()); - d.SetSerializer(channel.GetSerializer()); - d.SetStream(&channel.GetStream()); - d.SetSendMutex(&channel.GetSendMutex()); - return d; -} - -} // namespace dmq - -#endif // REMOTE_CHANNEL_H diff --git a/DelegateMQ/extras/rpc/README.md b/DelegateMQ/extras/rpc/README.md deleted file mode 100644 index d929f8c..0000000 --- a/DelegateMQ/extras/rpc/README.md +++ /dev/null @@ -1,81 +0,0 @@ -# RPC Layer - -This directory contains **DelegateMQ**'s point-to-point RPC pattern: synchronous or fire-and-forget calls to a specific remote endpoint, as opposed to the topic-based publish/subscribe pattern in [`extras/databus`](../databus/README.md). - -## RemoteDispatcher vs. DataBus — Remote Function Invoke vs. Data Distribution - -DelegateMQ has two distinct patterns for talking across threads/processes/machines. Picking the wrong one for the job shows up as awkward code, not a compile error, so it's worth knowing which is which before starting: - -| | **RemoteDispatcher** (this directory) | **DataBus** ([`extras/databus`](../databus/README.md)) | -|---|---|---| -| Pattern | Point-to-point RPC (remote function invoke) | Publish/subscribe (data distribution) | -| Addressing | Remote ID → one specific registered endpoint | Topic string, many-to-many | -| Who receives | Exactly one endpoint per remote ID | Any number of subscribers (0, 1, or many) — the publisher doesn't know or care who | -| Call semantics | `RemoteInvokeWait()` blocks the caller until the remote ACKs or times out, returning success/failure directly — plus a fire-and-forget mode too | `Publish()` is always fire-and-forget from the caller's side; delivery outcome (if any) arrives later via `NetworkNode` signals (`OnPeerSendStatus`, `OnDeliveryFailed`) | -| How you use it | Compose: hold a `dmq::rpc::RemoteDispatcher` as a member (`NetworkMgr`), connect to its `OnError`/`OnStatus`/`OnDeliveryFailed` Signals — no subclassing required | Compose: hold an `ITransport&` (`Participant`), or instantiate `NetworkNode` — no subclassing required | -| Reliability opt-in | Per-connection — the owning class decides once whether to wrap its transport in `ReliableTransport` | Per-message — pass `Reliability::RELIABLE` or `UNRELIABLE` to `Send()` | -| Multi-peer topology | One connection per `RemoteDispatcher` instance; the app manages multiple peers itself if it needs more than one | Built in — `NetworkNode` manages any number of peers | -| Typical use | Commands, remote function calls, request/response where the caller needs to know the call landed | Sensor data, telemetry, status broadcasts, state that should reach whoever's currently interested | - -**Rule of thumb:** if you're asking "did that specific call succeed?" reach for RemoteDispatcher. If you're asking "who needs to know this happened?" reach for DataBus. - -## Overview - -`dmq::rpc::RemoteDispatcher` is designed to be held as a member (composition, not inheritance — matching `extras/databus`'s `Participant`/`NetworkNode` shape), and it owns the network thread and reliability plumbing ([`TransportMonitor`](../util/TransportMonitor.h), shared with `extras/databus`, not duplicated here) but never constructs or knows the concrete transport type. The owning, application-specific manager owns its own transport (e.g. `Win32UdpTransport`, `ZeroMqTransport`), optionally wraps it in [`ReliableTransport`](../util/ReliableTransport.h)+[`RetryMonitor`](../util/RetryMonitor.h) for ACK/retry reliability, and hands the result to `Attach()`. `RemoteDispatcher` only ever sees `dmq::transport::ITransport`, so it works with any transport that implements it — not a fixed list — and carries no per-transport branching itself. - -```cpp -class NetworkMgr -{ -public: - NetworkMgr() { - // ITransport has no Close(); SetCloseHandler() supplies the callback - // that closes whatever concrete transport(s) this class owns. Called - // by m_dispatcher.Stop() before the receive thread is joined. - m_dispatcher.SetCloseHandler(MakeDelegate(this, &NetworkMgr::CloseTransports)); - } - - int Create() { - // Construct and open the concrete transport, then hand it up. Wrap in - // ReliableTransport first if this transport needs ACK/retry reliability. - m_transport.Create(...); - m_dispatcher.Attach(m_transport, m_transport); - - m_alarmChannel.emplace(m_dispatcher.GetSendTransport(), m_alarmSer); - m_alarmChannel->Bind(this, &NetworkMgr::OnAlarm, ALARM_MSG_ID); - m_dispatcher.RegisterEndpoint(ALARM_MSG_ID, m_alarmChannel->GetEndpoint()); - return 0; - } - - // Fire-and-forget - void SendAlarm(AlarmMsg& msg) { (*m_alarmChannel)(msg); } - - // Blocking: waits for ACK or timeout, returns success/failure - bool SendCommandWait(CommandMsg& msg) { - return m_dispatcher.RemoteInvokeWait(*m_commandChannel, msg); - } - -private: - void CloseTransports() { m_transport.Close(); } - void OnAlarm(AlarmMsg& msg) { /* handle incoming alarm */ } - - // Composed, not inherited. - dmq::rpc::RemoteDispatcher m_dispatcher; - dmq::transport::SomeTransport m_transport; - dmq::serialization::serializer::Serializer m_alarmSer; - std::optional> m_alarmChannel; - std::optional> m_commandChannel; -}; -``` - -## Key Components - -* **`dmq::rpc::RemoteDispatcher.h`**: Manages the internal network thread and marshals calls onto it automatically. `RemoteInvokeWait()` blocks the caller until the message's final outcome — the one capability `DataBus::Publish()` (inherently async/fire-and-forget) doesn't provide. `true` means the remote ACKed it. With a RetryMonitor attached (`AttachRetryMonitor()`), a timeout means a retry follows, so the call waits through the retries and `false` means they ran out; without one, the first timeout returns `false`. The wait is bounded by `GetInvokeWaitLimit()` (9.4 s with the defaults); `RemoteInvokeWaitFor(channel, timeout, args...)` sets a shorter limit, in which case `false` can also mean "not ACKed yet" while retries continue. - * `Attach(sendTransport, recvTransport)` — call once (typically from the owning class's `Create()`, after its own transport member exists) to hand `RemoteDispatcher` the `ITransport&` it sends/receives through. - * `AttachRetryMonitor(retryMonitor)` — call once, after `Attach()`, only if the owning class layered `RetryMonitor`/`ReliableTransport` on top of its transport. Skip it for a self-reliable transport (e.g. ZeroMQ) that has no `RetryMonitor`. - * `SetCloseHandler(handler)` — supply a delegate that closes the concrete transport(s) the owning class owns; `ITransport` itself has no `Close()`. Called by `Stop()` before the receive thread is joined. Optional: if never set, this is a no-op. - * `GetThread()` / `GetTransportMonitor()` / `GetSendTransport()` — public accessors an owning class needs to marshal calls onto the network thread, wire a transport's `TransportMonitor`, and construct `RemoteChannel`s against the send transport. -* **`extras/dispatcher/RemoteChannel.h`**: The recommended way to configure a remote endpoint — aggregates the dispatcher, stream, serializer, and delegate binding for one message signature into a single object. `Bind()` registers the receive-side handler; `GetEndpoint()` returns the `IRemoteInvoker*` to pass to `RegisterEndpoint()`. See [`extras/dispatcher/README.md`](../dispatcher/README.md). - -## Transport Support - -Any transport implementing `dmq::transport::ITransport` works — `RemoteDispatcher` never constructs or names a concrete transport type itself, so there's no per-transport list to extend. This is also what `extras/databus`'s `Participant` already does generically; `RemoteDispatcher` now follows the same shape rather than the old `NetworkEngine`'s fixed `#if`/`#elif` chain over five transports. diff --git a/DelegateMQ/extras/rpc/RemoteDispatcher.cpp b/DelegateMQ/extras/rpc/RemoteDispatcher.cpp deleted file mode 100644 index c18e175..0000000 --- a/DelegateMQ/extras/rpc/RemoteDispatcher.cpp +++ /dev/null @@ -1,217 +0,0 @@ -// Needs a real thread port (DMQ_HAS_THREADING) and compiles to nothing on bare -// metal, so every DelegateMQ source file can be added to a build (see -// src/DelegateMQ.cpp). -#include "delegate/DelegateSelect.h" -#if defined(DMQ_HAS_THREADING) - -#include "RemoteDispatcher.h" -#include "extras/util/TimerDelegate.h" - -namespace dmq::rpc { - -using namespace dmq; -using namespace dmq::transport; -using dmq::util::TransportMonitor; -using dmq::util::RetryMonitor; - -RemoteDispatcher::RemoteDispatcher(dmq::Duration ackTimeout) - : m_thread("RemoteDispatcher", 25, dmq::os::FullPolicy::DROP) - , m_transportMonitor(ackTimeout) - , m_recvThread("NetworkRecv") -{ - m_statusConn = m_transportMonitor.OnSendStatus.Connect(dmq::MakeDelegate(this, &RemoteDispatcher::InternalStatusHandler)); - m_thread.CreateThread(); -} - -RemoteDispatcher::~RemoteDispatcher() -{ - Stop(); - m_thread.ExitThread(); -} - -void RemoteDispatcher::Attach(dmq::transport::ITransport& sendTransport, dmq::transport::ITransport& recvTransport) -{ - DMQ_ASSERT_TRUE(m_txTransport == nullptr && m_rxTransport == nullptr); // Attach() called more than once - m_txTransport = &sendTransport; - m_rxTransport = &recvTransport; - m_dispatcher.SetTransport(&sendTransport); -} - -void RemoteDispatcher::AttachRetryMonitor(RetryMonitor& retryMonitor) -{ - m_retryMonitor = &retryMonitor; - m_deliveryFailedConn = retryMonitor.OnDeliveryFailed.Connect(dmq::MakeDelegate(this, &RemoteDispatcher::InternalDeliveryFailedHandler)); -} - -dmq::Duration RemoteDispatcher::GetInvokeWaitLimit() const -{ - const dmq::Duration ack = m_transportMonitor.GetTimeout(); - int retries = m_retryMonitor ? m_retryMonitor->GetMaxRetries() : 0; - if (retries < 0) - retries = 0; - // Each attempt's TIMEOUT is seen up to one poll interval after it expires; - // half an ACK timeout on top is scheduling slack. - return (ack + TIMEOUT_POLL_INTERVAL) * (retries + 1) + ack / 2; -} - -dmq::transport::ITransport& RemoteDispatcher::GetSendTransport() -{ - DMQ_ASSERT_TRUE(m_txTransport != nullptr); // Attach() must be called first - return *m_txTransport; -} - -void RemoteDispatcher::Start() -{ - // Blocking marshal (matches Stop()'s own self-marshal below): a caller on - // another thread must see m_recvThread fully created before Start() - // returns, or a Start()-then-Stop() sequence from that same thread races - // Stop()'s direct (non-marshaled) m_recvThread.ExitThread() call against - // this method's own CreateThread() still running asynchronously on - // m_thread -- caught by ThreadSanitizer as a data race on StdlibThread's - // internal std::optional. - if (!m_thread.IsCurrentThread()) - return dmq::MakeDelegate(this, &RemoteDispatcher::Start, m_thread, dmq::WAIT_INFINITE)(); - - DMQ_ASSERT_TRUE(m_txTransport != nullptr && m_rxTransport != nullptr); // Attach() must be called first - - if (!m_recvThreadCreated) - { - m_recvThreadCreated = true; - m_recvThread.CreateThread(); - - // Post the "RecvThread" loop to run on this new thread. - dmq::MakeDelegate(this, &RemoteDispatcher::RecvThread, m_recvThread).AsyncInvoke(); - } - - m_timeoutTimerConn = m_timeoutTimer.OnExpired.Connect(dmq::util::MakeTimerDelegate(this, &RemoteDispatcher::Timeout, m_thread)); - m_timeoutTimer.Start(TIMEOUT_POLL_INTERVAL); -} - -void RemoteDispatcher::Stop() -{ - if (!m_thread.IsCurrentThread()) { - if (m_recvThreadExit) return; - - // 1. Signal exit flag FIRST so RecvThread knows it should terminate - m_recvThreadExit = true; - - // 2. Close transports to unblock any pending Receive() calls. - // This is necessary because some transports (like sockets) are blocking - // and won't return until a message arrives or the resource is closed. - // ITransport has no Close() of its own -- the owning class supplies a - // handler via SetCloseHandler() to close whichever concrete - // transport(s) it owns. Optional: if never set, this is a no-op. - if (m_closeHandler) - m_closeHandler(); - - // 3. Exit/Join the receive thread. - m_recvThread.ExitThread(); - - // 4. Marshal the rest of the cleanup to the Network Thread. - return dmq::MakeDelegate(this, &RemoteDispatcher::Stop, m_thread, dmq::WAIT_INFINITE)(); - } - m_timeoutTimer.Stop(); - m_timeoutTimerConn.Disconnect(); - m_statusConn.Disconnect(); - m_deliveryFailedConn.Disconnect(); -} - -void RemoteDispatcher::RegisterEndpoint(dmq::DelegateRemoteId id, dmq::IRemoteInvoker* endpoint) -{ - // Thread Safety: Ensure this runs on the Network Thread to avoid - // racing with 'Incoming()' which reads this map. - if (!m_thread.IsCurrentThread()) - { - // Marshal the call to the Network Thread. Cast disambiguates the overload - // set now that RegisterEndpoint() has a templated RemoteChannel sibling. - using RegisterEndpointFn = void (RemoteDispatcher::*)(dmq::DelegateRemoteId, dmq::IRemoteInvoker*); - dmq::MakeDelegate(this, static_cast(&RemoteDispatcher::RegisterEndpoint), m_thread, dmq::WAIT_INFINITE)(id, endpoint); - return; - } - - // Actual insertion (Safe because we are now on the correct thread) - m_receiveIdMap[id] = endpoint; -} - -//------------------------------------------------------------------------------ -// RecvThread -//------------------------------------------------------------------------------ -/// @brief The main loop for the background receive thread. -void RemoteDispatcher::RecvThread() -{ - // Timeout for enqueuing the message to the main thread. - static const std::chrono::milliseconds INVOKE_TIMEOUT(1000); - - std::shared_ptr arg_data; - - while (!m_recvThreadExit) - { - DmqHeader header; - - // Only allocate a new stream if we dispatched the previous one - if (!arg_data) { - arg_data = dmq::xmake_shared(std::ios::in | std::ios::out | std::ios::binary); - } else { - // Reuse the existing stream: clear error flags and empty its contents - arg_data->clear(); - arg_data->str(dmq::xstring()); - } - - // Block reading from the physical transport - int error = m_rxTransport->Receive(*arg_data, header); - - if (!error && !arg_data->str().empty() && !m_recvThreadExit) - { - // Dispatch processing to the main RemoteDispatcher thread. - // Passes ownership of the data stream via shared_ptr (no deep copy). - dmq::MakeDelegate(this, &RemoteDispatcher::Incoming, m_thread, INVOKE_TIMEOUT).AsyncInvoke(header, arg_data); - - // Release our local reference so a new one is allocated next iteration - arg_data.reset(); - } - else if (error < 0 && !m_recvThreadExit) - { - // Negative is a genuine transport fault (bad frame, socket error); - // ITransport::RECEIVE_NO_DATA (a receive timeout) is not reported. - // The m_recvThreadExit guard excludes the one expected non-fault - // case: Stop() closing the socket to unblock this call. - InternalErrorHandler(dmq::INVALID_REMOTE_ID, dmq::DelegateError::ERR_TRANSPORT_RECEIVE, error); - } - } -} - -//------------------------------------------------------------------------------ -// Incoming -//------------------------------------------------------------------------------ -/// @brief Handles incoming messages on the main Network Thread. -void RemoteDispatcher::Incoming(DmqHeader& header, std::shared_ptr arg_data) -{ - // Filter out ACKs; we only dispatch application data here. - if (header.GetId() != dmq::ACK_REMOTE_ID) { - // Find the registered endpoint for this Message ID - auto it = m_receiveIdMap.find(header.GetId()); - - // If found and valid, let the endpoint handle deserialization and execution - if (it != m_receiveIdMap.end() && it->second) { - it->second->Invoke(*arg_data); - } - } -} - -void RemoteDispatcher::Timeout() { m_transportMonitor.Process(); } - -void RemoteDispatcher::InternalErrorHandler(dmq::DelegateRemoteId id, dmq::DelegateError error, dmq::DelegateErrorAux aux) { - OnError(id, error, aux); -} - -void RemoteDispatcher::InternalStatusHandler(dmq::DelegateRemoteId id, uint16_t seq, TransportMonitor::Status status) { - OnStatus(id, seq, status); -} - -void RemoteDispatcher::InternalDeliveryFailedHandler(dmq::DelegateRemoteId id, uint16_t seqNum) { - OnDeliveryFailed(id, seqNum); -} - -} // namespace dmq::rpc - -#endif // DMQ_HAS_THREADING diff --git a/DelegateMQ/extras/rpc/RemoteDispatcher.h b/DelegateMQ/extras/rpc/RemoteDispatcher.h deleted file mode 100644 index 6dbed45..0000000 --- a/DelegateMQ/extras/rpc/RemoteDispatcher.h +++ /dev/null @@ -1,488 +0,0 @@ -/// @file RemoteDispatcher.h -/// @brief Base class for point-to-point RPC over any dmq::transport::ITransport, -/// handling threading and synchronization generically. -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. - -#ifndef REMOTE_DISPATCHER_H -#define REMOTE_DISPATCHER_H - -#include "delegate/DelegateAsync.h" -#include "delegate/DelegateAsyncWait.h" -#include "delegate/Semaphore.h" -#include "delegate/Signal.h" -#include "delegate/UnicastDelegate.h" -#include "extras/rpc/RemoteEndpoint.h" -#include "extras/util/TransportMonitor.h" -#include "extras/util/RetryMonitor.h" -#include "extras/dispatcher/RemoteChannel.h" -#include "port/transport/common/ITransport.h" -#include -#include -#include - -#if defined(DMQ_THREAD_STDLIB) - #include "port/os/stdlib/StdlibThread.h" -#elif defined(DMQ_THREAD_WIN32) - #include "port/os/win32/Win32Thread.h" -#elif defined(DMQ_THREAD_POSIX) - #include "port/os/posix/PosixThread.h" -#elif defined(DMQ_THREAD_FREERTOS) - #include "port/os/freertos/FreeRTOSThread.h" -#elif defined(DMQ_THREAD_THREADX) - #include "port/os/threadx/ThreadXThread.h" -#elif defined(DMQ_THREAD_ZEPHYR) - #include "port/os/zephyr/ZephyrThread.h" -#elif defined(DMQ_THREAD_CMSIS_RTOS2) - #include "port/os/cmsis-rtos2/CmsisRtos2Thread.h" -#endif - -namespace dmq::rpc { - -// TransportMonitor/RetryMonitor/Timer live in dmq::util (shared reliability -// plumbing with extras/databus, not duplicated here) -- pulled in by name -// rather than `using namespace dmq::util;` so this header doesn't leak all of -// dmq::util into anyone who later reopens namespace dmq::rpc themselves. -using dmq::util::TransportMonitor; -using dmq::util::RetryMonitor; -using dmq::util::Timer; - -/// @brief Base class for handling point-to-point RPC transport, threading, and -/// synchronization. -/// -/// @details RemoteDispatcher encapsulates the "plumbing" of point-to-point remote -/// calls -- transport dispatch, the receive thread, ACK/timeout bookkeeping -- -/// entirely behind `dmq::transport::ITransport`. It never constructs or knows -/// the concrete transport type: an owning class constructs its own transport -/// (Win32UdpTransport, ZeroMqTransport, ...), optionally wraps it in -/// ReliableTransport for ACK/retry reliability, and hands the result to -/// Attach(). This works with any transport that implements ITransport, not a -/// fixed list, and keeps this class itself free of per-transport branching. -/// -/// **Key Responsibilities:** -/// * **Lifecycle Management:** Controls the startup and shutdown of the -/// receiver thread. -/// * **Thread Synchronization:** Marshals all outgoing network calls to a -/// dedicated network thread to ensure thread safety and prevent blocking -/// the caller's UI or logic threads. -/// * **Message Routing:** Maps incoming data (by ID) to specific -/// `DelegateMemberRemote` instances via `RegisterEndpoint`. -/// * **Reliability:** Integrates with `TransportMonitor` to handle -/// Acknowledgments (ACKs) and retransmissions/timeouts. -/// -/// @note Designed to be held as a member (composition), not inherited from -- -/// matching `extras/databus`'s Participant/NetworkNode shape. Status is -/// reported via public Signal members (OnError/OnStatus/OnDeliveryFailed -/// below); transport lifecycle (constructing/closing the concrete transport) -/// is wired through Attach()/SetCloseHandler(). An owning class never needs -/// to subclass RemoteDispatcher just to plug into it. -class RemoteDispatcher -{ -public: - /// @param ackTimeout How long a sent message waits for its ACK before - /// TIMEOUT (the internal TransportMonitor's timeout). Defaults to - /// dmq::TRANSPORT_MONITOR_TIMEOUT (DMQ_TRANSPORT_MONITOR_TIMEOUT_SEC). - explicit RemoteDispatcher(dmq::Duration ackTimeout = dmq::TRANSPORT_MONITOR_TIMEOUT); - ~RemoteDispatcher(); - - RemoteDispatcher(const RemoteDispatcher&) = delete; - RemoteDispatcher& operator=(const RemoteDispatcher&) = delete; - - /// @brief Fires when a channel/endpoint reports a technical error - /// (serialization failure, type mismatch, etc.) via SetErrorHandler(). - dmq::Signal OnError; - - /// @brief Fires on every send-status update from the internal - /// TransportMonitor (e.g. TIMEOUT while a RELIABLE message is still - /// being retried, or SUCCESS on ACK). Not the same as OnDeliveryFailed: - /// a message can report TIMEOUT several times while still retrying - /// before either succeeding or finally exhausting its retry budget. - dmq::Signal OnStatus; - - /// @brief Fires when a RELIABLE message exhausts its retry budget - /// without being ACKed (RetryMonitor::OnDeliveryFailed). Only fires if - /// the derived class called AttachRetryMonitor(). - dmq::Signal OnDeliveryFailed; - - /// @brief Attach the transport(s) this engine sends/receives through. - /// @details Call exactly once, after the owning class's own transport - /// member(s) are constructed and before Start()/any send -- e.g. from the - /// owning class's constructor body or a separate Create()-style init - /// method. The owning class retains ownership; sendTransport/recvTransport - /// must outlive this object. Pass a decorator (e.g. a ReliableTransport - /// wrapping a raw one) as sendTransport to add ACK/retry reliability on - /// top of an unreliable transport -- RemoteDispatcher only ever sees the - /// ITransport interface, so it neither knows nor cares. - /// @param sendTransport Transport used for outgoing sends; also the - /// transport GetSendTransport() returns for - /// constructing RemoteChannel instances against. - /// @param recvTransport Transport used for the blocking receive loop. - void Attach(dmq::transport::ITransport& sendTransport, dmq::transport::ITransport& recvTransport); - - /// @brief Optionally wire a RetryMonitor's delivery-failure signal to - /// this engine's own OnDeliveryFailed signal. - /// @details Call once, after Attach(), only if the owning class layered - /// RetryMonitor/ReliableTransport on top of its transport for ACK/retry - /// reliability. Skip this call for a self-reliable transport (e.g. - /// ZeroMQ) that has no RetryMonitor. - /// Once attached, RemoteInvokeWait() treats a TIMEOUT as a retry in - /// progress and waits for the final ACK or delivery failure, so the - /// RetryMonitor must be built on GetTransportMonitor(). - /// @param retryMonitor The independently-owned RetryMonitor whose - /// OnDeliveryFailed signal should forward here. - void AttachRetryMonitor(RetryMonitor& retryMonitor); - - /// @brief Set the handler Stop() calls to close the underlying - /// transport(s). - /// @details Call once, any time before Stop() (typically right after - /// Attach()). Necessary because some transports (sockets, serial ports) - /// are blocking and won't return from Receive() until a message arrives - /// or the resource is closed -- ITransport itself has no Close() (its - /// concrete transports each expose their own), so Stop() calls this - /// handler at the exact point closing needs to happen: after the exit - /// flag is set, before the receive thread is joined. - /// @param handler Called by Stop() to close the transport(s). Optional - /// -- if never set, Stop() simply skips this step, same - /// as the old CloseTransports() hook's no-op default. - void SetCloseHandler(dmq::UnicastDelegate handler) { m_closeHandler = std::move(handler); } - - /// @brief Returns the network thread this engine dispatches on. - /// @details Use `GetThread().IsCurrentThread()` for thread-affinity checks, - /// or pass `GetThread()` as the destination thread to `dmq::MakeDelegate(...)` - /// when marshaling a call from the owning class onto the network thread. - dmq::os::Thread& GetThread() { return m_thread; } - - /// @brief Returns the internal TransportMonitor, for wiring into whichever - /// concrete transport(s) the owning class constructs, e.g. - /// `transport.SetTransportMonitor(&GetTransportMonitor())`. - TransportMonitor& GetTransportMonitor() { return m_transportMonitor; } - - /// @brief Returns the transport passed as `sendTransport` to Attach(), for - /// use by RemoteChannel instances. - /// @details Pass this to RemoteChannel constructors so each channel owns - /// its own Dispatcher while sharing the same physical transport. - /// Hard-faults if called before Attach(). - dmq::transport::ITransport& GetSendTransport(); - - /// @brief Starts the network engine and its receiving thread. - /// - /// @details This method initializes the internal `RecvThread` to begin polling the - /// transport layer for incoming messages. It also starts the `Timeout` timer used - /// by the `TransportMonitor` to track unacknowledged messages. - /// - /// @note This method is thread-safe and will automatically marshal the call to the - /// internal Network Thread if called from a different context. Requires Attach() - /// to have been called first. - void Start(); - - /// @brief Stops the network engine and releases resources. - /// - /// @details This method gracefully shuts down the `RecvThread`, stops the timeout - /// timer, and calls the handler set via SetCloseHandler() (if any) so the - /// owning class can close its underlying transport socket(s). It ensures - /// that all internal threads are joined before returning to prevent - /// resource leaks. - /// - /// @note This call blocks until the shutdown sequence is complete. - void Stop(); - - /// @brief Registers a remote endpoint with the network engine. - /// - /// @details This function maps a unique `DelegateRemoteId` to a specific - /// `DelegateMemberRemote` instance (via the `IRemoteInvoker` interface). - /// When the `RemoteDispatcher` receives data from the transport layer, it - /// uses the message ID to look up the registered endpoint in this map and - /// invokes it to deserialize and handle the payload. - /// - /// @param id The unique identifier for the remote message type. - /// @param endpoint Pointer to the endpoint instance responsible for - /// handling this ID. - void RegisterEndpoint(dmq::DelegateRemoteId id, dmq::IRemoteInvoker* endpoint); - - /// @brief Registers a RemoteChannel endpoint and automatically wires its - /// error handler to fire this RemoteDispatcher's OnError signal. - /// @details Equivalent to calling `channel.SetErrorHandler(...)` followed - /// by `RegisterEndpoint(id, channel.GetEndpoint())`. Prefer this overload - /// so a new channel's send and receive errors are never left unreported. - /// Call `channel.SetErrorHandler(...)` again afterward to override with a - /// custom per-channel handler. - /// @param id The unique identifier for the remote message type. - /// @param channel The RemoteChannel instance responsible for handling - /// this ID. - template - void RegisterEndpoint(dmq::DelegateRemoteId id, dmq::RemoteChannel& channel) { - channel.SetErrorHandler(dmq::MakeDelegate(this, &RemoteDispatcher::InternalErrorHandler)); - RegisterEndpoint(id, channel.GetEndpoint()); - } - - /// @brief Generic helper function to synchronously invoke a remote - /// delegate. - /// - /// @details Blocks the calling thread until the message's final outcome: - /// 1. The remote endpoint acknowledges it (ACK): returns `true`. - /// 2. It is abandoned: returns `false`. With a RetryMonitor attached - /// (AttachRetryMonitor()) that means its retries ran out - /// (`OnDeliveryFailed`); intermediate TIMEOUTs are retries in progress - /// and don't end the wait. Without one, the first TIMEOUT is final. - /// - /// The wait is bounded by GetInvokeWaitLimit(), which covers the whole - /// retry window. Use RemoteInvokeWaitFor() for a shorter limit. - /// - /// **Thread Synchronization Logic:** - /// * **If called from the Network Thread:** The send operation executes - /// immediately and returns the result of the transport send call. No - /// blocking wait occurs because we are already on the thread - /// responsible for I/O. - /// * **If called from any other thread:** The call is marshaled to the - /// Network Thread. The calling thread blocks on a condition variable. - /// When the Network Thread receives an ACK (or timeout), it signals the - /// condition variable to wake up the caller. - /// - /// @tparam TClass The class type of the remote endpoint (usually - /// inferred). - /// @tparam RetType The return type of the function signature (usually - /// void). - /// @tparam Args The argument types of the function signature. - /// @param endpoint The specific `RemoteEndpoint` instance to invoke. - /// @param args The arguments to forward to the remote function. - /// @return `true` if the remote acknowledged the message; `false` on - /// timeout or transport failure. - template - bool RemoteInvokeWait(dmq::DelegateMemberRemote& endpoint, Args&&... args) - { - return RemoteInvokeWaitInternal, Args...>( - endpoint, GetInvokeWaitLimit(), std::forward(args)...); - } - - /// @brief RemoteInvokeWait() with a caller-supplied limit on the wait. - /// @details If `timeout` expires before the final outcome, returns `false` - /// though the message may still be delivered: retries continue in the - /// background. Use it when the caller can't block for the whole retry window. - /// @param endpoint The specific `RemoteEndpoint` instance to invoke. - /// @param timeout The most the caller waits. - /// @param args The arguments to forward to the remote function. - /// @return `true` if the remote acknowledged the message within `timeout`. - template - bool RemoteInvokeWaitFor(dmq::DelegateMemberRemote& endpoint, dmq::Duration timeout, Args&&... args) - { - return RemoteInvokeWaitInternal, Args...>( - endpoint, timeout, std::forward(args)...); - } - - /// @brief Overload of RemoteInvokeWait that accepts a RemoteChannel - /// directly. - /// @details Equivalent to the DelegateMemberRemote overload; routes - /// through the channel's internal delegate. Prefer this when the - /// endpoint is managed by a RemoteChannel (i.e. configured via - /// `channel.Bind()`). - /// @tparam RetType The return type of the function signature (usually - /// void). - /// @tparam Args The argument types of the function signature. - /// @param channel The RemoteChannel instance to invoke. - /// @param args The arguments to forward to the remote function. - /// @return `true` if the remote acknowledged the message; `false` on - /// timeout or transport failure. - template - bool RemoteInvokeWait(dmq::RemoteChannel& channel, Args&&... args) - { - return RemoteInvokeWaitInternal, Args...>( - channel, GetInvokeWaitLimit(), std::forward(args)...); - } - - /// @brief RemoteInvokeWait() on a RemoteChannel with a caller-supplied limit. - /// @details See the DelegateMemberRemote overload of RemoteInvokeWaitFor(). - template - bool RemoteInvokeWaitFor(dmq::RemoteChannel& channel, dmq::Duration timeout, Args&&... args) - { - return RemoteInvokeWaitInternal, Args...>( - channel, timeout, std::forward(args)...); - } - - /// @brief Default limit for RemoteInvokeWait(): - /// (retries + 1) x (ACK timeout + TIMEOUT_POLL_INTERVAL) + ACK timeout / 2. - /// Each attempt's TIMEOUT can be reported up to one poll interval late; the - /// half ACK timeout is scheduling slack. Retries are 0 without a - /// RetryMonitor attached. With the defaults (2 s, 3 retries): 9.4 s. - dmq::Duration GetInvokeWaitLimit() const; - - /// How often the network thread checks for ACK timeouts. - static constexpr std::chrono::milliseconds TIMEOUT_POLL_INTERVAL{ 100 }; - -private: - dmq::os::Thread m_thread; - Dispatcher m_dispatcher; - TransportMonitor m_transportMonitor; - dmq::UnicastDelegate m_closeHandler; - - /// @brief Shared synchronization state for RemoteInvokeWaitInternal(). - /// @details All fields are guarded by `mtx`. The dispatched sequence number - /// is not known until the send executes on the network thread, but the final - /// outcome (ACK, final TIMEOUT, or delivery failure) can arrive first — e.g. - /// on a loopback transport, or an immediate send failure inside the send. - /// Outcomes that arrive before the seq is recorded are buffered in `early` - /// and reconciled by the send lambda, so a fast one is never lost. - struct InvokeWaitState { - bool complete = false; ///< Final outcome received for expectedSeq - bool success = false; ///< Final outcome was an ACK - bool seqSet = false; ///< expectedSeq is valid - uint16_t expectedSeq = 0; ///< Seq assigned to the dispatched message - /// Final outcomes (true = ACKed) received before seqSet, by seq. - dmq::xmap early; - - /// @brief Record a final outcome for `seq`. - /// @return true if it completed the wait, so the caller must Signal(). - bool Report(uint16_t seq, bool acked) { - dmq::LockGuard lock(mtx); - if (!seqSet) { - early.emplace(seq, acked); // keep the first outcome per seq - return false; - } - if (complete || seq != expectedSeq) - return false; - complete = true; - success = acked; - return true; - } - dmq::Mutex mtx; // Generic Mutex - dmq::Semaphore sem; // Portable wake signal (DMQ_HAS_SEMAPHORE is - // available everywhere this file is included -- - // see DelegateMQ.h's #if defined(DMQ_HAS_SEMAPHORE) - // guard -- unlike dmq::ConditionVariable, which - // has no port on Zephyr/CMSIS-RTOS2/NuttX) - XALLOCATOR - }; - - /// @brief Shared implementation for both RemoteInvokeWait() overloads. - /// @tparam Target A sender exposing operator()(Args...), GetRemoteId(), - /// GetError(), and GetLastSeqNum() -- i.e. - /// DelegateMemberRemote or RemoteChannel. - template - bool RemoteInvokeWaitInternal(Target& target, dmq::Duration timeout, Args&&... args) - { - // [Network Thread] Already on the correct thread: send immediately, - // no blocking wait is possible (we would deadlock waiting on ourselves). - if (m_thread.IsCurrentThread()) - { - target(std::forward(args)...); - return (target.GetError() == dmq::DelegateError::SUCCESS); - } - - // 1. [Caller Thread] Create shared synchronization state. - auto state = dmq::xmake_shared(); - dmq::DelegateRemoteId remoteId = target.GetRemoteId(); - - // 2. [Caller Thread] Define the callbacks that report the final outcome. - // With a RetryMonitor attached, a TIMEOUT only means a retry follows; the - // message is final on SUCCESS or on the RetryMonitor's delivery failure. - // Without one, the first TIMEOUT is final. - const bool retrying = (m_retryMonitor != nullptr); - std::function statusCbFunc = - [state, remoteId, retrying](dmq::DelegateRemoteId id, uint16_t seq, TransportMonitor::Status status) { - if (id != remoteId) - return; - const bool acked = (status == TransportMonitor::Status::SUCCESS); - if (!acked && retrying) - return; - if (state->Report(seq, acked)) - state->sem.Signal(); - }; - std::function failedCbFunc = - [state, remoteId](dmq::DelegateRemoteId id, uint16_t seq) { - if (id == remoteId && state->Report(seq, false)) - state->sem.Signal(); - }; - - // 3. [Caller Thread] Register the callbacks. - dmq::ScopedConnection conn = m_transportMonitor.OnSendStatus.Connect(dmq::MakeDelegate(statusCbFunc)); - dmq::ScopedConnection failedConn; - if (retrying) - failedConn = OnDeliveryFailed.Connect(dmq::MakeDelegate(failedCbFunc)); - - // 4. [Caller Thread] Define the "Send" logic lambda. - auto* targetPtr = ⌖ - std::function asyncCallFunc = [targetPtr, state](auto&&... fwdArgs) -> bool { - (*targetPtr)(std::forward(fwdArgs)...); - bool notify = false; - { - dmq::LockGuard lock(state->mtx); - state->expectedSeq = targetPtr->GetLastSeqNum(); - state->seqSet = true; - - // Reconcile an outcome that arrived before the seq was known - auto it = state->early.find(state->expectedSeq); - if (it != state->early.end()) { - state->complete = true; - state->success = it->second; - notify = true; - } - - state->early.clear(); - } - if (notify) - state->sem.Signal(); - return (targetPtr->GetError() == dmq::DelegateError::SUCCESS); - }; - - // 5. [Caller Thread] Dispatch the lambda to the Network Thread queue. - // Must block until asyncCallFunc actually runs (or throws) on the network - // thread rather than timing out on the *queueing* wait: asyncCallFunc - // captures a raw pointer to the caller's `target`. If this wait timed out - // while the message was still queued (a short SEND_TIMEOUT was previously - // used here), a caller seeing "failed" could free `target` while the - // still-queued closure later runs against a dangling pointer. Every other - // marshal-to-network-thread call site in this file (Start, RegisterEndpoint, - // Stop) uses WAIT_INFINITE for the same reason. - auto retVal = dmq::MakeDelegate(std::move(asyncCallFunc), m_thread, dmq::WAIT_INFINITE) - .AsyncInvoke(std::forward(args)...); - - if (retVal.has_value() && retVal.value() == true) - { - // 6. [Caller Thread] BLOCK until the status callback (or the send - // lambda's reconciliation) completes the wait, or timeout. Whichever - // lambda sets state->complete/state->success calls state->sem.Signal() - // exactly once, outside the lock; Signal()-before-Wait() is safe since - // dmq::Semaphore retains its signaled state (see delegate/Semaphore.h). - // If Wait() times out, state->success is still correctly read below -- - // it was initialized false and nothing sets it without also signaling. - state->sem.Wait(timeout); - dmq::LockGuard lock(state->mtx); - return state->success; - } - - // 7. [Caller Thread] Send failed or timed out queueing to the network - // thread. 'conn' disconnects on scope exit; 'state' stays alive via - // shared_ptr if a late status callback races with our return. - dmq::LockGuard lock(state->mtx); - return state->success; - } - - void RecvThread(); - void Incoming(dmq::transport::DmqHeader& header, std::shared_ptr arg_data); - void Timeout(); - void InternalErrorHandler(dmq::DelegateRemoteId id, dmq::DelegateError error, dmq::DelegateErrorAux aux); - void InternalStatusHandler(dmq::DelegateRemoteId id, uint16_t seq, TransportMonitor::Status status); - void InternalDeliveryFailedHandler(dmq::DelegateRemoteId id, uint16_t seqNum); - - dmq::os::Thread m_recvThread; - std::atomic m_recvThreadExit{ false }; - bool m_recvThreadCreated = false; - Timer m_timeoutTimer; - dmq::ScopedConnection m_timeoutTimerConn; - - // Set by Attach(). Not owned -- the derived class retains ownership of - // whatever concrete transport(s) these point to. - dmq::transport::ITransport* m_txTransport = nullptr; - dmq::transport::ITransport* m_rxTransport = nullptr; - - dmq::xmap m_receiveIdMap; - dmq::ScopedConnection m_statusConn; - dmq::ScopedConnection m_deliveryFailedConn; - - /// Set by AttachRetryMonitor(); not owned. Decides whether a TIMEOUT is - /// final for RemoteInvokeWait() and sizes GetInvokeWaitLimit(). - RetryMonitor* m_retryMonitor = nullptr; -}; - -} // namespace dmq::rpc - -#endif // REMOTE_DISPATCHER_H diff --git a/DelegateMQ/extras/rpc/RemoteEndpoint.h b/DelegateMQ/extras/rpc/RemoteEndpoint.h deleted file mode 100644 index ee4c5ee..0000000 --- a/DelegateMQ/extras/rpc/RemoteEndpoint.h +++ /dev/null @@ -1,80 +0,0 @@ -#ifndef REMOTE_ENDPOINT_H -#define REMOTE_ENDPOINT_H - -#include "delegate/DelegateRemote.h" -#include "port/transport/common/ITransport.h" -#include "port/transport/common/DmqHeader.h" -#include - -namespace dmq::rpc { - -template -struct RemoteEndpoint; // Not defined - -/// @brief `RemoteEndpoint` wraps a `DelegateMemberRemote` and its associated -/// transport infrastructure into a single, cohesive unit. -/// @details This structure is designed to simplify the management of remote -/// endpoints by grouping the delegate, the transport, and the necessary stream -/// for serialization. -/// @tparam TClass The class type that contains the member function. -/// @tparam RetType The return type of the member function. -/// @tparam Args The types of the function arguments. -template -struct RemoteEndpoint -{ - XALLOCATOR - /// @brief The `DelegateMemberRemote` object that handles the remote invocation. - dmq::DelegateMemberRemote delegate; - - /// @brief The transport used to send the serialized data. - dmq::transport::ITransport* transport = nullptr; - - /// @brief The stream used for serializing the function arguments. - dmq::xostringstream stream; - - /// @brief The identifier for the remote endpoint. - dmq::DelegateRemoteId id = 0; - - /// @brief Constructor to initialize the remote endpoint. - /// @param[in] obj A shared pointer to the instance of `TClass`. - /// @param[in] func A pointer to the member function of `TClass`. - /// @param[in] _transport The transport to be used for remote communication. - /// @param[in] _id The remote identifier for this endpoint. - RemoteEndpoint(std::shared_ptr obj, RetType(TClass::* func)(Args...), dmq::transport::ITransport& _transport, dmq::DelegateRemoteId _id) - : delegate(obj, func, _id), transport(&_transport), stream(std::ios::in | std::ios::out | std::ios::binary), id(_id) - { - } -}; - -/// @brief Partial specialization of `RemoteEndpoint` for free functions. -/// @tparam RetType The return type of the function. -/// @tparam Args The types of the function arguments. -template -struct RemoteEndpoint -{ - XALLOCATOR - /// @brief The `DelegateFreeRemote` object that handles the remote invocation. - dmq::DelegateFreeRemote delegate; - - /// @brief The transport used to send the serialized data. - dmq::transport::ITransport* transport = nullptr; - - /// @brief The stream used for serializing the function arguments. - dmq::xostringstream stream; - - /// @brief The identifier for the remote endpoint. - dmq::DelegateRemoteId id = 0; - - /// @brief Constructor to initialize the remote endpoint for a free function. - /// @param[in] func A pointer to the free function. - /// @param[in] _transport The transport to be used for remote communication. - /// @param[in] _id The remote identifier for this endpoint. - RemoteEndpoint(RetType(*func)(Args...), dmq::transport::ITransport& _transport, dmq::DelegateRemoteId _id) - : delegate(func, _id), transport(&_transport), stream(std::ios::in | std::ios::out | std::ios::binary), id(_id) - { - } -}; - -} // namespace dmq::rpc - -#endif diff --git a/DelegateMQ/extras/util/AsyncInvoke.h b/DelegateMQ/extras/util/AsyncInvoke.h deleted file mode 100644 index bd4c838..0000000 --- a/DelegateMQ/extras/util/AsyncInvoke.h +++ /dev/null @@ -1,153 +0,0 @@ -#ifndef ASYNC_INVOKE_H -#define ASYNC_INVOKE_H - -/// @file AsyncInvoke.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// @brief Helper functions for simplified, one-line asynchronous function invocation. -/// -/// @details -/// The `AsyncInvoke` helper functions provide a convenient wrapper around the -/// DelegateMQ library to execute any callable (free function, lambda, or member function) -/// on a specific target thread. -/// -/// **Key Features:** -/// * **Automatic Context Switching:** Automatically detects if the caller is already -/// execute on the target thread. -/// - If **Yes**: It executes the function synchronously (immediately) to avoid overhead. -/// - If **No**: It creates a temporary asynchronous delegate, marshals the arguments, -/// and executes the function on the target thread. -/// * **Blocking Wait:** Supports a timeout parameter to wait for the asynchronous -/// execution to complete and return a value. -/// * **Return Value Handling:** Safely retrieves the return value from the target -/// function across thread boundaries. - -#include "delegate/DelegateRemote.h" -#include "delegate/DelegateAsync.h" -#include "delegate/IThread.h" -#include "delegate/DelegateOpt.h" -#include "extras/dispatcher/RemoteChannel.h" -#include -#include -#include -#include -#include - -namespace dmq::util { - -/// Helper function to simplify asynchronous invoke of a free function/lambda. -/// @param[in] func - the function/lambda to invoke -/// @param[in] thread - the thread to invoke func on -/// @param[in] timeout - the time to wait for invoke to complete -/// @param[in] args - the function argument(s) passed to func -template -auto AsyncInvoke(Func func, dmq::IThread& thread, const dmq::Duration& timeout, Args&&... args) -{ - // Deduce return type - using RetType = decltype(func(std::forward(args)...)); - - // Is the calling function executing on the requested thread? - if (!thread.IsCurrentThread()) - { - // Internal type used to bridge raw lambda to DelegateFunctionAsyncWait. - // decay_t ensures that references and const qualifiers are removed for storage. - std::function...)> typedFunc = func; - - // Create a delegate that points to func to invoke on thread - auto delegate = dmq::MakeDelegate(typedFunc, thread, timeout); - - // Invoke the delegate target function asynchronously and wait for completion - auto retVal = delegate.AsyncInvoke(std::forward(args)...); - - // Target function has a return value? - if constexpr (!std::is_void_v) - { - if (retVal.has_value()) { - return retVal.value(); - } - else { - return RetType{}; - } - } - } - else - { - // Invoke target function synchronously - return func(std::forward(args)...); - } -} - -/// Helper function to simplify asynchronous invoke of a member function using a raw pointer. -/// @param[in] tclass - the class instance (pointer) -/// @param[in] func - the member function pointer -/// @param[in] thread - the thread to invoke func on -/// @param[in] timeout - the time to wait for invoke to complete -/// @param[in] args - the function argument(s) passed to func -template -auto AsyncInvoke(TClass* tclass, Func func, dmq::IThread& thread, const dmq::Duration& timeout, Args&&... args) -{ - // Deduce return type using std::invoke (robust for member pointers) - using RetType = decltype(std::invoke(func, tclass, std::forward(args)...)); - - if (!thread.IsCurrentThread()) - { - // Create delegate. MakeDelegate handles member pointers correctly. - auto delegate = dmq::MakeDelegate(tclass, func, thread, timeout); - - auto retVal = delegate.AsyncInvoke(std::forward(args)...); - - if constexpr (!std::is_void_v) - { - if (retVal.has_value()) { - return retVal.value(); - } - else { - return RetType{}; - } - } - } - else - { - return std::invoke(func, tclass, std::forward(args)...); - } -} - -/// Helper function to simplify asynchronous invoke of a member function using a shared pointer. -/// @param[in] tclass - the class instance (shared_ptr) -/// @param[in] func - the member function pointer -/// @param[in] thread - the thread to invoke func on -/// @param[in] timeout - the time to wait for invoke to complete -/// @param[in] args - the function argument(s) passed to func -template -auto AsyncInvoke(std::shared_ptr tclass, Func func, dmq::IThread& thread, const dmq::Duration& timeout, Args&&... args) -{ - // Deduce return type using std::invoke (robust for member pointers) - using RetType = decltype(std::invoke(func, tclass, std::forward(args)...)); - - if (!thread.IsCurrentThread()) - { - // Create delegate. MakeDelegate handles shared_ptr correctly (creates DelegateMemberSp). - auto delegate = dmq::MakeDelegate(tclass, func, thread, timeout); - - auto retVal = delegate.AsyncInvoke(std::forward(args)...); - - if constexpr (!std::is_void_v) - { - if (retVal.has_value()) { - return retVal.value(); - } - else { - return RetType{}; - } - } - } - else - { - return std::invoke(func, tclass, std::forward(args)...); - } -} - -} // namespace dmq::util - -#endif diff --git a/DelegateMQ/extras/util/ClockHelper.h b/DelegateMQ/extras/util/ClockHelper.h deleted file mode 100644 index 01efdec..0000000 --- a/DelegateMQ/extras/util/ClockHelper.h +++ /dev/null @@ -1,36 +0,0 @@ -#ifndef CLOCK_HELPER_H -#define CLOCK_HELPER_H - -#include "../../delegate/DelegateOpt.h" -#include - -namespace dmq::util { - -namespace detail { - /// @brief Captures the process-start time point once, on first call. - inline const dmq::Clock::time_point& ProcessStart() { - static const dmq::Clock::time_point start = dmq::Clock::now(); - return start; - } -} - -/// @brief Get elapsed time since process start in milliseconds. -/// @details Normalizes to process start so timestamps are comparable across -/// nodes regardless of the underlying clock's epoch (e.g. FreeRTOS ticks -/// vs. std::chrono::steady_clock which counts from system boot). -/// @return Milliseconds elapsed since first call to any dmq::util::Timestamp function. -inline uint64_t TimestampMs() { - return static_cast(std::chrono::duration_cast( - dmq::Clock::now() - detail::ProcessStart()).count()); -} - -/// @brief Get elapsed time since process start in microseconds. -/// @return Microseconds elapsed since first call to any dmq::util::Timestamp function. -inline uint64_t TimestampUs() { - return static_cast(std::chrono::duration_cast( - dmq::Clock::now() - detail::ProcessStart()).count()); -} - -} // namespace dmq::util - -#endif diff --git a/DelegateMQ/extras/util/Fault.h b/DelegateMQ/extras/util/Fault.h deleted file mode 100644 index a1937fd..0000000 --- a/DelegateMQ/extras/util/Fault.h +++ /dev/null @@ -1,60 +0,0 @@ -#ifndef _FAULT_H -#define _FAULT_H - -#ifdef __cplusplus - #define DMQ_NORETURN [[noreturn]] -#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L - #define DMQ_NORETURN _Noreturn -#elif defined(__GNUC__) || defined(__clang__) - #define DMQ_NORETURN __attribute__((noreturn)) -#elif defined(_MSC_VER) - #define DMQ_NORETURN __declspec(noreturn) -#else - #define DMQ_NORETURN -#endif - -#ifdef __cplusplus -namespace dmq::util { - /// Handles all software assertions in the system. - /// @param[in] file - the file name that the software assertion occurred on - /// @param[in] line - the line number that the software assertion occurred on - DMQ_NORETURN void FaultHandler(const char* file, unsigned short line); - - /// Install OS-specific crash handlers to capture and report critical errors. - void InstallCrashHandlers(); -} -#endif - -#ifdef __cplusplus -extern "C" { -#endif - DMQ_NORETURN void FaultHandler(const char* file, unsigned short line); - DMQ_NORETURN void WatchdogHandler(const char* threadName); - void InstallCrashHandlers(); -#ifdef __cplusplus -} -#endif - -#ifdef __cplusplus -#ifndef DMQ_ASSERT -#define DMQ_ASSERT() \ - dmq::util::FaultHandler(__FILE__, static_cast(__LINE__)) -#endif - -#ifndef DMQ_ASSERT_TRUE -#define DMQ_ASSERT_TRUE(condition) \ - do {if (!(condition)) dmq::util::FaultHandler(__FILE__, static_cast(__LINE__));} while (0) -#endif -#else -#ifndef DMQ_ASSERT -#define DMQ_ASSERT() \ - FaultHandler(__FILE__, (unsigned short) __LINE__) -#endif - -#ifndef DMQ_ASSERT_TRUE -#define DMQ_ASSERT_TRUE(condition) \ - do {if (!(condition)) FaultHandler(__FILE__, (unsigned short) __LINE__);} while (0) -#endif -#endif - -#endif diff --git a/DelegateMQ/extras/util/MonotonicGuard.h b/DelegateMQ/extras/util/MonotonicGuard.h deleted file mode 100644 index 5f22df1..0000000 --- a/DelegateMQ/extras/util/MonotonicGuard.h +++ /dev/null @@ -1,73 +0,0 @@ -#ifndef MONOTONIC_GUARD_H -#define MONOTONIC_GUARD_H - -#include -#include - -namespace dmq::util { - -/// @brief Utility to guard against out-of-order or stale messages. -/// @details Tracks the last accepted sequence number and rejects any incoming value -/// that is not strictly newer. Handles unsigned integer rollover for types of 32 bits -/// or smaller via signed-difference comparison. -/// -/// Primary use case — LVC rewind: when a DataBus subscriber connects with -/// Last Value Cache enabled, it may receive a stale cached value AFTER a fresher -/// value has already been delivered (see DataBus::InternalSubscribe, step 5). -/// Embed a sequence number in every message (e.g. via MessageBase) and call -/// IsNewer() in the subscriber to silently discard the stale arrival. -/// -/// @note This class is NOT thread-safe. Use within a single thread of control -/// (e.g., an Active Object or a dedicated subscriber thread). -template -class MonotonicGuard { - static_assert(std::is_integral_v && std::is_unsigned_v, "T must be an unsigned integral type"); - -public: - MonotonicGuard() = default; - - /// @brief Check if a message is newer (more recent than the last processed). - /// @param timestamp The timestamp from the incoming message. - /// @return true if newer, false if stale or out-of-order. - bool IsNewer(T timestamp) { - if (m_first) { - m_lastTimestamp = timestamp; - m_first = false; - return true; - } - - if constexpr (sizeof(T) <= 4) { - // Use signed difference to handle rollover for 32-bit (or smaller) types. - // This works correctly up to half the range of the type (e.g., ~24 days for uint32 ms). - using SignedT = std::make_signed_t; - SignedT diff = static_cast(timestamp - m_lastTimestamp); - if (diff > 0) { - m_lastTimestamp = timestamp; - return true; - } - } else { - // For 64-bit types, rollover is effectively impossible. - // Simple greater-than comparison is sufficient. - if (timestamp > m_lastTimestamp) { - m_lastTimestamp = timestamp; - return true; - } - } - - return false; - } - - /// @brief Reset the guard to its initial state. - void Reset() { - m_first = true; - m_lastTimestamp = 0; - } - -private: - T m_lastTimestamp = 0; - bool m_first = true; -}; - -} // namespace dmq::util - -#endif diff --git a/DelegateMQ/extras/util/NetworkConnect.h b/DelegateMQ/extras/util/NetworkConnect.h deleted file mode 100644 index 0086d7c..0000000 --- a/DelegateMQ/extras/util/NetworkConnect.h +++ /dev/null @@ -1,118 +0,0 @@ -#ifndef NETWORK_CONNECT_H -#define NETWORK_CONNECT_H - -/// @brief RAII wrapper to initialize and cleanup network stacks. -/// Instantiate this ONCE at the top of main(). -/// -/// On bare-metal targets (no OS, no socket stack) the class compiles to -/// empty stubs so that DataBus.h can include this header unconditionally. - -// DelegateOpt.h owns the actual platform-header decision and include (see -// its DMQ_NETWORK_CONNECT_DESKTOP_HOST_HEADERS block) so that no library -// file other than DelegateOpt.h ever #includes a platform header directly. -// This header only reads the resulting macro. -#include "delegate/DelegateOpt.h" - -#include - -namespace dmq::util { - -class NetworkContext -{ -public: - NetworkContext() - { -#if defined(DMQ_NETWORK_CONNECT_DESKTOP_HOST_HEADERS) && defined(_WIN32) - WSADATA wsaData; - int result = WSAStartup(MAKEWORD(2, 2), &wsaData); - if (result != 0) - { - // WSAStartup failed — network unavailable - } -#endif - } - - ~NetworkContext() - { -#if defined(DMQ_NETWORK_CONNECT_DESKTOP_HOST_HEADERS) && defined(_WIN32) - WSACleanup(); -#endif - } - - /// @brief Helper to find the first non-loopback physical IPv4 address. - /// @return The IP address as a string (e.g. "192.168.1.5") or "127.0.0.1" if none found. - /// @note Unavailable on embedded RTOS targets (ThreadX/Zephyr/CMSIS-RTOS2) - /// -- a desktop-only convenience with no embedded equivalent, see - /// DelegateOpt.h's DMQ_NETWORK_CONNECT_DESKTOP_HOST_HEADERS block -- - /// and always returns "127.0.0.1" there. - /// FreeRTOS is not in that list: its Win32/POSIX simulator samples - /// (databus-freertos, freertos-linux) use real host sockets on purpose. - static std::string GetLocalAddress() - { -#if !defined(DMQ_NETWORK_CONNECT_DESKTOP_HOST_HEADERS) - return "127.0.0.1"; -#elif defined(_WIN32) - char hostname[256]; - if (gethostname(hostname, sizeof(hostname)) == SOCKET_ERROR) { - return "127.0.0.1"; - } - - addrinfo hints = {}, *res = nullptr; - hints.ai_family = AF_INET; - hints.ai_socktype = SOCK_DGRAM; - - if (getaddrinfo(hostname, nullptr, &hints, &res) != 0) { - return "127.0.0.1"; - } - - std::string firstIp = "127.0.0.1"; - for (addrinfo* p = res; p != nullptr; p = p->ai_next) { - char ipStr[INET_ADDRSTRLEN]; - sockaddr_in* ipv4 = (sockaddr_in*)p->ai_addr; - inet_ntop(AF_INET, &(ipv4->sin_addr), ipStr, INET_ADDRSTRLEN); - std::string current(ipStr); - if (current.find("127.") != 0) { - firstIp = current; - break; - } - } - - freeaddrinfo(res); - return firstIp; -#elif defined(__linux__) || defined(__APPLE__) || defined(__unix__) - struct ifaddrs *ifaddr, *ifa; - if (getifaddrs(&ifaddr) == -1) { - return "127.0.0.1"; - } - - std::string firstIp = "127.0.0.1"; - for (ifa = ifaddr; ifa != nullptr; ifa = ifa->ifa_next) { - if (ifa->ifa_addr == nullptr || ifa->ifa_addr->sa_family != AF_INET) - continue; - if (ifa->ifa_flags & IFF_LOOPBACK) - continue; - if (!(ifa->ifa_flags & IFF_UP)) - continue; - - char ipStr[INET_ADDRSTRLEN]; - void* addrPtr = &((struct sockaddr_in*)ifa->ifa_addr)->sin_addr; - inet_ntop(AF_INET, addrPtr, ipStr, INET_ADDRSTRLEN); - std::string current(ipStr); - if (current != "0.0.0.0" && current.find("127.") != 0) { - firstIp = current; - break; - } - } - - freeifaddrs(ifaddr); - return firstIp; -#else - return "127.0.0.1"; -#endif - } -}; - -} // namespace dmq::util - - -#endif // NETWORK_CONNECT_H diff --git a/DelegateMQ/extras/util/README.md b/DelegateMQ/extras/util/README.md deleted file mode 100644 index f833b40..0000000 --- a/DelegateMQ/extras/util/README.md +++ /dev/null @@ -1,62 +0,0 @@ -# Utility & Helper Layer - -This directory contains concrete utility classes and helper functions that complement the core DelegateMQ library. - -While the core library (`namespace dmq`) provides the fundamental mechanism for delegates and threading interfaces, this directory provides the **"batteries included"** implementations required to build real-world applications (Timers, Reliability, Networking logic, etc.). - -> **Note:** Code in this directory resides in the **`dmq::util`** namespace. - -## Functional Modules - -### 1. Asynchronous Helpers -* **`dmq::util::AsyncInvoke.h`**: A powerful template helper that allows you to fire any function (lambda, member, free) onto any thread in a single line of code. - * *Example:* `dmq::util::AsyncInvoke(myFunc, workerThread, 1s, arg1);` - -### 2. Timing & Scheduling -* **`dmq::util::Timer.h`**: A complete software timer system capable of one-shot and periodic callbacks via delegates. Supports millisecond and microsecond precision depending on the platform clock. -* **`dmq::util::TimerDelegate.h`**: A stateful delegate wrapper that prevents thread queue flooding. It ensures at most one timer message is in the target thread's queue at any time, providing safe backpressure for high-frequency timers. - -### 3. Reliability Layer (QoS) -These classes provide transport-layer reliability (ACKs and Retries) over unreliable media (like UDP or Serial). -* **`dmq::util::TransportMonitor.h`**: Tracks outgoing messages and handles sequence numbers. -* **`dmq::util::RetryMonitor.h`**: Logic to detect lost packets and trigger re-transmissions. -* **`dmq::util::ReliableTransport.h`**: A composite transport that wraps a raw transport (e.g., UDP) and adds reliability logic transparently. - -### 4. Networking Logic -* **`dmq::util::NetworkConnect.h`**: Platform-specific socket initialization helpers (e.g., `dmq::util::NetworkContext`) to handle networking boilerplate like `WSAStartup`. - -> **`RemoteDispatcher`/`RemoteEndpoint`** (the point-to-point RPC pattern) moved to [`extras/rpc`](../rpc/README.md). They still use this directory's `TransportMonitor`/`RetryMonitor`/`ReliableTransport` as shared reliability plumbing. - -### 5. Monotonic Messaging and Time -These utilities help handle message ordering and timestamping in distributed systems. -* **`dmq::util::ClockHelper.h`**: Simplified functions to get monotonic timestamps (`TimestampMs()`, `TimestampUs()`) across all supported platforms. -* **`dmq::util::MonotonicGuard.h`**: A generic template class to filter out-of-order or stale messages. Handles 32-bit rollover logic automatically and provides simple 64-bit monotonic checks. - -### 6. System Utilities -* **`dmq::util::Fault.h`**: Assertions and fault trapping macros (`DMQ_ASSERT_TRUE`, `dmq::util::FaultHandler`) used throughout the library examples. -* **`dmq::util::crc16.h`**: Checksum utility for data integrity in serial/UDP headers. - -## Usage - -Include these headers when you need specific functionality beyond basic delegates. For example, if you need to schedule a periodic callback: - -```cpp -#include "extras/util/Timer.h" - -dmq::util::Timer myTimer; -// Use a delegate to receive timer callbacks; store the connection or it disconnects immediately -auto conn = myTimer.OnExpired.Connect(dmq::MakeDelegate(&myClass, &MyClass::OnTimeout)); -myTimer.Start(std::chrono::milliseconds(1000)); // 1-second periodic timer - -// Drive all timers periodically (main loop or high-priority task; an ISR only on bare metal) -dmq::util::Timer::ProcessTimers(); -``` - -Or to invoke a function on a specific thread with a 5-second timeout: - -```cpp -#include "extras/util/AsyncInvoke.h" - -// Fires and waits up to 5s for completion on workerThread -dmq::util::AsyncInvoke(myWorkerFunc, workerThread, 5s, 123, "hello"); -``` diff --git a/DelegateMQ/extras/util/ReliableTransport.h b/DelegateMQ/extras/util/ReliableTransport.h deleted file mode 100644 index a45f274..0000000 --- a/DelegateMQ/extras/util/ReliableTransport.h +++ /dev/null @@ -1,111 +0,0 @@ -#ifndef RELIABLE_TRANSPORT_H -#define RELIABLE_TRANSPORT_H - -/// @file ReliableTransport.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// @brief Reliability adapter for the DelegateMQ transport layer. -/// -/// @details -/// This class applies the **Decorator Pattern** to any existing `ITransport` implementation, -/// adding automatic retransmission capabilities without modifying the underlying transport logic. -/// -/// ### The Reliability Stack -/// It functions as the entry point to the reliability system, routing outgoing messages -/// through the `RetryMonitor` to ensure delivery guarantees (ACKs) are met. -/// -/// @verbatim -/// Application -/// | Send() -/// v -/// +-----------------------+ -/// | ReliableTransport | <-- Adapter / Entry Point -/// +-----------------------+ -/// | -/// v -/// +-----------------------+ +------------------+ -/// | RetryMonitor | <----(Signaled)----- | TransportMonitor | -/// | (Manages Re-sending) | | (Tracks Timeouts)| -/// +-----------------------+ +------------------+ -/// | ^ -/// | Send() | Add(SeqNum) -/// v | -/// +-----------------------+ | -/// | PhysicalTransport | ------------------------------+ -/// | (TCP, UDP, Serial...) | -/// +-----------------------+ -/// | -/// v -/// Network -/// @endverbatim -/// -/// **Key Responsibilities:** -/// 1. **Send Interception**: Redirects `Send()` calls to `RetryMonitor::SendWithRetry()`. -/// 2. **Receive Pass-through**: Forwards `Receive()` calls directly to the physical transport -/// (no interference with incoming data). -/// -/// @brief Notes on Packet Ordering and Reliability -/// -/// The DelegateMQ reliability layer (RetryMonitor) ensures *eventual delivery*, -/// but the order of execution depends heavily on the underlying transport: -/// -/// 1. **UDP / Serial (Unordered Transports)**: -/// These transports do not buffer or reorder packets. If Packet #2 is lost -/// and re-transmitted by the RetryMonitor, the Receiver will process them -/// in the order of arrival: #1 -> #3 -> #2 (Retry). -/// *Application logic must be robust against out-of-order updates.* -/// -/// 2. **TCP (Ordered Stream)**: -/// The TCP protocol stack enforces strict ordering. If Packet #2 is lost -/// (tcp segment loss), the OS holds Packet #3 in the kernel buffer until -/// #2 is retransmitted by the TCP stack itself. The Receiver application -/// will always see: #1 -> #2 -> #3. -/// *Note: If the TCP connection is fully severed and re-connected, the -/// DelegateMQ retry logic may kick in, potentially leading to duplicates -/// or ordering issues across the connection boundary.* - -#include "../../port/transport/common/ITransport.h" -#include "RetryMonitor.h" - -namespace dmq::util { - -/// @brief Adapter to enable automatic retries on any ITransport. -/// @details Routes Send() calls through the RetryMonitor before passing them -/// to the physical transport. -class ReliableTransport : public dmq::transport::ITransport -{ - XALLOCATOR -public: - ReliableTransport() = default; - - ReliableTransport(dmq::transport::ITransport& transport, RetryMonitor& retry) - { - Init(transport, retry); - } - - void Init(dmq::transport::ITransport& transport, RetryMonitor& retry) - { - m_transport = &transport; - m_retry = &retry; - } - - virtual int Send(dmq::xostringstream& os, const dmq::transport::DmqHeader& header) override { - DMQ_ASSERT_TRUE(m_retry != nullptr); - return m_retry->SendWithRetry(os, header); - } - - virtual int Receive(dmq::xstringstream& is, dmq::transport::DmqHeader& header) override { - DMQ_ASSERT_TRUE(m_transport != nullptr); - return m_transport->Receive(is, header); - } - -private: - dmq::transport::ITransport* m_transport = nullptr; - RetryMonitor* m_retry = nullptr; -}; - -} // namespace dmq::util - - -#endif \ No newline at end of file diff --git a/DelegateMQ/extras/util/RetryMonitor.h b/DelegateMQ/extras/util/RetryMonitor.h deleted file mode 100644 index 64defc0..0000000 --- a/DelegateMQ/extras/util/RetryMonitor.h +++ /dev/null @@ -1,311 +0,0 @@ -#ifndef _RETRY_MONITOR_H -#define _RETRY_MONITOR_H - -#include "delegate/DelegateOpt.h" -#include "delegate/DelegateRemote.h" -#include "port/transport/common/ITransport.h" -#include "port/transport/common/DmqHeader.h" -#include "TransportMonitor.h" -#include - -namespace dmq::util { - -/// @file RetryMonitor.h -/// @brief Automatic retransmission manager for DelegateMQ remote calls. -/// -/// @details -/// The RetryMonitor acts as a reliability decorator for any ITransport implementation. -/// It bridges the gap between detection (TransportMonitor) and recovery (Physical Transport). -/// -/// ### Core Responsibilities -/// 1. **Data Persistence**: Stores the fully serialized binary payload of every outgoing -/// remote delegate call, indexed by its unique Sequence Number. -/// 2. **Timeout Handling**: Subscribes to the `TransportMonitor::OnSendStatus` signal. -/// 3. **Automatic Recovery**: If a TIMEOUT status is received, it decrements the retry -/// counter and re-submits the exact binary packet to the transport. -/// 4. **Cleanup**: Discards stored packets upon SUCCESS (ACK received) or when -/// `maxRetries` is exhausted. -/// -/// ### Sequence Number Integrity -/// Retries use the **original** sequence number. This allows the Receiver to perform -/// idempotency checks (filtering out duplicate calls if an ACK was lost but the -/// function was already executed). -/// -/// ### Reentrancy Note -/// This class calls `ITransport::Send()`. If the underlying transport (e.g., SerialTransport) -/// routes its high-level `Send()` back into this monitor, the transport MUST implement -/// a reentrancy guard to prevent infinite recursion. -/// -/// @see https://github.com/DelegateMQ/DelegateMQ -class RetryMonitor -{ - XALLOCATOR -public: - /// @brief Storage for a message that might need retransmission. - struct RetryEntry { - dmq::xstring packetData; ///< The raw serialized arguments - dmq::transport::DmqHeader header; ///< Original metadata (ID, SeqNum, etc.) - int attemptsRemaining; ///< Counter for retry budget - bool isSent = false; ///< Flag to prevent TOCTOU races - }; - - /// Signal emitted when a message is permanently abandoned: either a synchronous - /// send attempt failed immediately (TransportMonitor::Add() or ITransport::Send() - /// itself failed, before any retry could be attempted) or the message exhausted - /// its retry budget without being ACKed. A send rejected because its sequence - /// number is still in use by an earlier in-flight message is reported only by - /// SendWithRetry()'s -1 return. Subscribers receive: (remoteId, seqNum); - /// no further retries or status callbacks will occur for this seqNum. - /// Fired outside the internal lock so subscribers may call back into RetryMonitor safely. - dmq::Signal OnDeliveryFailed; - - RetryMonitor() = default; - - /// @brief Constructor - /// @param transport The underlying transport to use for re-sending. - /// @param monitor The monitor that detects the timeouts. - /// @param maxRetries Number of retries before giving up. - /// Default is dmq::RETRY_MONITOR_MAX_RETRIES (DMQ_RETRY_MONITOR_MAX_RETRIES - /// in delegatemqconfig.h). - RetryMonitor(dmq::transport::ITransport& transport, TransportMonitor& monitor, - int maxRetries = dmq::RETRY_MONITOR_MAX_RETRIES) - { - Init(transport, monitor, maxRetries); - } - - void Init(dmq::transport::ITransport& transport, TransportMonitor& monitor, - int maxRetries = dmq::RETRY_MONITOR_MAX_RETRIES) - { - m_transport = &transport; - m_monitor = &monitor; - m_maxRetries = maxRetries; - m_connection = m_monitor->OnSendStatus.Connect(dmq::MakeDelegate(this, &RetryMonitor::OnStatusChanged)); - } - - ~RetryMonitor() { - m_connection.Disconnect(); - - const dmq::LockGuard lock(m_lock); - m_retryStore.clear(); - } - - /// @brief Resends after the first attempt before a message is abandoned. - int GetMaxRetries() const { return m_maxRetries; } - - /// @brief Sends a message and tracks it for potential retries. - /// @return 0 on success, -1 on immediate transport failure. - int SendWithRetry(dmq::xostringstream& os, const dmq::transport::DmqHeader& header) - { - DMQ_ASSERT_TRUE(m_transport != nullptr); - // Critical Section: Store the packet for retry before sending. - // If Send() fails we remove the entry immediately so it doesn't leak. - uint32_t key = (static_cast(header.GetId()) << 16) | header.GetSeqNum(); - bool collision = false; - { - dmq::LockGuard lock(m_lock); - - // The 16-bit sequence number wrapped while an earlier message with the - // same key is still awaiting its ACK. Reject the new send and leave the - // earlier entry alone: overwriting it would lose its retry data. - collision = m_retryStore.find(key) != m_retryStore.end(); - if (!collision) { - RetryEntry entry; - entry.attemptsRemaining = m_maxRetries; - entry.header = header; - entry.packetData = os.str(); // Copy data - entry.isSent = false; // Mark as NOT yet sent to physical transport - m_retryStore[key] = entry; - } - } - if (collision) { - // Reported only through the -1 return (the sender's delegate raises - // ERR_DISPATCH). Not through OnDeliveryFailed: that is keyed by - // (remoteId, seqNum), which here names the earlier message, still in - // flight. Firing it would report that message as failed. - LOG_ERROR("RetryMonitor: SeqNum wraparound collision for seq {}", header.GetSeqNum()); - return -1; - } - - // Non-Critical Section: Send via Transport. - // We must NOT hold m_lock while calling Send(). - // Send() calls TransportMonitor::Add(), which takes its own lock. - bool added = true; - if (m_monitor) - added = m_monitor->Add(header.GetSeqNum(), header.GetId()); - - if (!added) { - { - dmq::LockGuard lock(m_lock); - m_retryStore.erase(key); - } - LOG_ERROR("RetryMonitor: TransportMonitor::Add() failed for seq {}", header.GetSeqNum()); - OnDeliveryFailed(header.GetId(), header.GetSeqNum()); - return -1; - } - - int result = m_transport->Send(os, header); - - // If the send failed, TransportMonitor::Add() already succeeded above, so - // this entry is sitting in TransportMonitor's pending map. Cancel() frees - // that slot immediately (silently -- no false SUCCESS/TIMEOUT signal) instead - // of leaving it to occupy a slot until TRANSPORT_TIMEOUT expires naturally. - // Report the failure now so it isn't silently lost. - if (result != 0) - { - if (m_monitor) - m_monitor->Cancel(header.GetSeqNum(), header.GetId()); - size_t erased = 0; - { - dmq::LockGuard lock(m_lock); - erased = m_retryStore.erase(key); - } - // erased == 0: OnStatusChanged() already abandoned the entry and - // reported it (failed re-register while this Send() was running). - if (erased > 0) { - LOG_ERROR("RetryMonitor: immediate Send() failure for seq {}", header.GetSeqNum()); - OnDeliveryFailed(header.GetId(), header.GetSeqNum()); - } - } - else - { - // SUCCESS: Mark the entry as sent so OnStatusChanged can retry if needed. - dmq::LockGuard lock(m_lock); - auto it = m_retryStore.find(key); - if (it != m_retryStore.end()) { - it->second.isSent = true; - } - } - - return result; - } - -private: - void OnStatusChanged(dmq::DelegateRemoteId id, uint16_t seqNum, TransportMonitor::Status status) - { - // Variables to hold data for the retry OUTSIDE the lock - bool shouldRetry = false; - bool shouldReregister = false; - bool shouldReportFailure = false; - dmq::xstring retryPayload; - dmq::transport::DmqHeader retryHeader; - uint32_t key = (static_cast(id) << 16) | seqNum; - - { - // 1. Critical Section: Read/Modify Map ONLY - const dmq::LockGuard lock(m_lock); - - auto it = m_retryStore.find(key); - if (it == m_retryStore.end()) return; - - if (status == TransportMonitor::Status::SUCCESS) - { - // Message arrived safely, we can forget about the data now - m_retryStore.erase(it); - return; // Done - } - else if (status == TransportMonitor::Status::TIMEOUT) - { - // ONLY retry if the message has actually finished its first physical send. - // If isSent is false, it means SendWithRetry is still executing m_transport->Send(). - if (it->second.attemptsRemaining > 0 && it->second.isSent) - { - // Decrement counter - it->second.attemptsRemaining--; - - // COPY data to local variables so we can use them after unlocking - retryPayload = it->second.packetData; - retryHeader = it->second.header; - shouldRetry = true; - } - else if (it->second.attemptsRemaining > 0 && !it->second.isSent) - { - // TIMEOUT fired while the initial Send() is still executing. - // TransportMonitor has already erased its pending entry, so no - // further callbacks will fire unless we re-register. Re-add to - // TransportMonitor so monitoring continues; do not decrement - // attemptsRemaining — the first send has not completed yet. - retryHeader = it->second.header; - shouldReregister = true; - } - else if (it->second.attemptsRemaining <= 0) - { - // Max retries exceeded. Clean up. - m_retryStore.erase(it); - shouldReportFailure = true; - } - } - } // <--- LOCK IS RELEASED HERE - - // 2. Non-Critical Section: Perform blocking network operations - if (shouldRetry && m_transport) - { - dmq::xostringstream os(std::ios::in | std::ios::out | std::ios::binary); - os.write(retryPayload.data(), retryPayload.size()); - - bool added = true; - if (m_monitor) - added = m_monitor->Add(retryHeader.GetSeqNum(), retryHeader.GetId()); - - if (added) { - int result = m_transport->Send(os, retryHeader); - if (result != 0) { - // Same reasoning as SendWithRetry's immediate-failure path: Add() - // already succeeded, so cancel it silently rather than leaving the - // slot occupied until TRANSPORT_TIMEOUT expires naturally. - if (m_monitor) - m_monitor->Cancel(retryHeader.GetSeqNum(), retryHeader.GetId()); - { - dmq::LockGuard lock(m_lock); - m_retryStore.erase(key); - } - LOG_ERROR("RetryMonitor: immediate Send() failure while retrying seq {}", seqNum); - OnDeliveryFailed(id, seqNum); - } - } else { - { - dmq::LockGuard lock(m_lock); - m_retryStore.erase(key); - } - LOG_ERROR("RetryMonitor: TransportMonitor::Add() failed while retrying seq {}", seqNum); - OnDeliveryFailed(id, seqNum); - } - } - - if (shouldReregister && m_monitor) - { - if (!m_monitor->Add(retryHeader.GetSeqNum(), retryHeader.GetId())) { - // Nothing is tracking this message any more, so no further status - // will arrive for it. Abandon it now rather than leak the entry. - // SendWithRetry() may still be inside Send(); it finds the entry - // gone and doesn't report again. - size_t erased = 0; - { - dmq::LockGuard lock(m_lock); - erased = m_retryStore.erase(key); - } - if (erased > 0) { - LOG_ERROR("RetryMonitor: TransportMonitor::Add() failed while re-registering seq {}", seqNum); - OnDeliveryFailed(id, seqNum); - } - } - } - - if (shouldReportFailure) - { - LOG_ERROR("RetryMonitor: Max retries exceeded for seq {}", seqNum); - OnDeliveryFailed(id, seqNum); - } - } - - dmq::transport::ITransport* m_transport = nullptr; - TransportMonitor* m_monitor = nullptr; - int m_maxRetries = dmq::RETRY_MONITOR_MAX_RETRIES; - dmq::xmap m_retryStore; - dmq::RecursiveMutex m_lock; - dmq::ScopedConnection m_connection; -}; - -} // namespace dmq::util - - -#endif // _RETRY_MONITOR_H diff --git a/DelegateMQ/extras/util/ThreadMonitor.cpp b/DelegateMQ/extras/util/ThreadMonitor.cpp deleted file mode 100644 index a515069..0000000 --- a/DelegateMQ/extras/util/ThreadMonitor.cpp +++ /dev/null @@ -1,124 +0,0 @@ -// ThreadMonitor publishes per-thread stats gathered by Thread::SnapshotStats(), -// which only exists when DMQ_DATABUS_TOOLS is enabled (desktop default; off on -// embedded DataBus builds -- see DelegateSelect.h). Otherwise this file -// compiles to nothing, so it can stay in a build that adds every DelegateMQ -// source file (see src/DelegateMQ.cpp). -#include "delegate/DelegateSelect.h" -#if defined(DMQ_HAS_THREADING) && defined(DMQ_DATABUS) && defined(DMQ_DATABUS_TOOLS) - -#include "ThreadMonitor.h" -#include "DelegateMQ.h" - -#include -#include - -namespace dmq::util { -// ... rest of namespace dmq::util content ... - -ThreadMonitor::~ThreadMonitor() { - Disable(); -} - -void ThreadMonitor::Register(dmq::os::Thread* thread) { - if (!thread) return; - auto& instance = GetInstance(); - dmq::LockGuard lock(instance.m_mutex); - for (size_t i = 0; i < instance.m_threadCount; ++i) { - if (instance.m_threads[i] == thread) return; - } - if (instance.m_threadCount < dmq::MAX_WATCHDOG_THREADS) - instance.m_threads[instance.m_threadCount++] = thread; - else - DMQ_ASSERT(); -} - -void ThreadMonitor::Deregister(dmq::os::Thread* thread) { - if (!thread) return; - auto& instance = GetInstance(); - dmq::LockGuard lock(instance.m_mutex); - for (size_t i = 0; i < instance.m_threadCount; ++i) { - if (instance.m_threads[i] == thread) { - instance.m_threads[i] = instance.m_threads[--instance.m_threadCount]; - instance.m_threads[instance.m_threadCount] = nullptr; - return; - } - } -} - -void ThreadMonitor::Enable(const dmq::xstring& topic) { - auto& instance = GetInstance(); - if (instance.m_enabled.exchange(true)) return; - - instance.m_topic = topic; - - dmq::LockGuard lock(instance.m_mutex); - instance.m_monitorThread.emplace("ThreadMonitor", 10); - instance.m_monitorThread->CreateThread(); - - (void)dmq::MakeDelegate(&instance, &ThreadMonitor::MonitorLoop, *instance.m_monitorThread).AsyncInvoke(); -} - -void ThreadMonitor::Disable() { - auto& instance = GetInstance(); - if (!instance.m_enabled.exchange(false)) return; - - // ExitThread() must not be called while holding m_mutex: MonitorLoop - // acquires m_mutex after Sleep() to check m_enabled before re-arming, - // which would deadlock if Disable() held the lock across the join. - if (instance.m_monitorThread) { - instance.m_monitorThread->ExitThread(); - } - - dmq::LockGuard lock(instance.m_mutex); - instance.m_monitorThread.reset(); -} - -void ThreadMonitor::MonitorLoop() { - if (!m_enabled) return; - - std::array snapshots; - size_t snapshotCount = 0; - { - dmq::LockGuard lock(m_mutex); - for (size_t i = 0; i < dmq::MAX_WATCHDOG_THREADS; ++i) { - if (i >= m_threadCount || snapshotCount >= dmq::MAX_WATCHDOG_THREADS) - break; - - if (m_threads[i] != nullptr) { - snapshots[snapshotCount++] = m_threads[i]->SnapshotStats(); - } - } - } - - for (size_t i = 0; i < snapshotCount; ++i) { - const auto& s = snapshots[i]; - ThreadStatsPacket packet; - packet.cpu_name = s.cpu_name; - packet.thread_name = s.thread_name; - packet.queue_depth = static_cast(s.queue_depth); - packet.queue_depth_max_window = static_cast(s.queue_depth_max_window); - packet.queue_depth_max_all = static_cast(s.queue_depth_max_all); - packet.queue_size_limit = static_cast(s.queue_size_limit); - packet.latency_avg_ms = s.latency_avg_ms; - packet.latency_max_window_ms = s.latency_max_window_ms; - packet.latency_max_all_ms = s.latency_max_all_ms; - packet.invoke_avg_ms = s.invoke_avg_ms; - packet.invoke_max_window_ms = s.invoke_max_window_ms; - packet.invoke_max_all_ms = s.invoke_max_all_ms; - packet.dispatch_count = s.dispatch_count; - - dmq::databus::DataBus::Publish(m_topic, packet); - } - - if (m_enabled) { - dmq::os::Thread::Sleep(std::chrono::seconds(2)); - - dmq::LockGuard lock(m_mutex); - if (m_enabled && m_monitorThread.has_value()) - (void)dmq::MakeDelegate(this, &ThreadMonitor::MonitorLoop, *m_monitorThread).AsyncInvoke(); - } -} - -} // namespace dmq::util - -#endif // DMQ_DATABUS && DMQ_DATABUS_TOOLS diff --git a/DelegateMQ/extras/util/ThreadMonitor.h b/DelegateMQ/extras/util/ThreadMonitor.h deleted file mode 100644 index aecdfc9..0000000 --- a/DelegateMQ/extras/util/ThreadMonitor.h +++ /dev/null @@ -1,73 +0,0 @@ -#ifndef THREAD_MONITOR_H -#define THREAD_MONITOR_H - -#include "DelegateMQ.h" - -// ThreadMonitor publishes per-thread stats gathered by Thread::SnapshotStats(), -// which only exists when DMQ_DATABUS_TOOLS is enabled (desktop default; off on -// embedded DataBus builds -- see DelegateOpt.h). -#if defined(DMQ_DATABUS) && defined(DMQ_DATABUS_TOOLS) - -#include -#include -#include - -namespace dmq::util { -// ... rest of namespace dmq::util content ... - -/// @brief Packet published to DataBus for thread monitoring. -struct ThreadStatsPacket { - dmq::xstring cpu_name; - dmq::xstring thread_name; - uint32_t queue_depth = 0; - uint32_t queue_depth_max_window = 0; - uint32_t queue_depth_max_all = 0; - uint32_t queue_size_limit = 0; - float latency_avg_ms = 0.0f; - float latency_max_window_ms = 0.0f; - float latency_max_all_ms = 0.0f; - float invoke_avg_ms = 0.0f; - float invoke_max_window_ms = 0.0f; - float invoke_max_all_ms = 0.0f; - uint64_t dispatch_count = 0; -}; - -/// @brief Central monitor that polls registered threads and publishes stats. -class ThreadMonitor { -public: - /// Register a thread for monitoring. - static void Register(dmq::os::Thread* thread); - - /// Deregister a thread. - static void Deregister(dmq::os::Thread* thread); - - /// Enable the monitor (starts the 2-second polling loop). - static void Enable(const dmq::xstring& topic = "ThreadStats"); - - /// Disable the monitor. - static void Disable(); - -private: - ThreadMonitor() = default; - ~ThreadMonitor(); - - static ThreadMonitor& GetInstance() { - static ThreadMonitor instance; - return instance; - } - - void MonitorLoop(); - - std::array m_threads{}; - size_t m_threadCount = 0; - dmq::Mutex m_mutex; - std::optional m_monitorThread; - std::atomic m_enabled{false}; - dmq::xstring m_topic; -}; - -} // namespace dmq::util - -#endif // DMQ_DATABUS && DMQ_DATABUS_TOOLS - -#endif diff --git a/DelegateMQ/extras/util/ThreadMonitorSer.h b/DelegateMQ/extras/util/ThreadMonitorSer.h deleted file mode 100644 index 7cf3a7a..0000000 --- a/DelegateMQ/extras/util/ThreadMonitorSer.h +++ /dev/null @@ -1,62 +0,0 @@ -#ifndef THREAD_MONITOR_SER_H -#define THREAD_MONITOR_SER_H - -#include "ThreadMonitor.h" -#include "port/serialize/serialize/msg_serialize.h" -#include - -namespace dmq::util { - -/// @brief Serializer for ThreadStatsPacket. -class ThreadStatsPacketSerializer : public dmq::ISerializer { -public: - virtual std::ostream& Write(std::ostream& os, const ThreadStatsPacket& data) override { - serialize s; - s.write(os, data.cpu_name); - s.write(os, data.thread_name); - s.write(os, data.queue_depth); - s.write(os, data.queue_depth_max_window); - s.write(os, data.queue_depth_max_all); - s.write(os, data.queue_size_limit); - s.write(os, data.latency_avg_ms); - s.write(os, data.latency_max_window_ms); - s.write(os, data.latency_max_all_ms); - s.write(os, data.invoke_avg_ms); - s.write(os, data.invoke_max_window_ms); - s.write(os, data.invoke_max_all_ms); - s.write(os, data.dispatch_count); - return os; - } - - virtual std::istream& Read(std::istream& is, ThreadStatsPacket& data) override { - serialize s; - s.read(is, data.cpu_name); - s.read(is, data.thread_name); - s.read(is, data.queue_depth); - s.read(is, data.queue_depth_max_window); - s.read(is, data.queue_depth_max_all); - s.read(is, data.queue_size_limit); - s.read(is, data.latency_avg_ms); - s.read(is, data.latency_max_window_ms); - s.read(is, data.latency_max_all_ms); - s.read(is, data.invoke_avg_ms); - s.read(is, data.invoke_max_window_ms); - s.read(is, data.invoke_max_all_ms); - s.read(is, data.dispatch_count); - return is; - } -}; - -/// @brief Stringifier for ThreadStatsPacket (for DataSpy). -inline dmq::xstring ThreadStatsPacketToString(const ThreadStatsPacket& p) { - dmq::xstringstream ss; - ss << "CPU:" << p.cpu_name << " Thread:" << p.thread_name - << " Q:" << p.queue_depth << "/" << p.queue_depth_max_window << "/" << p.queue_depth_max_all - << " Latency(ms):" << std::fixed << std::setprecision(2) << p.latency_avg_ms << "/" << p.latency_max_window_ms - << " Invoke(ms):" << std::fixed << std::setprecision(2) << p.invoke_avg_ms << "/" << p.invoke_max_window_ms; - return ss.str(); -} - -} // namespace dmq::util - -#endif diff --git a/DelegateMQ/extras/util/Timer.cpp b/DelegateMQ/extras/util/Timer.cpp deleted file mode 100644 index 7f5f67d..0000000 --- a/DelegateMQ/extras/util/Timer.cpp +++ /dev/null @@ -1,252 +0,0 @@ -#include "Timer.h" -#include "Fault.h" -#include -#include -#include - -namespace dmq::util { - - -std::atomic Timer::m_timerStopped{false}; - -//------------------------------------------------------------------------------ -// Constructor -//------------------------------------------------------------------------------ -Timer::Timer() -{ - const dmq::LockGuard lock(GetLock()); - m_enabled = false; -} - -//------------------------------------------------------------------------------ -// Destructor -//------------------------------------------------------------------------------ -Timer::~Timer() -{ - // Wait out a ProcessTimers() that found this timer expired and hasn't - // copied its subscribers yet (see GetProcessLock()). - const dmq::LockGuard processLock(GetProcessLock()); - const dmq::LockGuard lock(GetLock()); - - // Remove 'this' from the intrusive linked list - Timer** pp = &GetTimersHead(); - while (*pp != nullptr) - { - if (*pp == this) - { - *pp = this->m_next; - this->m_next = nullptr; - break; - } - pp = &((*pp)->m_next); - } -} - -//------------------------------------------------------------------------------ -// Start -//------------------------------------------------------------------------------ -void Timer::Start(dmq::Duration timeout, bool once) -{ - if (timeout <= dmq::Duration(0)) { -#if !defined(__cpp_exceptions) || defined(DMQ_ASSERTS) - // Use the macro from Fault.h to halt the system - DMQ_ASSERT(); - return; -#else - throw std::invalid_argument("Timeout cannot be 0"); -#endif - } - - const dmq::LockGuard lock(GetLock()); - - m_timeout = timeout; - m_once = once; - m_expireTime = GetNow() + m_timeout; - m_enabled = true; - - // Search for 'this' in the intrusive list - bool found = false; - Timer* p = GetTimersHead(); - while (p != nullptr) - { - if (p == this) - { - found = true; - break; - } - p = p->m_next; - } - - // Only add if not already in the list. - if (!found) - { - m_next = GetTimersHead(); - GetTimersHead() = this; - } - - LOG_INFO("Timer::Start timeout={}", m_timeout.count()); -} - -//------------------------------------------------------------------------------ -// Stop -//------------------------------------------------------------------------------ -void Timer::Stop() -{ - const dmq::LockGuard lock(GetLock()); - - m_enabled = false; - - // Don't remove immediately! Just set a flag. - // Let ProcessTimers() handle the actual removal safely. - m_timerStopped = true; - - LOG_INFO("Timer::Stop timeout={}", m_timeout.count()); -} - -//------------------------------------------------------------------------------ -// CheckExpired -//------------------------------------------------------------------------------ -bool Timer::CheckExpired() -{ - if (!m_enabled) - return false; - - // Has the timer expired? - if (GetNow() < m_expireTime) - return false; // Not expired yet - - if (m_once) - { - m_enabled = false; - m_timerStopped = true; - } - else - { - // Increment the timer to the next expiration - m_expireTime += m_timeout; - - // Check if we are still behind (timer starvation) - // If the new deadline is STILL in the past, we are falling behind. - const dmq::TimePoint now = GetNow(); - if (now > m_expireTime) - { - // The timer has fallen behind. Skip the missed periods and expire one - // full period from now; expiring at `now` would fire again on the - // very next ProcessTimers() call. - m_expireTime = now + m_timeout; - - // Timer processing is falling behind. Maybe user timer expiration is too - // short, time processing takings too long, or CheckExpired not called - // frequently enough. - LOG_INFO("Timer::CheckExpired Timer Processing Falling Behind"); - } - } - - return true; -} - -//------------------------------------------------------------------------------ -// ProcessTimers -//------------------------------------------------------------------------------ -void Timer::ProcessTimers() -{ - // Drains all expired timers across multiple passes so a single call always - // fully clears the backlog, regardless of how many timers expired in the - // same tick — mirrors TransportMonitor::Process()'s identical "batch cap - // exceeded mid-drain" handling for the same MAX_TIMER_EXPIRED-sized batch. - size_t count; - - do { - std::array::Snapshot, dmq::MAX_TIMER_EXPIRED> snapshots; - count = 0; - size_t remaining = 0; - - { - // Held until every timer found expired below has had its subscribers - // copied. ~Timer() takes it too, so none of those timers can be - // destroyed in between. - const dmq::LockGuard processLock(GetProcessLock()); - - std::array expired; - { - const dmq::LockGuard lock(GetLock()); - - // Remove disabled timer from the list if stopped - if (m_timerStopped) - { - Timer** pp = &GetTimersHead(); - while (*pp != nullptr) - { - if (!((*pp)->m_enabled)) - { - Timer* next = (*pp)->m_next; - (*pp)->m_next = nullptr; - *pp = next; - } - else - { - pp = &((*pp)->m_next); - } - } - m_timerStopped = false; - } - - // Identify expired timers while holding the lock. - Timer* t = GetTimersHead(); - while (t != nullptr) - { - if (count >= dmq::MAX_TIMER_EXPIRED) { - // Batch is full for this pass. Deliberately do NOT call - // CheckExpired() on the remaining timers here — that would - // mutate their expiry state (advance m_expireTime / disable - // a one-shot) without capturing a snapshot, permanently - // dropping that expiration. Leaving them untouched lets the - // next pass process them correctly. - Timer* rem = t; - while (rem != nullptr) { ++remaining; rem = rem->m_next; } - break; - } - - if (t->CheckExpired()) - expired[count++] = t; - t = t->m_next; - } - } - - // Copy each expired timer's subscribers outside the critical section: - // GetSnapshot() takes the signal's OS mutexes and can allocate, neither - // of which is allowed with interrupts masked. - for (size_t i = 0; i < count; ++i) - snapshots[i] = expired[i]->OnExpired.GetSnapshot(); - } - - // Call the client's expired callback functions outside the lock. - // This allows callbacks to perform thread-safe operations (like DataBus::Publish) - // without risking a deadlock with the global timer lock. - // The Snapshot holds shared_ptrs to the delegates, so even if a Timer - // was deleted on another thread after the lock was released, the - // callback targets remain valid. - for (size_t i = 0; i < count; ++i) - { - dmq::Signal::InvokeSnapshot(snapshots[i]); - snapshots[i] = {}; // release shared_ptr refs so delegates aren't held between calls - } - - if (remaining > 0) { - LOG_ERROR("Timer::ProcessTimers: batch cap reached, {} timers remain — continuing drain.", remaining); - } - - } while (count == dmq::MAX_TIMER_EXPIRED); -} - -//------------------------------------------------------------------------------ -// GetNow -//------------------------------------------------------------------------------ -dmq::TimePoint Timer::GetNow() -{ - // time_point_cast converts the internal clock resolution (nanos) - // to your custom resolution (millis) inside the time_point wrapper. - return std::chrono::time_point_cast(dmq::Clock::now()); -} - -} // namespace dmq::util \ No newline at end of file diff --git a/DelegateMQ/extras/util/Timer.h b/DelegateMQ/extras/util/Timer.h deleted file mode 100644 index 1ed0d6a..0000000 --- a/DelegateMQ/extras/util/Timer.h +++ /dev/null @@ -1,151 +0,0 @@ -#ifndef _TIMER_H -#define _TIMER_H - -#include "../../delegate/DelegateOpt.h" -#include "../../delegate/Signal.h" -#include -#include -#include - -namespace dmq::util { - -/// @brief A thread-safe timer class that provides periodic or one-shot callbacks. -/// -/// @details -/// The Timer class allows clients to register for callbacks (`OnExpired`) that are invoked -/// when a specified timeout interval elapses. -/// -/// **Key Features:** -/// * **Thread Safe:** All public API methods (`Start`, `Stop`, etc.) are thread-safe and can be called -/// from any thread. -/// * **Flexible Modes:** Supports both one-shot (`once = true`) and periodic (`once = false`) operation. -/// * **Deterministic Execution:** Callbacks are invoked on the thread that calls `ProcessTimers()`. -/// This allows the user to control exactly which thread executes the timer logic (e.g., Main Thread, -/// GUI Thread, or a dedicated Worker Thread). -/// -/// **Usage — Preferred Pattern:** -/// Call `ProcessTimers()` from the highest-priority context that can preempt all watched threads. -/// On an RTOS port (FreeRTOS, ThreadX, Zephyr, CMSIS-RTOS2, NuttX) that is the highest-priority -/// task, never an ISR: `ProcessTimers()` takes OS mutexes to copy each expired timer's -/// subscribers. Only bare metal (`DMQ_THREAD_NONE`, no OS mutexes) can call it from a hardware -/// timer ISR. Connect `OnExpired` to one of: -/// - A plain (synchronous) delegate for inline, fast callbacks (no blocking, no allocation). -/// - An async delegate (`MakeDelegate(..., thread)`) to dispatch work to a worker thread. -/// The target thread MUST use `FullPolicy::FAULT` or `FullPolicy::DROP` — never `TIMEOUT`. -/// (`FAULT` crashes immediately if the queue is full, making overflow visible during testing; -/// `DROP` silently skips the dispatch, which is acceptable for periodic heartbeats.) -/// -/// **ProcessTimers() Blocking Invariant:** -/// `ProcessTimers()` MUST NEVER block. Violating this starves the timer subsystem and defeats -/// the watchdog. Three known causes: -/// -/// **Cause 1 — Async dispatch to a TIMEOUT-policy thread:** -/// `MakeDelegate(fn, thread)()` inside a timer callback calls `DispatchDelegate()` on the -/// target thread. If that thread's queue is full and its policy is `FullPolicy::TIMEOUT`, -/// `ProcessTimers()` stalls for up to `dispatchTimeout` (default 2 s). Fix: target threads -/// that receive timer dispatches must use `FAULT` or `DROP`, never `TIMEOUT`. -/// -/// **Cause 2 — DelegateAsyncWait connected to OnExpired:** -/// `DelegateAsyncWait` blocks its caller until the target thread returns the result. -/// If one is connected to `OnExpired`, `ProcessTimers()` blocks indefinitely waiting -/// for the remote call to complete. Fix: never connect `DelegateAsyncWait` to a timer signal. -/// Only plain async delegates (`MakeDelegate(..., thread)`) are safe for timer callbacks. -/// -/// **Cause 3 — Slow synchronous callback:** -/// A plain (non-async) delegate connected to `OnExpired` runs inline inside `ProcessTimers()`. -/// If that function acquires a lock, does I/O, or otherwise takes significant time, -/// `ProcessTimers()` is delayed for that duration. Fix: keep synchronous timer callbacks fast; -/// dispatch any slow work asynchronously to a worker thread instead. -/// -/// @see SafeTimer.cpp for examples on how to handle callbacks safely with object lifetimes. -class Timer -{ - XALLOCATOR -public: - /// Clients connect to OnExpired to get timer expiration callbacks. - dmq::Signal OnExpired; - - /// Constructor - Timer(void); - - /// Destructor - ~Timer(void); - - /// Starts a timer for callbacks on the specified timeout interval. - /// @param[in] timeout - the timeout. - /// @param[in] once - true if only one timer expiration - void Start(dmq::Duration timeout, bool once = false); - - /// Stops a timer. - void Stop(); - - /// Gets the enabled state of a timer. - /// @return TRUE if the timer is enabled, FALSE otherwise. - bool Enabled() { return m_enabled; } - - /// Get the time. - /// @return The time now. - static dmq::TimePoint GetNow(); - - /// Called on a periodic basic to service all timer instances. - /// @TODO: Call periodically for timer expiration handling. - static void ProcessTimers(); - -private: - // Prevent inadvertent copying of this object - Timer(const Timer&); - Timer& operator=(const Timer&); - - /// Called to check for expired timers and callback registered clients. - bool CheckExpired(); - - /// Get list head using the "Immortal" Pattern - static Timer*& GetTimersHead() - { - // Static head pointer. NEVER delete. Prevents lock from being destroyed - // before the last Timer destructor runs at app shutdown. - static Timer* head = nullptr; - return head; - } - - /// Get lock using the "Immortal" Pattern. Guards the timer list and each - /// timer's state; held only for short, bounded list work. - /// @note dmq::CriticalSection, not dmq::RecursiveMutex, so the list scan in - /// ProcessTimers() never blocks on an OS mutex and bare metal can run it from - /// a hardware ISR. Nothing that can block or allocate may run under it - /// (see GetProcessLock()). - static dmq::CriticalSection& GetLock() - { - // Allocate on heap and NEVER delete. Prevents lock from being destroyed - // before the last Timer destructor runs at app shutdown. - static dmq::CriticalSection* lock = new(std::nothrow) dmq::CriticalSection(); - if (!lock) - BAD_ALLOC(); - return *lock; - } - - /// Held by ProcessTimers() from finding the expired timers until their - /// subscribers are copied, and by ~Timer() before it unlinks itself, so a - /// timer can't be destroyed in between. Copying the subscribers takes the - /// signal's OS mutexes and can allocate, so it can't happen under GetLock(). - /// Lock order: this, then GetLock(). Not held while callbacks run. - static dmq::RecursiveMutex& GetProcessLock() - { - // Immortal, like GetLock(). - static dmq::RecursiveMutex* lock = new(std::nothrow) dmq::RecursiveMutex(); - if (!lock) - BAD_ALLOC(); - return *lock; - } - - dmq::Duration m_timeout = dmq::Duration(0); - dmq::TimePoint m_expireTime; - std::atomic m_enabled{false}; - bool m_once = false; - Timer* m_next = nullptr; - static std::atomic m_timerStopped; -}; - -} // namespace dmq::util - -#endif diff --git a/DelegateMQ/extras/util/TimerDelegate.h b/DelegateMQ/extras/util/TimerDelegate.h deleted file mode 100644 index e8804d4..0000000 --- a/DelegateMQ/extras/util/TimerDelegate.h +++ /dev/null @@ -1,374 +0,0 @@ -#ifndef TIMER_DELEGATE_H -#define TIMER_DELEGATE_H - -#include "Timer.h" -#include "../../delegate/DelegateAsync.h" -#include "../../delegate/UnicastDelegate.h" -#include - -namespace dmq::util { - -/// @brief Tag type whose lifetime tracks a dispatched message through the thread queue. -/// When the async closure is destroyed after Invoke() completes (or immediately on DROP), -/// the reference count falls to zero and the paired weak_ptr in PacedDispatch expires. -struct DispatchToken { - XALLOCATOR -}; - -/// @brief Gate that enforces at-most-one-in-flight dispatch for a periodic timer source. -/// -/// Solves two problems when a periodic timer drives an async dispatch: -/// - ProcessTimers() stalling: skips DispatchDelegate() entirely if previous message -/// is still queued, so ProcessTimers() never blocks on a TIMEOUT-policy thread. -/// - Queue flooding: at most one pending callback exists at any time; a slow thread -/// won't accumulate a backlog of stale timer events. -/// -/// The caller captures the shared_ptr inside the async lambda. When -/// Invoke() completes and the DelegateMsg is destroyed, the token's ref count drops to -/// zero, the weak_ptr expires, and the next TryFire() can proceed. -/// -/// If the message is dropped (FullPolicy::DROP), the DelegateMsg destructs immediately, -/// the token dies, and TryFire() retries on the next timer expiry. -/// -/// @note Not thread-safe for concurrent TryFire() calls. Safe when ProcessTimers() runs -/// on a single thread, which is the standard usage. -/// @note OnStuck fires from ProcessTimers() context -- keep it fast and non-blocking. -class PacedDispatch -{ - XALLOCATOR -public: - /// @brief Attempt a dispatch if no previous one is in flight. - /// - /// @param dispatchFn Callable receiving a shared_ptr by value. - /// Must capture the token in the async closure so its lifetime - /// tracks the message through the queue. - /// @param stuckTimeout If non-zero and the token is still live after this duration, - /// OnStuck is called. Default: disabled. - /// @return true if dispatch was attempted; false if skipped (already in flight). - template - bool TryFire(F&& dispatchFn, dmq::Duration stuckTimeout = dmq::Duration(0)) - { - if (!m_inFlight.expired()) - { - if (stuckTimeout.count() > 0 && OnStuck) - { - if (Timer::GetNow() - m_dispatchTime > stuckTimeout) - OnStuck(); - } - m_pending = true; - return false; - } - - m_pending = false; - - auto token = dmq::xmake_shared(); - m_inFlight = token; - m_dispatchTime = Timer::GetNow(); - - dispatchFn(std::move(token)); - return true; - } - - bool IsInFlight() const { return !m_inFlight.expired(); } - bool IsPending() const { return m_pending; } - void Reset() { m_inFlight.reset(); m_pending = false; } - - /// Optional. Called from ProcessTimers() context -- must be fast and non-blocking. - dmq::UnicastDelegate OnStuck; - -private: - std::weak_ptr m_inFlight; - dmq::TimePoint m_dispatchTime{}; - bool m_pending = false; -}; - -namespace detail { -/// @brief Target state shared between a TimerDelegate and its queued dispatches. -/// The TimerDelegate owns it; each queued message holds only a weak_ptr, so a -/// message still in the thread queue after the TimerDelegate is destroyed (e.g. -/// its Signal connection was dropped) finds it expired and skips the call -/// instead of touching the deleted TimerDelegate. -struct TimerTarget { - XALLOCATOR - dmq::UnicastDelegate fn; -}; -} // namespace detail - -/// @brief Timer-safe async delegate. Connects a periodic timer to a thread dispatch -/// with built-in queue-flood prevention. -/// -/// Implements Delegate directly so it can be stored in Signal connections -/// without a DelegateFunction wrapper -- eliminating the std::function layer on -/// the hot path. -/// -/// At most one message is in the target thread's queue at any time; excess timer -/// ticks are silently dropped rather than accumulated as backlog. -/// -/// Prefer constructing via MakeTimerDelegate() rather than directly. -/// -/// Destroying, clearing or reassigning a TimerDelegate (including disconnecting the -/// Signal connection that owns it) cancels any tick it has queued that the target -/// thread hasn't started: the target is not invoked. Two cases are not cancelled: -/// - A tick the target thread has already started runs to completion. -/// - Signal::operator() invokes a snapshot of its connections, so a Disconnect() -/// on another thread while Timer::ProcessTimers() is emitting OnExpired can -/// still queue one tick after Disconnect() returns. -/// So disconnecting alone doesn't make it safe to destroy a raw-pointer target. -/// Before freeing the target, stop the timer, disconnect, and let the target -/// thread finish what's queued (e.g. ExitThread(), which drains the queue), as -/// NetworkNode::Stop() does. -/// -/// @note Not intended for concurrent invocation. Safe when operator() is called -/// from a single ProcessTimers() context. -class TimerDelegate : public dmq::Delegate -{ - XALLOCATOR -public: - // Constructor for pre-formed Delegate subtypes (DelegateMember, DelegateFree, etc.). - // Stored directly as a delegate -- no std::function wrapping. - TimerDelegate(const dmq::Delegate& func, dmq::IThread& thr, - dmq::UnicastDelegate onStuck = dmq::UnicastDelegate(), - dmq::Duration stuckTimeout = dmq::Duration(0)) - : m_thread(&thr) - , m_stuckTimeout(stuckTimeout) - { - m_fn = func; - m_gate.OnStuck = std::move(onStuck); - } - - // Constructor for raw callables (lambdas, function pointers, functors). - // SFINAE excludes Delegate subtypes so the overload above is preferred for them. - template > || - !std::is_base_of_v, std::decay_t>>> - TimerDelegate(F&& func, dmq::IThread& thr, - dmq::UnicastDelegate onStuck = dmq::UnicastDelegate(), - dmq::Duration stuckTimeout = dmq::Duration(0)) - : m_thread(&thr) - , m_stuckTimeout(stuckTimeout) - { - m_fn = dmq::DelegateFunction(std::forward(func)); - m_gate.OnStuck = std::move(onStuck); - } - - // A copy shares no state with the original: its own (lazily allocated) target - // and a fresh gate, so destroying either one cancels only its own queued ticks. - TimerDelegate(const TimerDelegate& rhs) - : m_thread(rhs.m_thread) - , m_stuckTimeout(rhs.m_stuckTimeout) - { - m_fn = rhs.Fn(); - m_gate.OnStuck = rhs.m_gate.OnStuck; - } - - TimerDelegate& operator=(const TimerDelegate& rhs) - { - if (this != &rhs) - { - Clear(); // cancels this delegate's queued ticks - m_fn = rhs.Fn(); - m_thread = rhs.m_thread; - m_stuckTimeout = rhs.m_stuckTimeout; - m_gate.OnStuck = rhs.m_gate.OnStuck; - } - return *this; - } - - // A move transfers the target and gate: ticks the source queued now belong to - // the destination, and the source is left empty. - TimerDelegate(TimerDelegate&& rhs) noexcept - : m_fn(std::move(rhs.m_fn)) - , m_target(std::move(rhs.m_target)) - , m_thread(rhs.m_thread) - , m_stuckTimeout(rhs.m_stuckTimeout) - , m_gate(std::move(rhs.m_gate)) - { - rhs.Clear(); - } - - TimerDelegate& operator=(TimerDelegate&& rhs) noexcept - { - if (this != &rhs) - { - m_fn = std::move(rhs.m_fn); - m_target = std::move(rhs.m_target); // releasing the old target cancels its ticks - m_thread = rhs.m_thread; - m_stuckTimeout = rhs.m_stuckTimeout; - m_gate = std::move(rhs.m_gate); - rhs.Clear(); - } - return *this; - } - - virtual void operator()() override - { - if (Empty()) - return; - // Allocated on the first tick rather than at construction, so the temporary - // that Signal::Connect() clones and discards never allocates. - if (!m_target) - { - m_target = dmq::xmake_shared(); - m_target->fn = std::move(m_fn); - } - std::weak_ptr target = m_target; - dmq::IThread& thr = *m_thread; - m_gate.TryFire([&target, &thr](std::shared_ptr token) { - using DelegateType = dmq::DelegateFreeAsync, std::shared_ptr)>; - DelegateType(&TimerDelegate::InvokeTarget, thr)(std::move(target), std::move(token)); - }, m_stuckTimeout); - } - - virtual TimerDelegate* Clone() const override - { - return new(std::nothrow) TimerDelegate(*this); - } - - virtual bool Equal(const dmq::DelegateBase& rhs) const override - { - auto derived = dynamic_cast(&rhs); - if (!derived) return false; - if (Empty() && derived->Empty()) return true; - if (Empty() || derived->Empty()) return false; - if (!Fn().GetDelegate() || !derived->Fn().GetDelegate()) return false; - return m_thread == derived->m_thread && - Fn().GetDelegate()->Equal(*derived->Fn().GetDelegate()); - } - - virtual bool operator==(std::nullptr_t) const noexcept override { return Empty(); } - virtual bool operator!=(std::nullptr_t) const noexcept override { return !Empty(); } - - bool Empty() const noexcept { return Fn().Empty() || !m_thread; } - - /// Empties the delegate and cancels any tick it has queued that hasn't started. - void Clear() noexcept - { - m_fn.Clear(); - m_target.reset(); - m_thread = nullptr; - m_gate.Reset(); - m_gate.OnStuck.Clear(); - } - void operator=(std::nullptr_t) noexcept { Clear(); } - -private: - // The callable: in m_fn until the first tick, then moved into m_target. - const dmq::UnicastDelegate& Fn() const noexcept { return m_target ? m_target->fn : m_fn; } - - // Runs on the target thread. Static so the queued message never refers to the - // TimerDelegate itself; the token is held until the call returns. - static void InvokeTarget(std::weak_ptr target, std::shared_ptr token) - { - (void)token; - if (auto t = target.lock()) - t->fn(); - } - - dmq::UnicastDelegate m_fn; - std::shared_ptr m_target; - dmq::IThread* m_thread = nullptr; - dmq::Duration m_stuckTimeout{0}; - PacedDispatch m_gate; -}; - -/// @brief Create a timer-safe async delegate for a free function or static member function. -/// -/// @code -/// void OnTick() { ... } -/// m_timerConn = m_timer.OnExpired.Connect(MakeTimerDelegate(&OnTick, m_thread)); -/// @endcode -inline TimerDelegate MakeTimerDelegate( - void(*func)(), - dmq::IThread& thr, - dmq::UnicastDelegate onStuck = dmq::UnicastDelegate(), - dmq::Duration stuckTimeout = dmq::Duration(0)) -{ - return TimerDelegate(func, thr, std::move(onStuck), stuckTimeout); -} - -/// @brief Create a timer-safe async delegate for a lambda or other callable. -template -TimerDelegate MakeTimerDelegate( - F&& func, - dmq::IThread& thr, - dmq::UnicastDelegate onStuck = dmq::UnicastDelegate(), - dmq::Duration stuckTimeout = dmq::Duration(0)) -{ - return TimerDelegate(std::forward(func), thr, std::move(onStuck), stuckTimeout); -} - -/// @brief Create a timer-safe async delegate for a non-const member function. -/// -/// At most one dispatch is in flight; excess timer ticks are dropped. -/// DelegateAsyncWait is structurally prevented -- dispatch is always non-blocking. -/// -/// @param obj Raw pointer to target object. Must outlive the delegate. -/// @param method void() non-const member function to invoke. -/// @param thr Thread on which method is dispatched. -/// @param onStuck Optional. Called from ProcessTimers() when stuck is detected. -/// @param stuckTimeout Duration after which a non-expiring in-flight token triggers -/// onStuck. Zero disables. -/// -/// @code -/// m_timerConn = m_timer.OnExpired.Connect( -/// MakeTimerDelegate(this, &MyClass::OnTick, m_thread)); -/// -/// // With stuck detection: -/// m_timerConn = m_timer.OnExpired.Connect( -/// MakeTimerDelegate(this, &MyClass::OnTick, m_thread, -/// dmq::MakeDelegate(this, &MyClass::OnThreadStuck), std::chrono::seconds(2))); -/// @endcode -template -TimerDelegate MakeTimerDelegate( - TClass* obj, - void (TClass::*method)(), - dmq::IThread& thr, - dmq::UnicastDelegate onStuck = dmq::UnicastDelegate(), - dmq::Duration stuckTimeout = dmq::Duration(0)) -{ - return TimerDelegate(dmq::MakeDelegate(obj, method), thr, std::move(onStuck), stuckTimeout); -} - -/// @brief Create a timer-safe async delegate for a const member function. -template -TimerDelegate MakeTimerDelegate( - const TClass* obj, - void (TClass::*method)() const, - dmq::IThread& thr, - dmq::UnicastDelegate onStuck = dmq::UnicastDelegate(), - dmq::Duration stuckTimeout = dmq::Duration(0)) -{ - return TimerDelegate(dmq::MakeDelegate(obj, method), thr, std::move(onStuck), stuckTimeout); -} - -/// @brief Create a timer-safe async delegate for a non-const member function (shared_ptr owner). -/// -/// Captures a weak_ptr internally via DelegateMemberSp. If the object has been destroyed -/// by the time the dispatch fires, the invocation is silently skipped. -template -TimerDelegate MakeTimerDelegate( - std::shared_ptr obj, - void (TClass::*method)(), - dmq::IThread& thr, - dmq::UnicastDelegate onStuck = dmq::UnicastDelegate(), - dmq::Duration stuckTimeout = dmq::Duration(0)) -{ - return TimerDelegate(dmq::MakeDelegate(obj, method), thr, std::move(onStuck), stuckTimeout); -} - -/// @brief Create a timer-safe async delegate for a const member function (shared_ptr owner). -template -TimerDelegate MakeTimerDelegate( - std::shared_ptr obj, - void (TClass::*method)() const, - dmq::IThread& thr, - dmq::UnicastDelegate onStuck = dmq::UnicastDelegate(), - dmq::Duration stuckTimeout = dmq::Duration(0)) -{ - return TimerDelegate(dmq::MakeDelegate(obj, method), thr, std::move(onStuck), stuckTimeout); -} - -} // namespace dmq::util - -#endif \ No newline at end of file diff --git a/DelegateMQ/extras/util/TransportMonitor.h b/DelegateMQ/extras/util/TransportMonitor.h deleted file mode 100644 index 1d8a9af..0000000 --- a/DelegateMQ/extras/util/TransportMonitor.h +++ /dev/null @@ -1,247 +0,0 @@ -#ifndef _TRANSPORT_MONITOR_HH -#define _TRANSPORT_MONITOR_HH - -#include "delegate/DelegateOpt.h" -#include "delegate/Signal.h" -#include "../../port/transport/common/ITransportMonitor.h" -#include -#include -#include - -namespace dmq::util { - -/// @brief A thread-safe monitor for tracking outgoing remote messages and detecting timeouts. -/// -/// @details -/// The TransportMonitor implements the reliability layer for remote delegate invocations. -/// It tracks "in-flight" messages by their sequence number and timestamps them upon sending. -/// -/// **Key Responsibilities:** -/// * **Timeout Detection:** Identifies messages that have not been acknowledged within the -/// configured `TRANSPORT_TIMEOUT` duration. -/// * **Status Reporting:** Invokes the `SendStatusCb` delegate with `Status::SUCCESS` (upon ACK) -/// or `Status::TIMEOUT` (upon expiration) to notify the application. -/// * **Thread Safety:** Internal state is protected by a recursive mutex, allowing safe access -/// from multiple threads (e.g., sending thread vs. ACK receiving thread). -/// -/// **Usage Note:** -/// This class relies on a cooperative polling model. The `Process()` method must be called -/// periodically (typically by a background timer or the network thread loop) to scan for -/// and handle expired messages. -class TransportMonitor : public dmq::transport::ITransportMonitor -{ - XALLOCATOR -public: - enum class Status - { - SUCCESS, // Message received by remote - TIMEOUT // Message timeout - }; - - /// Signal emitted when a message status is determined. - /// Subscribers receive: (remoteId, seqNum, status) - dmq::Signal OnSendStatus; - - /// Signal emitted when the pending map hits MAX_TRANSPORT_MONITOR_PENDING. - /// Subscribers receive: (currentSize) — the number of unacknowledged messages at the time of rejection. - /// Fired outside the internal lock so subscribers may call back into TransportMonitor safely. - dmq::Signal OnCapExceeded; - - /// Signal emitted when Process() fills its batch buffer before emptying m_pending. - /// Subscribers receive: (remaining) — number of entries still in m_pending after the current pass. - /// Indicates that expired messages are accumulating faster than Process() is being called. - /// Fired outside the internal lock so subscribers may call back into TransportMonitor safely. - dmq::Signal OnPendingExceeded; - - /// @param timeout Per-message ACK timeout. Default is dmq::TRANSPORT_MONITOR_TIMEOUT - /// (DMQ_TRANSPORT_MONITOR_TIMEOUT_SEC in delegatemqconfig.h). - TransportMonitor(const dmq::Duration timeout = dmq::TRANSPORT_MONITOR_TIMEOUT) : TRANSPORT_TIMEOUT(timeout) {} - - ~TransportMonitor() - { - const dmq::LockGuard lock(m_lock); - m_pending.clear(); - } - - /// Add a sequence number - /// param[in] seqNum - the delegate message sequence number - /// param[in] remoteId - the remote ID - /// @return true if added; false otherwise. - virtual bool Add(uint16_t seqNum, dmq::DelegateRemoteId remoteId) override - { - size_t capSize = 0; - uint32_t key = (static_cast(remoteId) << 16) | seqNum; - { - const dmq::LockGuard lock(m_lock); - - if (m_pending.size() >= dmq::MAX_TRANSPORT_MONITOR_PENDING) { - capSize = m_pending.size(); - } else if (m_pending.find(key) != m_pending.end()) { - // Collision: 16-bit sequence wrapped before the old message timed out. - // Reject the send rather than silently clobbering the old message's tracking. - LOG_ERROR("TransportMonitor: SeqNum wraparound collision for seq {}", seqNum); - return false; - } else { - TimeoutData d; - d.timeStamp = dmq::Clock::now(); - d.remoteId = remoteId; - d.seqNum = seqNum; - m_pending[key] = d; - } - } - - if (capSize > 0) { - LOG_ERROR("TransportMonitor: Pending map full ({} entries). Check ACK logic or comm link.", capSize); - OnCapExceeded(capSize); - return false; - } - - return true; - } - - /// Remove a sequence number. Invokes SendStatusCb callback to notify - /// registered client of removal. - /// param[in] seqNum - the delegate message sequence number - /// param[in] remoteId - the remote ID (default 0 for backwards compatibility, but strongly recommended) - virtual void Remove(uint16_t seqNum, dmq::DelegateRemoteId remoteId = 0) - { - bool found = false; - TimeoutData d; - uint32_t key = (static_cast(remoteId) << 16) | seqNum; - - { - const dmq::LockGuard lock(m_lock); - - if (remoteId != 0) { - // Exact composite key lookup - auto it = m_pending.find(key); - if (it != m_pending.end()) { - d = it->second; - m_pending.erase(it); - found = true; - } - } else { - // Backwards compatibility: linear scan for seqNum if remoteId is unknown - for (auto it = m_pending.begin(); it != m_pending.end(); ++it) { - if (it->second.seqNum == seqNum) { - d = it->second; - m_pending.erase(it); - found = true; - break; - } - } - } - } - - if (found) - { - OnSendStatus(d.remoteId, seqNum, Status::SUCCESS); - } - } - - // Standard ITransportMonitor override (uses default remoteId 0) - virtual void Remove(uint16_t seqNum) override { Remove(seqNum, 0); } - - /// @brief Silently remove a sequence number without signaling SUCCESS. - /// @details Use this instead of Remove() when the entry must be freed because - /// the send itself is known to have failed (e.g. a synchronous ITransport::Send() - /// error right after Add() succeeded) -- Remove() fires OnSendStatus(..., SUCCESS), - /// which would misreport a failed send as an acknowledged one. Frees the pending - /// slot immediately instead of leaving it to expire via Process()/TRANSPORT_TIMEOUT. - /// @return true if an entry was found and removed. - bool Cancel(uint16_t seqNum, dmq::DelegateRemoteId remoteId) - { - const dmq::LockGuard lock(m_lock); - uint32_t key = (static_cast(remoteId) << 16) | seqNum; - auto it = m_pending.find(key); - if (it == m_pending.end()) - return false; - m_pending.erase(it); - return true; - } - - /// @brief The ACK timeout: how long a message waits for its ACK before - /// TIMEOUT is reported. - dmq::Duration GetTimeout() const { return TRANSPORT_TIMEOUT; } - - /// Call periodically to process message timeouts. - /// Drains all expired entries across multiple passes so a single call always - /// fully clears the backlog, regardless of how many entries have timed out. - void Process() - { - size_t expiredCount = 0; - - do { - expiredCount = 0; - size_t remaining = 0; - - // Local, not a member: it's read after the lock is released, when a - // concurrent Process() on another thread could overwrite a member. - std::array expiredItems; - - { - // Lock ONLY while reading/modifying the map - const dmq::LockGuard lock(m_lock); - - if (m_pending.empty()) - return; - - auto now = dmq::Clock::now(); - auto it = m_pending.begin(); - - while (it != m_pending.end()) - { - auto elapsed = std::chrono::duration_cast(now - (*it).second.timeStamp); - - if (elapsed > TRANSPORT_TIMEOUT) - { - if (expiredCount >= dmq::MAX_TIMER_EXPIRED) { - remaining = m_pending.size(); - break; - } - expiredItems[expiredCount++] = { (*it).second.remoteId, (*it).second.seqNum }; - it = m_pending.erase(it); - } - else - { - // map is sorted by key, not time — must scan all entries - ++it; - } - } - } // Lock is RELEASED here - - // Fire timeout callbacks without holding the lock - for (size_t i = 0; i < expiredCount; ++i) - { - OnSendStatus(expiredItems[i].remoteId, expiredItems[i].seq, Status::TIMEOUT); - } - - // Notify app if a full pass still left entries; loop to drain them - if (remaining > 0) { - LOG_ERROR("TransportMonitor: Cleanup bottleneck — {} entries remain after pass. Continuing drain.", remaining); - OnPendingExceeded(remaining); - } - - } while (expiredCount == dmq::MAX_TIMER_EXPIRED); - } - -private: - struct TimeoutData - { - dmq::DelegateRemoteId remoteId = 0; - uint16_t seqNum = 0; - dmq::TimePoint timeStamp; - }; - - struct ExpiredItem { dmq::DelegateRemoteId remoteId; uint16_t seq; }; - - // Key is (remoteId << 16) | seqNum - dmq::xmap m_pending; - const dmq::Duration TRANSPORT_TIMEOUT; - dmq::RecursiveMutex m_lock; -}; - -} // namespace dmq::util - - -#endif diff --git a/DelegateMQ/extras/util/crc16.h b/DelegateMQ/extras/util/crc16.h deleted file mode 100644 index 8ed3341..0000000 --- a/DelegateMQ/extras/util/crc16.h +++ /dev/null @@ -1,91 +0,0 @@ -#ifndef CRC16_H -#define CRC16_H - -/** - * @file crc16.h - * @brief Header-only 16-bit CRC-CCITT implementation (Polynomial 0x1021). - */ - -// Define USE_CRC_TABLE to use the faster table-based calculation. -// If commented out, the smaller loop-based calculation is used. -#define USE_CRC_TABLE - -namespace dmq::util { - -#ifdef USE_CRC_TABLE - -/** - * @brief CRC-CCITT lookup table based on x^16 + x^12 + x^5 + 1 (0x1021). - * - * `inline constexpr` (C++17) so every translation unit shares one definition. - * Plain `constexpr` at namespace scope has internal linkage, so each TU that - * used the table would get its own 512-byte copy. - */ -inline constexpr unsigned short crcccitt_table[] = { - 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, 0x8108, 0x9129, - 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, 0x1231, 0x0210, 0x3273, 0x2252, - 0x52b5, 0x4294, 0x72f7, 0x62d6, 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, - 0xf3ff, 0xe3de, 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, - 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, 0x3653, 0x2672, - 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, 0xb75b, 0xa77a, 0x9719, 0x8738, - 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, - 0x2802, 0x3823, 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, - 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, 0xdbfd, 0xcbdc, - 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, - 0x2c22, 0x3c03, 0x0c60, 0x1c41, 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, - 0x8d68, 0x9d49, 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, - 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, 0x9188, 0x81a9, - 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, 0x1080, 0x00a1, 0x30c2, 0x20e3, - 0x5004, 0x4025, 0x7046, 0x6067, 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, - 0xe37f, 0xf35e, 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, - 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, 0x34e2, 0x24c3, - 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xa7db, 0xb7fa, 0x8799, 0x97b8, - 0xe75f, 0xf77e, 0xc71d, 0xd73c, 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, - 0x4615, 0x5634, 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, - 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, 0xcb7d, 0xdb5c, - 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, 0x4a75, 0x5a54, 0x6a37, 0x7a16, - 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, - 0x9de8, 0x8dc9, 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, - 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, 0x6e17, 0x7e36, - 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0 -}; - -/** - * @brief Calculates a 16-bit CRC using the table-based method. - */ -inline unsigned short Crc16CalcBlock(const unsigned char* crc_msg, int len, unsigned short crc = 0xFFFF) -{ - while (len--) - crc = (crc << 8) ^ crcccitt_table[(crc >> 8) ^ *crc_msg++]; - return crc; -} - -#else - -/** - * @brief Calculates a 16-bit CRC using the loop-based method (saves memory). - */ -inline unsigned short Crc16CalcBlock(const unsigned char* crc_msg, int len, unsigned short crc = 0xFFFF) -{ - constexpr unsigned short POLY = 0x1021; - unsigned short data; - - while (len--) { - data = static_cast(*crc_msg++ << 8); - for (int i = 8; i > 0; i--) { - if ((data ^ crc) & 0x8000) - crc = static_cast((crc << 1) ^ POLY); - else - crc = static_cast(crc << 1); - data = static_cast(data << 1); - } - } - return crc; -} - -#endif // USE_CRC_TABLE - -} // namespace dmq::util - - -#endif // CRC16_H diff --git a/DelegateMQ/port/fault/Fault.cpp b/DelegateMQ/port/fault/Fault.cpp deleted file mode 100644 index eea88d9..0000000 --- a/DelegateMQ/port/fault/Fault.cpp +++ /dev/null @@ -1,291 +0,0 @@ -// Default FaultHandler()/WatchdogHandler(). An application that provides its -// own defines DMQ_CUSTOM_FAULT_HANDLER, and this file compiles to nothing, so -// it can stay in a build that adds every DelegateMQ source (see src/DelegateMQ.cpp). -#include "delegate/DelegateSelect.h" -#if !defined(DMQ_CUSTOM_FAULT_HANDLER) - -#include "extras/util/Fault.h" -#include -#include - -#if defined(_WIN32) || defined(__linux__) -#include -#include -#include "delegate/DelegateOpt.h" -#endif - -#ifdef _WIN32 -#include -#include -#include -#include -#pragma comment(lib, "dbghelp.lib") -#endif - -#ifdef __linux__ -#include -#include -#include -#endif - -namespace dmq::util { - -#ifdef __linux__ -static void LinuxSignalHandler(int sig) { - const char* name = "Unknown Signal"; - switch (sig) { - case SIGSEGV: name = "SIGSEGV (Segmentation Fault)"; break; - case SIGABRT: name = "SIGABRT (Abort)"; break; - case SIGFPE: name = "SIGFPE (Floating Point Exception)"; break; - case SIGILL: name = "SIGILL (Illegal Instruction)"; break; - case SIGBUS: name = "SIGBUS (Bus Error)"; break; - case SIGTERM: name = "SIGTERM (Termination Request)"; break; - } - FaultHandler(name, (unsigned short)sig); -} - -void InstallCrashHandlers() { - std::signal(SIGSEGV, LinuxSignalHandler); - std::signal(SIGABRT, LinuxSignalHandler); - std::signal(SIGFPE, LinuxSignalHandler); - std::signal(SIGILL, LinuxSignalHandler); - std::signal(SIGBUS, LinuxSignalHandler); - std::signal(SIGTERM, LinuxSignalHandler); -} -#endif - -#ifdef _WIN32 -LONG WINAPI WindowsExceptionFilter(EXCEPTION_POINTERS* pExceptionPointers) { - (void)pExceptionPointers; - FaultHandler("Windows Unhandled Exception", 0); -} - -void InstallCrashHandlers() { - SetUnhandledExceptionFilter(WindowsExceptionFilter); -} -#endif - -#if !defined(_WIN32) && !defined(__linux__) -void InstallCrashHandlers() { - // Stub for other platforms -} -#endif - -#ifdef _WIN32 -static void PrintStackTraceWindows(HANDLE hThread, const char* threadName) { - - DWORD tid = GetThreadId(hThread); - printf("\n--- Stack Trace: %s (TID: %lu) ---\n", (threadName ? threadName : "Unknown"), tid); - fflush(stdout); - - CONTEXT context = { 0 }; - context.ContextFlags = CONTEXT_FULL; - if (!GetThreadContext(hThread, &context)) { - printf(" Failed to get thread context (Error: %lu)\n", GetLastError()); - fflush(stdout); - return; - } - - STACKFRAME64 stackFrame = { 0 }; -#ifdef _M_IX86 - DWORD machineType = IMAGE_FILE_MACHINE_I386; - stackFrame.AddrPC.Offset = context.Eip; - stackFrame.AddrPC.Mode = AddrModeFlat; - stackFrame.AddrFrame.Offset = context.Ebp; - stackFrame.AddrFrame.Mode = AddrModeFlat; - stackFrame.AddrStack.Offset = context.Esp; - stackFrame.AddrStack.Mode = AddrModeFlat; -#elif _M_X64 - DWORD machineType = IMAGE_FILE_MACHINE_AMD64; - stackFrame.AddrPC.Offset = context.Rip; - stackFrame.AddrPC.Mode = AddrModeFlat; - stackFrame.AddrFrame.Offset = context.Rsp; - stackFrame.AddrFrame.Mode = AddrModeFlat; - stackFrame.AddrStack.Offset = context.Rsp; - stackFrame.AddrStack.Mode = AddrModeFlat; -#else - return; -#endif - - HANDLE hProcess = GetCurrentProcess(); - int frameCount = 0; - while (StackWalk64(machineType, hProcess, hThread, &stackFrame, &context, NULL, SymFunctionTableAccess64, SymGetModuleBase64, NULL)) { - if (stackFrame.AddrPC.Offset == 0 || frameCount++ > 50) break; - - char buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR)]; - PSYMBOL_INFO pSymbol = reinterpret_cast(buffer); - pSymbol->SizeOfStruct = sizeof(SYMBOL_INFO); - pSymbol->MaxNameLen = MAX_SYM_NAME; - - DWORD64 displacement = 0; - if (SymFromAddr(hProcess, stackFrame.AddrPC.Offset, &displacement, pSymbol)) { - IMAGEHLP_LINE64 line = { 0 }; - line.SizeOfStruct = sizeof(IMAGEHLP_LINE64); - DWORD lineDisplacement = 0; - if (SymGetLineFromAddr64(hProcess, stackFrame.AddrPC.Offset, &lineDisplacement, &line)) { - printf(" %s [%s:%lu]\n", pSymbol->Name, line.FileName, line.LineNumber); - } else { - printf(" %s (no line info)\n", pSymbol->Name); - } - } else { - printf(" 0x%llX (no symbol info)\n", stackFrame.AddrPC.Offset); - } - fflush(stdout); - } -} - -static void PrintAllThreadsStackTraces() { - printf("\nCapturing stack traces for all threads...\n"); - fflush(stdout); - - HANDLE hProcess = GetCurrentProcess(); - SymSetOptions(SYMOPT_LOAD_LINES | SYMOPT_UNDNAME); - - // Use FALSE for fInvadeProcess to avoid Error 87 in some environments. - // Symbols will be loaded on-demand. - if (!SymInitialize(hProcess, NULL, FALSE)) { - printf("SymInitialize failed (Error: %lu)\n", GetLastError()); - fflush(stdout); - return; - } - - // Refresh modules manually since we didn't invade - SymRefreshModuleList(hProcess); - - DWORD currentProcessId = GetCurrentProcessId(); - DWORD currentThreadId = GetCurrentThreadId(); - HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); - - if (hSnapshot != INVALID_HANDLE_VALUE) { - THREADENTRY32 te = { 0 }; - te.dwSize = sizeof(THREADENTRY32); - - if (Thread32First(hSnapshot, &te)) { - do { - if (te.th32OwnerProcessID == currentProcessId) { - if (te.th32ThreadID == currentThreadId) { - PrintStackTraceWindows(GetCurrentThread(), "Fault/Watchdog Thread"); - } else { - HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, te.th32ThreadID); - if (hThread) { - SuspendThread(hThread); - PrintStackTraceWindows(hThread, "Suspended Thread"); - ResumeThread(hThread); - CloseHandle(hThread); - } - } - } - } while (Thread32Next(hSnapshot, &te)); - } - CloseHandle(hSnapshot); - } - SymCleanup(hProcess); - printf("\nStack trace capture complete.\n"); - fflush(stdout); -} -#endif - -#ifdef __linux__ -static void PrintStackTraceLinux() { - void* array[50]; - int size = backtrace(array, 50); - char** symbols = backtrace_symbols(array, size); - printf("\n--- Stack Trace (Current Thread) ---\n"); - for (int i = 0; i < size; i++) { - printf(" %s\n", symbols[i]); - } - fflush(stdout); - free(symbols); -} -#endif - -//---------------------------------------------------------------------------- -// FaultHandler -//---------------------------------------------------------------------------- -DMQ_NORETURN void FaultHandler(const char* file, unsigned short line) -{ - // 1. PRINT FIRST - printf("\n************************************************\n"); - printf("FaultHandler called. Application terminated.\n"); - printf("File: %s Line: %u\n", file, static_cast(line)); - printf("************************************************\n"); - fflush(stdout); - -#if defined(_WIN32) || defined(__linux__) - LOG_ERROR("FaultHandler File={} Line={}", file, line); -#endif - - // 2. PRINT STACK TRACES -#ifdef _WIN32 - PrintAllThreadsStackTraces(); -#elif defined(__linux__) - PrintStackTraceLinux(); -#endif - - // 3. Break only if interactive or specifically desired -#ifdef _WIN32 - if (IsDebuggerPresent()) { - DebugBreak(); - } -#endif - - // 4. Force exit -#if defined(__linux__) - printf("\nTerminating application...\n"); - fflush(stdout); - - // When running via terminal wrappers (like xterm -e), the console closes - // immediately on exit. Wait for input to allow the user to read the crash info. - // Note: isatty() can return false when stdin is redirected by the wrapper. - printf("Press Enter to exit (or wait 60s)..."); - fflush(stdout); - - // Set a timeout on stdin so we don't hang forever in CI/headless - struct timeval tv; - fd_set fds; - tv.tv_sec = 60; - tv.tv_usec = 0; - FD_ZERO(&fds); - FD_SET(STDIN_FILENO, &fds); - if (select(STDIN_FILENO + 1, &fds, NULL, NULL, &tv) > 0) { - (void)getchar(); - } - - abort(); -#elif defined(_WIN32) - printf("\nTerminating application...\n"); - fflush(stdout); - abort(); -#else - printf("FaultHandler: %s line %u\r\n", file, static_cast(line)); - fflush(stdout); - while(1); -#endif -} - -} // namespace dmq::util - -extern "C" DMQ_NORETURN void FaultHandler(const char* file, unsigned short line) -{ - dmq::util::FaultHandler(file, line); -} - -extern "C" void InstallCrashHandlers() -{ - dmq::util::InstallCrashHandlers(); -} - -extern "C" DMQ_NORETURN void WatchdogHandler(const char* threadName) -{ -#if defined(_WIN32) || defined(__linux__) - std::cout << "\n************************************************" << std::endl; - std::cout << "WATCHDOG EXPIRED: " << threadName << std::endl; - std::cout << "************************************************\n" << std::endl; - DMQ_ASSERT(); -#else - printf("WATCHDOG EXPIRED: %s\r\n", threadName); - while (1); -#endif -} - -#endif // !DMQ_CUSTOM_FAULT_HANDLER diff --git a/DelegateMQ/port/os/README.md b/DelegateMQ/port/os/README.md deleted file mode 100644 index 0c863d1..0000000 --- a/DelegateMQ/port/os/README.md +++ /dev/null @@ -1,73 +0,0 @@ -# OS Ports (DelegateMQ Abstraction Layer) - -This directory contains the OS part of the **DelegateMQ Abstraction Layer**: the concrete threading implementations required to execute asynchronous delegates, plus the portable mutex, semaphore, clock and critical-section types the whole library uses. The transport and serializer parts are in `port/transport` and `port/serialize`. - -By abstracting the threading model behind the `dmq::IThread` interface, DelegateMQ can run seamlessly on everything from high-performance servers (Windows/Linux) to resource-constrained embedded systems (FreeRTOS, ThreadX, Zephyr). - -## Implementations - -The subdirectories contain the platform-specific thread wrappers: - -* **`stdlib`**: Standard C++11 implementation. - * *Target:* Windows, Linux, macOS, or any OS with a compliant C++ Standard Library. - * *Implementation:* Uses `std::thread`, `std::mutex`, `std::condition_variable`, and `std::promise`. -* **`win32`**: Native Windows implementation. - * *Target:* Windows. - * *Implementation:* Uses Win32 thread and message-queue APIs directly rather than `std::thread`. -* **`posix`**: Raw POSIX implementation. - * *Target:* Linux (verified). Written against the POSIX API rather than any Linux-specific - syscall, but `pthread_condattr_setclock(CLOCK_MONOTONIC)` -- used here so timed waits are - immune to wall-clock jumps -- is a common POSIX extension present on Linux (glibc, musl) and - not guaranteed elsewhere (e.g. not implemented on Darwin/macOS), so treat portability beyond - Linux as untested rather than assumed. - * *Implementation:* Uses native POSIX primitives directly -- `pthread_create`, `pthread_mutex_t`, - `pthread_cond_t` (with `CLOCK_MONOTONIC` via `pthread_condattr_setclock`) -- rather than going - through `std::thread`. Mutex/ConditionVariable/Clock/ThisThread still reuse the same `std::` - types as `stdlib` (already thin wrappers over these same primitives under glibc/libstdc++); - only the `Thread` class itself is native, mirroring `win32`'s relationship to `stdlib` but for - POSIX. See `example/sample-projects/posix-linux/`. -* **`freertos`**: Real-Time OS implementation. - * *Target:* Embedded ARM Cortex-M (STM32, NXP, etc.), ESP32, and others running FreeRTOS. - * *Implementation:* Uses native FreeRTOS primitives: `xTaskCreate`, `xQueueSend/Receive`, and `vTaskDelay`. -* **`threadx`**: Azure RTOS (ThreadX) implementation. - * *Target:* Enterprise embedded devices running Eclipse ThreadX (formerly Azure RTOS). - * *Implementation:* Uses `tx_thread_create` and `tx_queue_send/receive`. -* **`zephyr`**: Zephyr RTOS implementation. - * *Target:* Modern IoT devices supported by the Zephyr Project. - * *Implementation:* Uses kernel primitives `k_thread_create` and `k_msgq_put/get`. -* **`cmsis-rtos2`**: CMSIS-RTOS API v2 implementation. - * *Target:* Any kernel compliant with the ARM CMSIS-RTOS2 standard (Keil RTX5, Micrium OS, etc.). - * *Implementation:* Uses standard APIs `osThreadNew` and `osMessageQueuePut/Get`. -* **`nuttx`**: Apache NuttX RTOS implementation. - * *Target:* Any board supported by NuttX (POSIX-compliant embedded RTOS), including its `sim` simulation target. - * *Implementation:* Uses NuttX's native POSIX APIs directly: `pthread_create`, `pthread_mutex_t`, `sem_t`, and a POSIX `mqueue` (with native `msg_prio`-based priority) for message passing. -* **`bare-metal`**: No-OS support (`DMQ_THREAD_NONE`). - * *Target:* Super-loop firmware on ARM Cortex-M or RISC-V. - * *Implementation:* Provides `Clock`, `ThisThread` and an ISR-safe `CriticalSection` so synchronous delegates, signals and `dmq::util::Timer` work; there is no `Thread`, so asynchronous delegates are unavailable. -* **`qt`**: Qt Framework implementation. - * *Target:* Desktop or embedded GUI applications using Qt. - * *Implementation:* Uses `QThread` and the native Signal & Slot mechanism (`moveToThread`) to safely dispatch delegates to the Qt Event Loop. - -## Configuration - -To select the appropriate threading model, set the `DMQ_THREAD` variable in your CMake configuration: - -```cmake -# Options: -# DMQ_THREAD_STDLIB (Default for PC/Linux) -# DMQ_THREAD_WIN32 (Native Win32 threads) -# DMQ_THREAD_POSIX (Raw POSIX pthreads -- Linux, verified) -# DMQ_THREAD_FREERTOS (FreeRTOS) -# DMQ_THREAD_THREADX (Azure RTOS ThreadX) -# DMQ_THREAD_ZEPHYR (Zephyr RTOS) -# DMQ_THREAD_CMSIS_RTOS2 (ARM CMSIS-RTOS2) -# DMQ_THREAD_NUTTX (Apache NuttX RTOS) -# DMQ_THREAD_QT (Qt Framework) -# DMQ_THREAD_NONE (For Bare-metal super-loops) - -set(DMQ_THREAD "DMQ_THREAD_STDLIB" CACHE STRING "" FORCE) -``` - -## Custom Porting - -If you need to run DelegateMQ on a different OS (e.g., VxWorks, QNX, or a proprietary kernel), you can simply implement the `dmq::IThread` interface and inject your custom thread wrapper into the library. diff --git a/DelegateMQ/port/os/bare-metal/BareMetalClock.h b/DelegateMQ/port/os/bare-metal/BareMetalClock.h deleted file mode 100644 index b1ac27b..0000000 --- a/DelegateMQ/port/os/bare-metal/BareMetalClock.h +++ /dev/null @@ -1,62 +0,0 @@ -#ifndef BARE_METAL_CLOCK_H -#define BARE_METAL_CLOCK_H - -#include -#include - -// 1. Declare the external tick counter. -// This variable must be defined in your main.cpp or startup.c -// and incremented by your SysTick_Handler (or other timer ISR). -extern "C" volatile uint64_t g_ticks; - -namespace dmq::os { - - struct BareMetalClock { - // 2. Define duration traits - // We assume g_ticks represents Milliseconds (1/1000 sec). - // If your timer runs at a different rate (e.g. Microseconds), change std::milli to std::micro. - using rep = int64_t; - using period = std::milli; - using duration = std::chrono::duration; - using time_point = std::chrono::time_point; - - static const bool is_steady = true; - - // 3. The critical "now()" function - static time_point now() noexcept { - // On a 32-bit target, reading a 64-bit value requires two 32-bit - // loads. A timer ISR firing between them would produce a torn - // read, so interrupts are masked for the read. The previous - // interrupt state is saved and restored, not unconditionally - // re-enabled: Timer calls this while holding its - // BareMetalCriticalSection (Timer::Start(), and ProcessTimers() -> - // CheckExpired(), possibly from the timer ISR itself), and turning - // interrupts back on there would let the ISR run ProcessTimers() - // against a half-updated timer list. Same technique as - // BareMetalCriticalSection. -#if defined(__riscv) - unsigned long prev; - __asm__ volatile("csrrci %0, mstatus, 0x8" : "=r"(prev) :: "memory"); // clear MIE, save old - uint64_t t = g_ticks; - __asm__ volatile("csrs mstatus, %0" :: "r"(prev & 0x8ul) : "memory"); // restore MIE only if it was set -#elif defined(__arm__) && (defined(__GNUC__) || defined(__clang__)) - uint32_t prev; - __asm__ volatile("mrs %0, primask" : "=r"(prev) :: "memory"); - __asm__ volatile("cpsid i" ::: "memory"); - uint64_t t = g_ticks; - __asm__ volatile("msr primask, %0" :: "r"(prev) : "memory"); -#elif defined(__CC_ARM) || defined(__ARMCC_VERSION) - uint32_t prev = __get_PRIMASK(); - __disable_irq(); - uint64_t t = g_ticks; - __set_PRIMASK(prev); -#else - // Fallback: plain read (safe on platforms with atomic 64-bit loads) - uint64_t t = g_ticks; -#endif - return time_point(duration(static_cast(t))); - } - }; -} // namespace dmq::os - -#endif // BARE_METAL_CLOCK_H \ No newline at end of file diff --git a/DelegateMQ/port/os/bare-metal/BareMetalCriticalSection.h b/DelegateMQ/port/os/bare-metal/BareMetalCriticalSection.h deleted file mode 100644 index 8e8f9b1..0000000 --- a/DelegateMQ/port/os/bare-metal/BareMetalCriticalSection.h +++ /dev/null @@ -1,97 +0,0 @@ -#ifndef BARE_METAL_CRITICAL_SECTION_H -#define BARE_METAL_CRITICAL_SECTION_H - -/// @file BareMetalCriticalSection.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief ISR-safe critical section for bare metal (no RTOS). -/// -/// @details -/// Bare metal has no threads, so dmq::Mutex/RecursiveMutex are correctly a -/// no-op (NullMutex) there -- but that same no-op is NOT correct for a -/// critical section: real hardware ISRs still exist and can still preempt -/// the main loop even with no RTOS at all. dmq::util::Timer::ProcessTimers() -/// is commonly driven from a hardware ISR on this port (e.g. -/// SysTick_Handler), so its lock genuinely needs interrupt masking. -/// -/// Uses the same save-and-disable/restore technique, and the same per- -/// architecture branching, that BareMetalClock.h already uses for the -/// identical reason -- raw inline assembly (ARM: MRS/MSR PRIMASK: RISC-V: -/// CSRRCI/CSRS on mstatus.MIE) rather than a vendor intrinsics header, -/// since a minimal bare-metal build may not pull in the full CMSIS-Core -/// headers CmsisRtos2CriticalSection.h relies on for ARM, and there is no -/// RISC-V equivalent of CMSIS-Core at all. -/// -/// *** NARROW PURPOSE -- DO NOT USE THIS AS A GENERAL-PURPOSE LOCK *** -/// Holding this masks ALL maskable interrupts on the CPU for as long as it -/// is held. Only use it to protect something genuinely tiny and bounded -/// that may be touched from ISR context. -/// -/// *** NOT RE-LOCKABLE ON THE SAME INSTANCE *** -/// Calling lock() twice on the SAME instance without an intervening -/// unlock() is incorrect -- see ThreadXCriticalSection.h for the full -/// explanation; the same reasoning applies here. Locking two DIFFERENT -/// instances in proper LIFO lock/unlock order is fine. - -#include - -namespace dmq::os { - - // ========================================================================= - // BareMetalCriticalSection - // See the file-level comment above before using this type anywhere new. - // ========================================================================= - class BareMetalCriticalSection { - public: - BareMetalCriticalSection() = default; - - void lock() { -#if defined(__riscv) - // csrrci atomically reads mstatus into m_savedState AND clears - // the bits set in the immediate (0x8 = MIE, bit 3) in one - // instruction -- no separate disable step needed. - __asm__ volatile ("csrrci %0, mstatus, 0x8" : "=r" (m_savedState)); -#elif defined(__arm__) && (defined(__GNUC__) || defined(__clang__)) - __asm__ volatile ("mrs %0, primask" : "=r" (m_savedState)); - __asm__ volatile ("cpsid i" ::: "memory"); -#elif defined(__CC_ARM) || defined(__ARMCC_VERSION) - m_savedState = __get_PRIMASK(); - __disable_irq(); -#else - // Fallback: no real interrupt masking available on this - // toolchain/target -- see BareMetalClock.h for the same - // fallback rationale. - m_savedState = 0; -#endif - } - - void unlock() { -#if defined(__riscv) - // Restore mstatus.MIE only if it was set before lock() -- - // csrs ORs its argument's set bits into mstatus, so masking - // m_savedState down to just the MIE bit before restoring - // means an already-clear MIE (interrupts were off before this - // lock() at all, e.g. nested inside another disabled region) - // stays clear rather than being unconditionally forced back on. - __asm__ volatile ("csrs mstatus, %0" :: "r" (m_savedState & 0x8u) : "memory"); -#elif defined(__arm__) && (defined(__GNUC__) || defined(__clang__)) - __asm__ volatile ("msr primask, %0" :: "r" (m_savedState) : "memory"); -#elif defined(__CC_ARM) || defined(__ARMCC_VERSION) - __set_PRIMASK(m_savedState); -#endif - } - - // No try_lock(): interrupt masking cannot fail to "acquire", so a - // try_lock() here would always trivially succeed and isn't meaningful. - - BareMetalCriticalSection(const BareMetalCriticalSection&) = delete; - BareMetalCriticalSection& operator=(const BareMetalCriticalSection&) = delete; - - private: - uint32_t m_savedState = 0; - }; - -} // namespace dmq::os - -#endif // BARE_METAL_CRITICAL_SECTION_H diff --git a/DelegateMQ/port/os/bare-metal/BareMetalThisThread.h b/DelegateMQ/port/os/bare-metal/BareMetalThisThread.h deleted file mode 100644 index 19eb730..0000000 --- a/DelegateMQ/port/os/bare-metal/BareMetalThisThread.h +++ /dev/null @@ -1,42 +0,0 @@ -#ifndef BARE_METAL_THIS_THREAD_H -#define BARE_METAL_THIS_THREAD_H - -/// @file BareMetalThisThread.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief Portable sleep_for()/yield() for the calling thread, bare-metal backend. -/// -/// @details -/// This is dmq::ThisThread for this port (see DelegateOpt.h). GetCurrent() -/// has no per-thread storage here yet and returns nullptr. There is -/// no scheduler on DMQ_THREAD_NONE, so sleep_for() busy-waits against -/// BareMetalClock -- the same tick source Timer already keys off of -- rather -/// than pretending a real blocking delay exists. yield() is a no-op: with a -/// single thread of control (a superloop), there is nothing else to hand the -/// CPU to; hardware ISRs preempt regardless of this call. - -#include "BareMetalClock.h" -#include "port/os/common/CurrentThreadStorage.h" -#include - -namespace dmq::os { - - struct BareMetalThisThread : NoCurrentThread { - template - static void sleep_for(std::chrono::duration d) { - const auto ms = std::chrono::duration_cast(d); - auto start = BareMetalClock::now(); - while (BareMetalClock::now() - start < ms) { - // Busy-wait: no scheduler to yield to on bare metal. - } - } - - static void yield() noexcept { - // No-op: single thread of control on bare metal. - } - }; - -} // namespace dmq::os - -#endif // BARE_METAL_THIS_THREAD_H diff --git a/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Clock.h b/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Clock.h deleted file mode 100644 index b495611..0000000 --- a/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Clock.h +++ /dev/null @@ -1,70 +0,0 @@ -#ifndef CMSIS_RTOS2_CLOCK_H -#define CMSIS_RTOS2_CLOCK_H - -#include "cmsis_os2.h" -#include "CmsisRtos2CriticalSection.h" -#include "CmsisRtos2Ticks.h" -#include - -namespace dmq::os { - struct CmsisRtos2Clock { - // Milliseconds. now() converts the kernel tick count using the - // kernel's tick rate (osKernelGetTickFreq()), so any tick rate works. - using rep = int64_t; - using period = std::milli; - using duration = std::chrono::duration; - using time_point = std::chrono::time_point; - static const bool is_steady = true; - - static time_point now() noexcept { - // Static state to track the 32-bit rollover. - // osKernelGetTickCount() wraps after 2^32 ticks (~49.7 days at 1 kHz). - - // NOTE: This implementation relies on static state. - // It must be called at least once per wrap period to detect the wrap. - // - // Thread/ISR safety: dmq::util::Timer::ProcessTimers() (the only - // caller that needs 'last'/'high' updated atomically) is documented - // as callable from ISR context, and on CMSIS-RTOS2/Zephyr that's a - // real requirement, not a hypothetical -- a k_timer expiry_fn (which - // is what a CMSIS-RTOS2 osTimer callback compiles down to under - // Zephyr's compatibility layer) runs in genuine ISR context per - // Zephyr's own kernel.h. osKernelLock()/osKernelRestoreLock() are - // NOT ISR-safe -- Zephyr's implementation returns osErrorISR from - // osKernelLock() when called from an ISR, but osKernelRestoreLock() - // unconditionally writes that error code into the interrupted - // thread's own scheduler-lock-nesting count before it even checks - // for ISR context, corrupting scheduler state (verified: this is - // exactly what caused a one-shot dmq::util::Timer to refire forever - // instead of once, in example/sample-projects/cmsis-rtos2-linux). - // dmq::CriticalSection is the primitive this library already uses - // everywhere else for "must work from both thread and ISR context" - // (see CLAUDE.md's "ISR-Safe Locking" section) -- used here for the - // same reason. - static uint32_t last = 0; - static uint64_t high = 0; - - CmsisRtos2CriticalSection lock; - lock.lock(); - - uint32_t cur = osKernelGetTickCount(); - - // Check for wrap-around (current time is less than last seen time) - if (cur < last) { - // Add 2^32 to the high part accumulator - high += 0x100000000ULL; - } - - last = cur; - - // Combine the high part with the current low part. - uint64_t ticks = high + cur; - - lock.unlock(); - - return time_point(duration(static_cast(CmsisRtos2TicksToMs(ticks)))); - } - }; -} // namespace dmq::os - -#endif // CMSIS_RTOS2_CLOCK_H \ No newline at end of file diff --git a/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2CriticalSection.h b/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2CriticalSection.h deleted file mode 100644 index 71aedbd..0000000 --- a/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2CriticalSection.h +++ /dev/null @@ -1,86 +0,0 @@ -#ifndef CMSIS_RTOS2_CRITICAL_SECTION_H -#define CMSIS_RTOS2_CRITICAL_SECTION_H - -/// @file CmsisRtos2CriticalSection.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief ISR-safe critical section for CMSIS-RTOS2. -/// -/// @details -/// osMutexAcquire()/osMutexNew() are explicitly documented as not callable -/// from Interrupt Service Routines. Unlike Zephyr/ThreadX, CMSIS-RTOS2 has -/// no ISR-safe primitive of its own for this -- so this type bypasses -/// osMutex entirely and drops to the ARM Cortex-M CMSIS-Core intrinsics -/// directly (__get_PRIMASK()/__disable_irq()/__set_PRIMASK()), since -/// CMSIS-RTOS2 always sits on ARM Cortex-M. This is the same save/restore -/// technique BareMetalClock.h and ThreadXCriticalSection.h already use for -/// the identical reason: global interrupt masking is the only primitive -/// that is valid from both thread and ISR context on this architecture. -/// -/// @note UNVERIFIED: written against documented CMSIS-RTOS2/CMSIS-Core API -/// behavior. No CMSIS-RTOS2 SDK (e.g. Keil RTX5) or Cortex-M hardware/QEMU -/// target is available in this development environment to build and run it -/// (unlike ThreadXCriticalSection, exercised for real via the threadx-linux -/// sample). __get_PRIMASK()/__set_PRIMASK()/__disable_irq() are standard -/// CMSIS-Core intrinsics -- declared in cmsis_gcc.h (or the armclang/IAR -/// equivalent selected by cmsis_compiler.h), NOT in cmsis_os2.h itself, so -/// this file includes cmsis_compiler.h directly rather than assuming a -/// vendor device header already pulled it in transitively. -/// -/// *** NARROW PURPOSE -- DO NOT USE THIS AS A GENERAL-PURPOSE LOCK *** -/// Holding this masks ALL maskable interrupts on the CPU for as long as it -/// is held. Only use it to protect something genuinely tiny and bounded -/// that may be touched from ISR context. Do NOT use it in place of -/// dmq::Mutex / dmq::RecursiveMutex for ordinary thread-to-thread -/// synchronization (e.g. DataBus internals, a Thread's message queue) -- -/// anything that can block, take a while, or run for an unbounded time -/// must not run with interrupts globally masked; that is a real-time -/// correctness bug on hardware, not just a style issue. -/// -/// *** NOT RE-LOCKABLE ON THE SAME INSTANCE *** -/// Unlike dmq::RecursiveMutex, calling lock() twice on the SAME instance -/// without an intervening unlock() is incorrect: the second lock() call -/// overwrites the single saved PRIMASK member with the (already disabled) -/// inner state, so the outer unlock() restores the wrong state and -/// interrupts are left disabled permanently. There is no "recursive" -/// variant of this type -- it has no ownership concept to make recursion -/// meaningful, and Timer's own usage never nests. Locking two DIFFERENT -/// instances in proper LIFO lock/unlock order is fine: each instance saves -/// and restores its own PRIMASK independently. - -#include "cmsis_os2.h" -#include "cmsis_compiler.h" - -namespace dmq::os { - - // ========================================================================= - // CmsisRtos2CriticalSection - // See the file-level comment above before using this type anywhere new. - // ========================================================================= - class CmsisRtos2CriticalSection { - public: - CmsisRtos2CriticalSection() = default; - - void lock() { - m_savedPrimask = __get_PRIMASK(); - __disable_irq(); - } - - void unlock() { - __set_PRIMASK(m_savedPrimask); - } - - // No try_lock(): interrupt masking cannot fail to "acquire", so a - // try_lock() here would always trivially succeed and isn't meaningful. - - CmsisRtos2CriticalSection(const CmsisRtos2CriticalSection&) = delete; - CmsisRtos2CriticalSection& operator=(const CmsisRtos2CriticalSection&) = delete; - - private: - uint32_t m_savedPrimask = 0; - }; - -} // namespace dmq::os - -#endif // CMSIS_RTOS2_CRITICAL_SECTION_H diff --git a/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2DelegateQueue.h b/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2DelegateQueue.h deleted file mode 100644 index 6f3d093..0000000 --- a/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2DelegateQueue.h +++ /dev/null @@ -1,168 +0,0 @@ -#ifndef CMSIS_RTOS2_DELEGATE_QUEUE_H -#define CMSIS_RTOS2_DELEGATE_QUEUE_H - -/// @file CmsisRtos2DelegateQueue.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief Thin RAII wrapper around a pair of CMSIS-RTOS2 osMessageQueue -/// primitives used by dmq::os::Thread to carry pending ThreadMsg pointers, -/// with priority support. See the Priority enum in delegate/DelegateMsg.h for -/// the cross-port ordering contract this class must uphold. -/// -/// @details -/// *** DO NOT "SIMPLIFY" THIS BACK TO ONE QUEUE + msg_prio *** -/// osMessageQueuePut() takes a msg_prio argument, and an earlier version of -/// this class relied on it for HIGH priority with a single queue. CMSIS-RTOS2 -/// leaves msg_prio's effect to the implementation, and common ones ignore it: -/// Zephyr's CMSIS-RTOS2 layer (the backend this port is verified on) does -/// ARG_UNUSED(msg_prio) and always appends with k_msgq_put(), so HIGH messages -/// were delivered behind every NORMAL one already queued, breaking the Priority -/// contract every other port meets. -/// -/// The fix is the same design as FreeRTOSDelegateQueue and ThreadXDelegateQueue: -/// two independent osMessageQueue instances, one per priority lane, both always -/// appended to, and a counting osSemaphore as a shared "doorbell". Every -/// successful Send() (to either lane) releases the semaphore once; Receive() -/// acquires it (the single blocking wait) and then does a non-blocking get, -/// checking the HIGH lane first so it drains ahead of NORMAL while each lane -/// stays FIFO. -/// -/// Each lane is sized to the full requested 'capacity', so worst-case combined -/// depth is 2x capacity; the semaphore's max count is sized to match (2x -/// capacity) so a Send() that already found room in its lane can never fail to -/// release it. -/// -/// Send() is callable from an ISR with a zero timeout (osMessageQueuePut and -/// osSemaphoreRelease are ISR-safe in CMSIS-RTOS2); Receive() is only called by -/// the owning thread. This class owns no policy decisions of its own -/// (FullPolicy, timeout computation, and stats stay in Thread.cpp) -- it only -/// knows how to move ThreadMsg* pointers through two fixed-capacity CMSIS-RTOS2 -/// queues in priority order. - -#include "cmsis_os2.h" -#include "port/os/common/ThreadMsg.h" - -namespace dmq::os { - -class CmsisRtos2DelegateQueue -{ -public: - CmsisRtos2DelegateQueue() = default; - ~CmsisRtos2DelegateQueue() { Destroy(); } - - CmsisRtos2DelegateQueue(const CmsisRtos2DelegateQueue&) = delete; - CmsisRtos2DelegateQueue& operator=(const CmsisRtos2DelegateQueue&) = delete; - - /// Create both lanes (each with room for 'capacity' pointers) and the - /// doorbell semaphore. On a partial failure everything created so far is - /// destroyed, so a later Create() starts clean. - /// @return true on success, false if any CMSIS-RTOS2 object couldn't be created. - bool Create(size_t capacity) - { - if (IsCreated()) - return true; - - const uint32_t cap = static_cast(capacity); - if (!m_highQueue) - m_highQueue = osMessageQueueNew(cap, sizeof(ThreadMsg*), NULL); - if (!m_normalQueue) - m_normalQueue = osMessageQueueNew(cap, sizeof(ThreadMsg*), NULL); - if (!m_countSem) - m_countSem = osSemaphoreNew(cap * 2, 0, NULL); - - if (!IsCreated()) { - Destroy(); - return false; - } - return true; - } - - bool IsCreated() const { return m_highQueue != NULL && m_normalQueue != NULL && m_countSem != NULL; } - - /// Send a message pointer. 'highPriority' routes to the HIGH lane, which - /// Receive() always drains first; otherwise the NORMAL lane. Both lanes are - /// always appended to. 'waitOption' is 0 for non-blocking, osWaitForever to - /// block forever, or a finite timeout in kernel ticks (see CmsisRtos2ToTicks()); - /// it applies only to waiting for room in the lane. - /// @return true if the message was enqueued. - bool Send(ThreadMsg* msg, bool highPriority, uint32_t waitOption) - { - osMessageQueueId_t q = highPriority ? m_highQueue : m_normalQueue; - if (osMessageQueuePut(q, &msg, 0, waitOption) != osOK) - return false; - osSemaphoreRelease(m_countSem); - return true; - } - - /// Receive a message pointer, HIGH lane first, blocking up to 'waitOption' - /// for either lane to have one. - /// @return the message, or nullptr on timeout. - ThreadMsg* Receive(uint32_t waitOption) - { - if (osSemaphoreAcquire(m_countSem, waitOption) != osOK) - return nullptr; // timed out waiting for either lane - - ThreadMsg* msg = nullptr; - if (osMessageQueueGet(m_highQueue, &msg, NULL, 0) == osOK) - return msg; - if (osMessageQueueGet(m_normalQueue, &msg, NULL, 0) == osOK) - return msg; - return nullptr; - } - - /// Current number of messages waiting in both lanes. - size_t Size() const - { - if (!m_highQueue || !m_normalQueue) - return 0; - return static_cast(osMessageQueueGetCount(m_highQueue)) - + static_cast(osMessageQueueGetCount(m_normalQueue)); - } - - /// Remove and delete every pending message without blocking. Used during - /// shutdown once the owning thread has stopped consuming the queue. - /// Each message is canceled first (CancelThreadMsg()), releasing a sender - /// blocked waiting on it. - void DrainAndDelete() - { - ThreadMsg* msg = nullptr; - if (m_highQueue) { - while (osMessageQueueGet(m_highQueue, &msg, NULL, 0) == osOK) { - CancelThreadMsg(*msg); // Release a sender blocked on it - delete msg; - } - } - if (m_normalQueue) { - while (osMessageQueueGet(m_normalQueue, &msg, NULL, 0) == osOK) { - CancelThreadMsg(*msg); // Release a sender blocked on it - delete msg; - } - } - } - - void Destroy() - { - if (m_highQueue) { - osMessageQueueDelete(m_highQueue); - m_highQueue = NULL; - } - if (m_normalQueue) { - osMessageQueueDelete(m_normalQueue); - m_normalQueue = NULL; - } - if (m_countSem) { - osSemaphoreDelete(m_countSem); - m_countSem = NULL; - } - } - -private: - osMessageQueueId_t m_highQueue = NULL; - osMessageQueueId_t m_normalQueue = NULL; - osSemaphoreId_t m_countSem = NULL; -}; - -} // namespace dmq::os - -#endif // CMSIS_RTOS2_DELEGATE_QUEUE_H diff --git a/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Mutex.h b/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Mutex.h deleted file mode 100644 index f8a1abf..0000000 --- a/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Mutex.h +++ /dev/null @@ -1,88 +0,0 @@ -#ifndef CMSIS_RTOS2_MUTEX_H -#define CMSIS_RTOS2_MUTEX_H - -#include "cmsis_os2.h" -#include - -namespace dmq::os { - - // ========================================================================= - // CmsisRtos2Mutex (Non-Recursive) - // ========================================================================= - class CmsisRtos2Mutex { - public: - CmsisRtos2Mutex() { - // Explicitly define attributes as 0 (Non-Recursive) - osMutexAttr_t attr = {0}; - attr.attr_bits = 0; - m_id = osMutexNew(&attr); - assert(m_id != NULL); - } - - ~CmsisRtos2Mutex() { - if (m_id) osMutexDelete(m_id); - } - - void lock() { - if (m_id) osMutexAcquire(m_id, osWaitForever); - } - - // REQUIRED for std::unique_lock compatibility - bool try_lock() { - if (m_id) { - return osMutexAcquire(m_id, 0) == osOK; - } - return false; - } - - void unlock() { - if (m_id) osMutexRelease(m_id); - } - - CmsisRtos2Mutex(const CmsisRtos2Mutex&) = delete; - CmsisRtos2Mutex& operator=(const CmsisRtos2Mutex&) = delete; - - private: - osMutexId_t m_id = NULL; - }; - - // ========================================================================= - // CmsisRtos2RecursiveMutex (Recursive) - // ========================================================================= - class CmsisRtos2RecursiveMutex { - public: - CmsisRtos2RecursiveMutex() { - osMutexAttr_t attr = {0}; - attr.attr_bits = osMutexRecursive; - m_id = osMutexNew(&attr); - assert(m_id != NULL); - } - - ~CmsisRtos2RecursiveMutex() { - if (m_id) osMutexDelete(m_id); - } - - void lock() { - if (m_id) osMutexAcquire(m_id, osWaitForever); - } - - bool try_lock() { - if (m_id) { - return osMutexAcquire(m_id, 0) == osOK; - } - return false; - } - - void unlock() { - if (m_id) osMutexRelease(m_id); - } - - CmsisRtos2RecursiveMutex(const CmsisRtos2RecursiveMutex&) = delete; - CmsisRtos2RecursiveMutex& operator=(const CmsisRtos2RecursiveMutex&) = delete; - - private: - osMutexId_t m_id = NULL; - }; -} // namespace dmq::os - -#endif // CMSIS_RTOS2_MUTEX_H \ No newline at end of file diff --git a/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Semaphore.h b/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Semaphore.h deleted file mode 100644 index 689424c..0000000 --- a/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Semaphore.h +++ /dev/null @@ -1,82 +0,0 @@ -#ifndef CMSIS_RTOS2_SEMAPHORE_H -#define CMSIS_RTOS2_SEMAPHORE_H - -/// @file CmsisRtos2Semaphore.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief dmq::Semaphore backing for CMSIS-RTOS2, using osSemaphore -/// directly instead of the generic dmq::ConditionVariable + dmq::Mutex -/// implementation in delegate/Semaphore.h. -/// -/// @details -/// CMSIS-RTOS2 has no dmq::ConditionVariable port (no DMQ_HAS_CV) -- and no -/// native condition-variable primitive to build one from, unlike Zephyr's -/// k_condvar. It does have a native binary semaphore (osSemaphore), which -/// is a direct fit for what dmq::Semaphore actually needs: no need to build -/// one out of a mutex + condition variable when the RTOS already has a real -/// one. DelegateOpt.h resolves dmq::Semaphore to this type on CMSIS-RTOS2; -/// see the "Semaphore" comment next to DMQ_THREAD_CMSIS_RTOS2's -/// `using Semaphore = ...;` there. -/// -/// @note This header is included from DelegateOpt.h's early port-include -/// block, before "namespace dmq { ... }" opens and dmq::Duration is defined -/// inside it (including it any later would nest as dmq::dmq::os instead of -/// dmq::os) -- so, like the other CMSIS-RTOS2 port files, Wait() is -/// templated on the chrono duration type instead of depending on -/// dmq::Duration directly. A dmq::Duration argument still deduces through -/// it seamlessly at the call site, since dmq::Duration is itself a -/// std::chrono::duration specialization. -/// -/// @note osSemaphoreAcquire()'s timeout is in kernel ticks; Wait() converts -/// with CmsisRtos2ToTicks() (CmsisRtos2Ticks.h), so any tick rate works. - -#include "cmsis_os2.h" -#include "CmsisRtos2Ticks.h" -#include -#include - -namespace dmq::os { - - // ========================================================================= - // CmsisRtos2Semaphore - // Binary semaphore (max count 1), matching the semantics of the generic - // dmq::Semaphore this replaces: Signal() when already signaled is a - // no-op (not a counting semaphore), and Wait() consumes exactly one - // pending signal. - // ========================================================================= - class CmsisRtos2Semaphore { - public: - CmsisRtos2Semaphore() { - m_id = osSemaphoreNew(1, 0, nullptr); - assert(m_id != nullptr); - } - - ~CmsisRtos2Semaphore() { - if (m_id) osSemaphoreDelete(m_id); - } - - /// Called to wait on a semaphore to be signaled. - /// @param[in] timeout - semaphore timeout - /// @return Return true if semaphore signaled, false if timeout occurred. - template - bool Wait(const std::chrono::duration& timeout) { - if (!m_id) return false; - return osSemaphoreAcquire(m_id, CmsisRtos2ToTicks(timeout)) == osOK; - } - - /// Called to signal a semaphore. - void Signal() { - if (m_id) osSemaphoreRelease(m_id); - } - - CmsisRtos2Semaphore(const CmsisRtos2Semaphore&) = delete; - CmsisRtos2Semaphore& operator=(const CmsisRtos2Semaphore&) = delete; - - private: - osSemaphoreId_t m_id = nullptr; - }; - -} // namespace dmq::os - -#endif // CMSIS_RTOS2_SEMAPHORE_H diff --git a/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2ThisThread.h b/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2ThisThread.h deleted file mode 100644 index 398acb7..0000000 --- a/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2ThisThread.h +++ /dev/null @@ -1,49 +0,0 @@ -#ifndef CMSIS_RTOS2_THIS_THREAD_H -#define CMSIS_RTOS2_THIS_THREAD_H - -/// @file CmsisRtos2ThisThread.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief Portable sleep_for()/yield() for the calling thread, CMSIS-RTOS2 backend. -/// -/// @details -/// This is dmq::ThisThread for this port (see DelegateOpt.h). GetCurrent() -/// uses RegistryCurrentThread, keyed by the calling thread's id. Exists so -/// library internals that need to delay or yield (e.g. RetryMonitor backoff) -/// aren't forced to pull in the full dmq::os::Thread class -- which also -/// drags in the message queue, watchdog, and stats machinery -- just to -/// sleep. dmq::os::Thread::Sleep() forwards here too, so the CMSIS-RTOS2 -/// delay call is implemented exactly once. - -#include "cmsis_os2.h" -#include "CmsisRtos2Mutex.h" -#include "CmsisRtos2Ticks.h" -#include "port/os/common/CurrentThreadStorage.h" -#include - -namespace dmq::os { - - /// @brief Key for RegistryCurrentThread: the calling thread's id. - /// @TODO: Return 0 inside an ISR if your target can detect it (e.g. - /// __get_IPSR() != 0 on ARM Cortex-M). CMSIS-RTOS2 has no portable ISR check, - /// so dmq::ThisThread::GetCurrent() from an ISR returns the interrupted - /// thread's IThread instead of nullptr. See docs/PORTING.md, "Current Thread". - inline uintptr_t CmsisRtos2CurrentThreadKey() { - return reinterpret_cast(osThreadGetId()); - } - - struct CmsisRtos2ThisThread : RegistryCurrentThread { - template - static void sleep_for(std::chrono::duration d) { - osDelay(CmsisRtos2ToTicks(d)); // kernel ticks, rounded up - } - - static void yield() noexcept { - osThreadYield(); - } - }; - -} // namespace dmq::os - -#endif // CMSIS_RTOS2_THIS_THREAD_H diff --git a/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Thread.cpp b/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Thread.cpp deleted file mode 100644 index 89f7167..0000000 --- a/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Thread.cpp +++ /dev/null @@ -1,671 +0,0 @@ -// Compiles to nothing unless DMQ_THREAD_CMSIS_RTOS2 is selected, so every DelegateMQ source -// file can be added to a build (see src/DelegateMQ.cpp). -#include "delegate/DelegateSelect.h" -#if defined(DMQ_THREAD_CMSIS_RTOS2) - -#include "DelegateMQ.h" -#include "CmsisRtos2Thread.h" -#include "CmsisRtos2Ticks.h" -#include "port/os/common/ThreadMsg.h" -#include "port/os/common/ThreadHooks.h" -#include "extras/util/Fault.h" -#include -#include - -// Define DMQ_ASSERT_TRUE if not already defined -#ifndef DMQ_ASSERT_TRUE -#define DMQ_ASSERT_TRUE(x) if(!(x)) { while(1); } -#endif - -namespace dmq::os { - -using namespace dmq; -using namespace dmq::util; - -//---------------------------------------------------------------------------- -// Thread Constructor -//---------------------------------------------------------------------------- -CmsisRtos2Thread::CmsisRtos2Thread(const char* threadName, size_t maxQueueSize, FullPolicy fullPolicy, dmq::Duration dispatchTimeout, const char* cpuName) - : THREAD_NAME(threadName) - , CPU_NAME(cpuName) - , m_queueSize((maxQueueSize == 0) ? DEFAULT_QUEUE_SIZE : maxQueueSize) - , FULL_POLICY(fullPolicy) - , m_dispatchTimeout(dispatchTimeout) - , m_exit(false) -{ - // Default Priority - m_priority = osPriorityNormal; - -#if defined(DMQ_DATABUS_TOOLS) - m_statMutex = osMutexNew(NULL); -#endif -} - -//---------------------------------------------------------------------------- -// Thread Destructor -//---------------------------------------------------------------------------- -CmsisRtos2Thread::~CmsisRtos2Thread() -{ - ExitThread(); - - const dmq::LockGuard lock(GetWatchdogLock()); - CmsisRtos2Thread** pp = &GetWatchdogHead(); - while (*pp != nullptr) - { - if (*pp == this) - { - *pp = this->m_watchdogNext; - this->m_watchdogNext = nullptr; - break; - } - pp = &((*pp)->m_watchdogNext); - } - -#if defined(DMQ_DATABUS_TOOLS) - if (m_statMutex) { - osMutexDelete(m_statMutex); - m_statMutex = NULL; - } -#endif - - // Cleanup semaphore if it exists - if (m_exitSem) { - osSemaphoreDelete(m_exitSem); - m_exitSem = NULL; - } - - if (m_startSem) { - osSemaphoreDelete(m_startSem); - m_startSem = NULL; - } -} - -//---------------------------------------------------------------------------- -// CreateThread -//---------------------------------------------------------------------------- -bool CmsisRtos2Thread::CreateThread(std::optional watchdogTimeout) -{ - if (m_thread == NULL) - { - // Reset from a previous ExitThread(), so the thread can be created again - m_exit.store(false); - // Held from creation, so the watchdog never sees a gated thread as hung - // before it reaches the gate (e.g. created before the scheduler runs) - m_startGate.OnCreate(); - // Set before the thread exists: its loop reads the timeout before its - // first queue wait, and an idle thread waits forever with no timeout - m_lastAliveTime.store(Timer::GetNow()); - m_watchdogTimeout.store(watchdogTimeout.value_or(dmq::Duration(0))); - m_discard.store(false); - - // 1. Create Exit Semaphore (Max 1, Initial 0) - // We use this to wait for the thread to shut down gracefully. Created - // once and reused across ExitThread()/CreateThread() cycles (ExitThread() - // doesn't delete it; the destructor does), so a restart doesn't leak one. - if (m_exitSem == NULL) { - m_exitSem = osSemaphoreNew(1, 0, NULL); - DMQ_ASSERT_TRUE(m_exitSem != NULL); - } - - // 2. Create Message Queue - DMQ_ASSERT_TRUE(m_queue.Create(m_queueSize)); - - // 3. Create Thread - osThreadAttr_t attr = {0}; - attr.name = THREAD_NAME.c_str(); - attr.stack_size = STACK_SIZE; - attr.priority = m_priority; - - // If the kernel is running, CreateThread() waits for the start handler. - // Before osKernelStart() it cannot block; the start handler then runs - // when the kernel starts, still before any message is processed. - // - // Zephyr's CMSIS-RTOS2 compatibility layer (subsys/portability/cmsis_rtos_v2/) - // never implements osKernelGetState() -- calling it is a link error -- but on - // Zephyr the kernel is already scheduling before main() runs (there is no - // separate osKernelStart() call on this backend; see cmsis-rtos2-linux's - // main_delegate.cpp), so it would always report osKernelRunning anyway. - // __ZEPHYR__ is defined by Zephyr's own build system on every compile. -#if defined(__ZEPHYR__) - m_startSync = true; -#else - m_startSync = (osKernelGetState() == osKernelRunning); -#endif - if (m_startSync && m_startSem == NULL) { - m_startSem = osSemaphoreNew(1, 0, NULL); - DMQ_ASSERT_TRUE(m_startSem != NULL); - } - - m_thread = osThreadNew(CmsisRtos2Thread::Process, this, &attr); - DMQ_ASSERT_TRUE(m_thread != NULL); - - if (m_startSync) { - // m_thread is now stored: let Run() proceed to the start handler (see - // Run()), then wait for it to complete. - osThreadFlagsSet(m_thread, START_FLAG); - osSemaphoreAcquire(m_startSem, osWaitForever); - } - - m_lastAliveTime.store(Timer::GetNow()); - - if (watchdogTimeout.has_value()) - { - - const dmq::LockGuard lock(GetWatchdogLock()); - - // Add to watchdog registry if not already present - bool found = false; - CmsisRtos2Thread* p = GetWatchdogHead(); - while (p != nullptr) - { - if (p == this) - { - found = true; - break; - } - p = p->m_watchdogNext; - } - - if (!found) - { - m_watchdogNext = GetWatchdogHead(); - GetWatchdogHead() = this; - } - } - } - return true; -} - -//---------------------------------------------------------------------------- -// SetThreadPriority -//---------------------------------------------------------------------------- -void CmsisRtos2Thread::SetThreadPriority(osPriority_t priority) -{ - m_priority = priority; - - // If the thread is already running, update it live - if (m_thread != NULL) { - osThreadSetPriority(m_thread, m_priority); - } -} - -//---------------------------------------------------------------------------- -// GetThreadPriority -//---------------------------------------------------------------------------- -osPriority_t CmsisRtos2Thread::GetThreadPriority() -{ - return m_priority; -} - -//---------------------------------------------------------------------------- -// ExitThread -//---------------------------------------------------------------------------- -void CmsisRtos2Thread::ExitThread(ExitPolicy policy) -{ - if (m_queue.IsCreated()) - { - // Set before m_exit: Run() reads it for every message ahead of the exit message - m_discard.store(policy == ExitPolicy::DISCARD); - m_exit.store(true); - - // A thread held at its start gate isn't waiting on its queue: wake it so it - // sees the exit flag (set above) and leaves. Never touches the gate itself, - // which may be destroyed once the thread is released. - m_startGate.Wake(); - - // Check self-exit BEFORE attempting to enqueue the exit message. If - // this thread is destroying itself from within its own dispatched - // callback, it is not consuming its own queue right now -- it is - // blocked here, inside ExitThread(). A blocking osMessageQueuePut() - // would deadlock forever if the queue happened to be full. No message - // needs to be queued in that case: Run()'s dispatch loop already - // checks m_selfExitPtr immediately after the current callback invoke - // returns, and unwinds without touching 'this' again. - if (osThreadGetId() == m_thread) { - if (m_selfExitPtr) { *m_selfExitPtr = true; m_selfExitPtr = nullptr; } - m_startGate.Leave(); // exited from its start handler: never reaches the gate - } else { - // Send exit message - ThreadMsg* msg = new (std::nothrow) ThreadMsg(MSG_EXIT_THREAD); - if (msg) - { - // Send pointer, wait forever to ensure it gets in. - if (!m_queue.Send(msg, /*highPriority=*/false, osWaitForever)) - { - delete msg; // Failed to send - } - } - - // Wait for thread to process the exit message and signal completion. - if (m_exitSem != NULL) osSemaphoreAcquire(m_exitSem, osWaitForever); - } - - // Thread has finished Run(). Now we can safely clean up resources. - m_thread = NULL; - - // The thread has finished (or, on a self-exit, is in its last handler): - // stop watchdog checks. Not earlier, so a thread that hangs while - // ExitThread() waits for it is still reported. - m_watchdogTimeout.store(dmq::Duration(0)); - - m_queue.DrainAndDelete(); - m_queue.Destroy(); - } -} - -//---------------------------------------------------------------------------- -// GetThreadId -//---------------------------------------------------------------------------- -osThreadId_t CmsisRtos2Thread::GetThreadId() -{ - return m_thread; -} - -//---------------------------------------------------------------------------- -// GetCurrentThreadId -//---------------------------------------------------------------------------- -osThreadId_t CmsisRtos2Thread::GetCurrentThreadId() -{ - return osThreadGetId(); -} - -//---------------------------------------------------------------------------- -// IsCurrentThread -//---------------------------------------------------------------------------- -bool CmsisRtos2Thread::IsCurrentThread() -{ - return GetThreadId() == GetCurrentThreadId(); -} - -//---------------------------------------------------------------------------- -// GetQueueSize -//---------------------------------------------------------------------------- -size_t CmsisRtos2Thread::GetQueueSize() -{ - return m_queue.Size(); -} - -void CmsisRtos2Thread::Sleep(dmq::Duration timeout) { - dmq::ThisThread::sleep_for(timeout); -} - -//---------------------------------------------------------------------------- -// DispatchDelegate -//---------------------------------------------------------------------------- -bool CmsisRtos2Thread::DispatchDelegate(std::shared_ptr msg) -{ - DMQ_ASSERT_TRUE(m_queue.IsCreated()); - - // 1. Allocate message container - ThreadMsg* threadMsg = new (std::nothrow) ThreadMsg(MSG_DISPATCH_DELEGATE, msg); - if (!threadMsg) return false; -#if defined(DMQ_DATABUS_TOOLS) - threadMsg->SetEnqueueTime(Timer::GetNow()); -#endif - - // 2. Send pointer to queue - uint32_t timeout; - if (FULL_POLICY == FullPolicy::TIMEOUT) - timeout = CmsisRtos2ToTicks(m_dispatchTimeout); - else - timeout = 0; // DROP and FAULT: non-blocking - - // High priority goes to the queue's HIGH lane, drained first (see CmsisRtos2DelegateQueue). - bool sent = m_queue.Send(threadMsg, msg->GetPriority() == Priority::HIGH, timeout); - if (!sent) - { - if (FULL_POLICY == FullPolicy::FAULT) { - printf("[Thread] CRITICAL: Queue full on thread '%s'! TRIGGERING FAULT.\n", THREAD_NAME.c_str()); - DMQ_ASSERT_TRUE(sent); - } else if (FULL_POLICY == FullPolicy::TIMEOUT) { - printf("[Thread] WARNING: Queue post timed out on '%s' — possible deadlock. Message dropped.\n", THREAD_NAME.c_str()); - if (m_droppedHandler) - m_droppedHandler(GetQueueSize()); - } else { // DROP - if (m_droppedHandler) - m_droppedHandler(GetQueueSize()); - } - // Failed to send (queue full or timed out) - delete threadMsg; - return false; - } - -#if defined(DMQ_DATABUS_TOOLS) - // Update monitoring stats - osMutexAcquire(m_statMutex, osWaitForever); - size_t currentDepth = GetQueueSize(); - if (currentDepth > m_queueDepthMaxWindow) m_queueDepthMaxWindow = currentDepth; - if (currentDepth > m_queueDepthMaxAll) m_queueDepthMaxAll = currentDepth; - osMutexRelease(m_statMutex); -#endif - - return true; -} - -//---------------------------------------------------------------------------- -// Process (Static Entry Point) -//---------------------------------------------------------------------------- -void CmsisRtos2Thread::Process(void* argument) -{ - CmsisRtos2Thread* thread = static_cast(argument); - if (thread) - { - thread->Run(); - } - - // Thread terminates automatically when function returns. - osThreadExit(); -} - -//---------------------------------------------------------------------------- -// WatchdogCheck -//---------------------------------------------------------------------------- -void CmsisRtos2Thread::WatchdogCheck() -{ - if (m_startGate.IsHeld()) - return; // held at its start gate by design, not hung - - auto now = Timer::GetNow(); - auto lastAlive = m_lastAliveTime.load(); - auto watchdogTimeout = m_watchdogTimeout.load(); - - if (watchdogTimeout.count() > 0) - { - auto delta = now - lastAlive; - if (delta > watchdogTimeout) - { - WatchdogHandler(THREAD_NAME.c_str()); - } - } -} - -//---------------------------------------------------------------------------- -// ThreadCheck -//---------------------------------------------------------------------------- -void CmsisRtos2Thread::ThreadCheck() -{ - m_lastAliveTime.store(Timer::GetNow()); -} - -//---------------------------------------------------------------------------- -// WatchdogCheckAll -//---------------------------------------------------------------------------- -void CmsisRtos2Thread::WatchdogCheckAll() -{ - const dmq::LockGuard lock(GetWatchdogLock()); - CmsisRtos2Thread* p = GetWatchdogHead(); - while (p != nullptr) - { - p->WatchdogCheck(); - p = p->m_watchdogNext; - } -} - -//---------------------------------------------------------------------------- -// GetWatchdogHead -//---------------------------------------------------------------------------- -CmsisRtos2Thread*& CmsisRtos2Thread::GetWatchdogHead() -{ - static CmsisRtos2Thread* head = nullptr; - return head; -} - -//---------------------------------------------------------------------------- -// GetWatchdogLock -//---------------------------------------------------------------------------- -dmq::RecursiveMutex& CmsisRtos2Thread::GetWatchdogLock() -{ - static dmq::RecursiveMutex* lock = new dmq::RecursiveMutex(); - return *lock; -} - -void CmsisRtos2Thread::Run() -{ - bool selfExit = false; - m_selfExitPtr = &selfExit; - - // Exit and idle handlers are copied onto this stack frame so they work on - // every return path, including a self-exit where 'this' may already be freed. - ThreadExitGuard exitGuard(m_exitHandler); - ThreadIdleTimer idle(m_idleHandler, m_idleInterval); - - // osThreadNew() returns m_thread only after this thread may already be - // running; wait for CreateThread() so the start handler can use it. - const bool startSync = m_startSync; - if (startSync) - osThreadFlagsWait(START_FLAG, osFlagsWaitAny, osWaitForever); - - // dmq::ThisThread::GetCurrent() returns this thread from here on. Reset - // before the exit handler runs (and destroyed before exitGuard on a - // self-exit), so the exit handler sees nullptr. - std::optional currentScope; - currentScope.emplace(this); - - if (m_startHandler) - m_startHandler(); - - // A start handler that exited this thread (ExitThread() on itself) leaves - // right after the signal below: once CreateThread() returns, the Thread may - // be destroyed, so nothing after the signal may touch 'this'. - const bool exitedInStart = selfExit; - - if (startSync) - osSemaphoreRelease(m_startSem); - if (exitedInStart) - return; - - // Optional start gate: wait here, ready but processing nothing, until it opens - if (m_startGate.Enabled()) - { - const bool opened = m_startGate.Wait(m_exit); - m_lastAliveTime.store(Timer::GetNow()); // before Passed(): no stale watchdog read - m_startGate.Passed(); - // ExitThread() while held: run nothing. Cancel each queued message - // (DISCARD) until the exit message. Consuming them also keeps - // ExitThread()'s blocking send of the exit message from waiting on a - // full queue. - if (!opened) - m_discard.store(true); - } - - ThreadMsg* msg = nullptr; - - while (!selfExit) - { - dmq::Duration watchdogTimeout; - { - m_lastAliveTime.store(Timer::GetNow()); - watchdogTimeout = m_watchdogTimeout.load(); - } - - // If watchdog active, use a finite timeout so we can periodically update - // m_lastAliveTime while idle. If an idle handler is set, wake no later - // than when it is due. Otherwise, block forever to save power. - uint32_t waitOption = osWaitForever; - if (watchdogTimeout.count() > 0) - { - // Divide in microseconds so a 1-3 ms watchdog doesn't truncate to 0; - // CmsisRtos2ToTicks() rounds any nonzero wait up to at least 1 tick. - waitOption = CmsisRtos2ToTicks( - std::chrono::duration_cast(watchdogTimeout) / dmq::WATCHDOG_HEARTBEAT_DIVISOR); - } - if (idle.Enabled()) - { - uint32_t idleTicks = CmsisRtos2ToTicks(idle.WaitTime(dmq::Duration(-1))); - if (idleTicks < waitOption) waitOption = idleTicks; - } - - // Block for a message or timeout - msg = m_queue.Receive(waitOption); - if (msg == nullptr) - { - // Exit requested but no exit message arrived (e.g. it could not be allocated) - if (m_exit.load()) - break; - - // Timed out with the queue empty: run the idle handler if it is due - if (idle.IsDue()) - { - idle.Run(); - // The idle handler exited this thread (and may have deleted it): leave - // without touching 'this', as the message path does - if (selfExit) - return; - } - } - else - { - int msgId = msg->GetId(); - if (msgId == MSG_DISPATCH_DELEGATE && m_discard.load()) - { - // ExitPolicy::DISCARD: skip messages queued ahead of the exit message - CancelThreadMsg(*msg); - } - else if (msgId == MSG_DISPATCH_DELEGATE) - { - #if defined(DMQ_DATABUS_TOOLS) - // Update latency stats before invoking - dmq::Duration latency = Timer::GetNow() - msg->GetEnqueueTime(); - { - osMutexAcquire(m_statMutex, osWaitForever); - m_latencyTotalWindow += latency; - m_latencyCountWindow++; - if (latency > m_latencyMaxWindow) m_latencyMaxWindow = latency; - if (latency > m_latencyMaxAll) m_latencyMaxAll = latency; - m_dispatchCountAll++; - osMutexRelease(m_statMutex); - } - #endif - - auto delegateMsg = msg->GetData(); - DMQ_ASSERT_TRUE(delegateMsg); - auto invoker = delegateMsg->GetInvoker(); - DMQ_ASSERT_TRUE(invoker); - -#if defined(DMQ_DATABUS_TOOLS) - dmq::TimePoint start = Timer::GetNow(); -#endif -#if defined(__cpp_exceptions) && !defined(DMQ_ASSERTS) - bool success = false; - try { - success = invoker->Invoke(delegateMsg); - if (!selfExit) DMQ_ASSERT_TRUE(success); - } - catch (const std::bad_alloc& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled bad_alloc in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::invalid_argument& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled invalid_argument in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::runtime_error& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled runtime_error in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::exception& e) { - printf("[Thread:%s] Unhandled exception in delegate callback: %s\n", THREAD_NAME.c_str(), e.what()); - DMQ_ASSERT(); - } - catch (...) { - printf("[Thread:%s] Unhandled unknown exception in delegate callback.\n", THREAD_NAME.c_str()); - DMQ_ASSERT(); - } -#else - bool success = invoker->Invoke(delegateMsg); - if (!selfExit) DMQ_ASSERT_TRUE(success); -#endif - if (selfExit) { - delete msg; - return; - } - -#if defined(DMQ_DATABUS_TOOLS) - dmq::Duration invokeTime = Timer::GetNow() - start; - { - osMutexAcquire(m_statMutex, osWaitForever); - m_invokeTotalWindow += invokeTime; - m_invokeCountWindow++; - if (invokeTime > m_invokeMaxWindow) m_invokeMaxWindow = invokeTime; - if (invokeTime > m_invokeMaxAll) m_invokeMaxAll = invokeTime; - osMutexRelease(m_statMutex); - } -#endif - } - - delete msg; - - if (msgId == MSG_EXIT_THREAD) { - break; - } - - // Any message restarts the idle countdown - idle.Restart(); - } - } - - // Run the exit handler before signalling ExitThread(), so it returns only after it - currentScope.reset(); - exitGuard.Fire(); - - // Clear before signalling: once ExitThread() returns, 'this' may be destroyed - m_selfExitPtr = nullptr; - // Signal ExitThread() that we are done - if (m_exitSem) { - osSemaphoreRelease(m_exitSem); - } -} - -#if defined(DMQ_DATABUS_TOOLS) -//---------------------------------------------------------------------------- -// SnapshotStats -//---------------------------------------------------------------------------- -CmsisRtos2Thread::ThreadStats CmsisRtos2Thread::SnapshotStats() -{ - osMutexAcquire(m_statMutex, osWaitForever); - ThreadStats stats; - stats.cpu_name = CPU_NAME; - stats.thread_name = THREAD_NAME; - stats.queue_depth = GetQueueSize(); - stats.queue_depth_max_window = m_queueDepthMaxWindow; - stats.queue_depth_max_all = m_queueDepthMaxAll; - stats.queue_size_limit = m_queueSize; - - if (m_latencyCountWindow > 0) { - stats.latency_avg_ms = static_cast(std::chrono::duration_cast(m_latencyTotalWindow).count()) / (static_cast(m_latencyCountWindow) * 1000.0f); - } else { - stats.latency_avg_ms = 0.0f; - } - - stats.latency_max_window_ms = static_cast(std::chrono::duration_cast(m_latencyMaxWindow).count()) / 1000.0f; - stats.latency_max_all_ms = static_cast(std::chrono::duration_cast(m_latencyMaxAll).count()) / 1000.0f; - - if (m_invokeCountWindow > 0) { - stats.invoke_avg_ms = static_cast(std::chrono::duration_cast(m_invokeTotalWindow).count()) / (static_cast(m_invokeCountWindow) * 1000.0f); - } else { - stats.invoke_avg_ms = 0.0f; - } - - stats.invoke_max_window_ms = static_cast(std::chrono::duration_cast(m_invokeMaxWindow).count()) / 1000.0f; - stats.invoke_max_all_ms = static_cast(std::chrono::duration_cast(m_invokeMaxAll).count()) / 1000.0f; - - stats.dispatch_count = m_dispatchCountAll; - - // Reset windowed stats - m_queueDepthMaxWindow = 0; - m_latencyTotalWindow = Duration(0); - m_latencyCountWindow = 0; - m_latencyMaxWindow = Duration(0); - - m_invokeTotalWindow = Duration(0); - m_invokeCountWindow = 0; - m_invokeMaxWindow = Duration(0); - - osMutexRelease(m_statMutex); - return stats; -} -#endif - -} // namespace dmq::os - -#endif // DMQ_THREAD_CMSIS_RTOS2 diff --git a/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Thread.h b/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Thread.h deleted file mode 100644 index 8f98b3f..0000000 --- a/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Thread.h +++ /dev/null @@ -1,296 +0,0 @@ -#ifndef _THREAD_CMSIS_RTOS2_H -#define _THREAD_CMSIS_RTOS2_H - -/// @file CmsisRtos2Thread.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief CMSIS-RTOS2 implementation of the DelegateMQ IThread interface. -/// -/// @details -/// This class provides a concrete implementation of the `IThread` interface using -/// the CMSIS-RTOS2 standard API (`cmsis_os2.h`). It enables DelegateMQ to dispatch -/// asynchronous delegates to a dedicated thread on any CMSIS-compliant RTOS -/// (e.g., Keil RTX, FreeRTOS wrapped by CMSIS, Zephyr, etc.). -/// -/// @note This implementation is a basic port. For reference, the stdlib and win32 -/// implementations provide additional features: -/// 1. Synchronized Startup: CreateThread() blocks until the worker thread is ready. -/// -/// **Key Features:** -/// * **Task Integration:** Wraps `osThreadNew` to establish a dedicated worker loop. -/// * **FullPolicy Support:** Configurable back-pressure (DROP or TIMEOUT) when the -/// message queue is full. -/// * **Priority Support:** Normal and High priorities, as two queue lanes drained -/// HIGH first (see `CmsisRtos2DelegateQueue` for why `osMessageQueuePut`'s -/// `msg_prio` isn't relied on). -/// * **Queue-Based Dispatch:** Uses `CmsisRtos2DelegateQueue` (a thin RAII wrapper -/// around two `osMessageQueue` lanes and a counting `osSemaphore`) to receive -/// and process incoming delegate messages in a thread-safe manner. -/// * **Priority Control:** Supports runtime priority configuration via `SetThreadPriority` -/// using standard `osPriority_t` levels. -/// * **Graceful Shutdown:** Implements robust termination logic using semaphores to ensure -/// the thread exits cleanly before destruction. -/// * **Watchdog Integration:** Optional heartbeat mechanism detects stalled or deadlocked -/// threads. Enable by passing a timeout to CreateThread(). Requires -/// Thread::WatchdogCheckAll() to be called periodically from a context that can preempt -/// watched threads -- the highest-priority task in the system, not an ISR. -/// * **Start Gate:** Optional `SetStartGate(StartGate*)`, called before `CreateThread()`, -/// holds the thread ready but processing no messages, at any priority, until -/// `StartGate::Open()` releases every thread sharing the gate at once. - -#include "delegate/IThread.h" -#include "delegate/UnicastDelegate.h" -#include "extras/util/Timer.h" -#include "port/os/common/ThreadMsg.h" -#include "port/os/common/StartGate.h" -#include "CmsisRtos2DelegateQueue.h" -#include "cmsis_os2.h" -#include -#include -#include -#include - -namespace dmq::os { - -/// @brief Policy applied when the thread message queue is full. See dmq::FullPolicy -/// in DelegateOpt.h for the canonical definition, shared by every dmq::os::Thread port. -using FullPolicy = dmq::FullPolicy; - -/// @brief What ExitThread() does with queued messages. See dmq::ExitPolicy in DelegateOpt.h. -using ExitPolicy = dmq::ExitPolicy; - -class CmsisRtos2Thread : public dmq::IThread -{ -public: -#if defined(DMQ_DATABUS_TOOLS) - /// @brief Statistics captured for thread monitoring. - struct ThreadStats { - dmq::xstring cpu_name; - dmq::xstring thread_name; - size_t queue_depth; // Current depth - size_t queue_depth_max_window;// Max depth since last snapshot - size_t queue_depth_max_all; // All-time max depth - size_t queue_size_limit; // Max allowed - float latency_avg_ms; // Avg wait in window - float latency_max_window_ms; // Max wait since last snapshot - float latency_max_all_ms; // All-time max wait - float invoke_avg_ms; // Avg execution in window - float invoke_max_window_ms; // Max execution since last snapshot - float invoke_max_all_ms; // All-time max execution - uint64_t dispatch_count; // Total dispatches (all-time) - }; -#endif - - /// Default queue size if 0 is passed - static const uint32_t DEFAULT_QUEUE_SIZE = dmq::DEFAULT_QUEUE_SIZE; - - /// Constructor - /// @param threadName Name for the thread - /// @param maxQueueSize Max number of messages in queue (0 = Default dmq::DEFAULT_QUEUE_SIZE) - /// @param fullPolicy Action when queue is full: FAULT (default), DROP, or TIMEOUT. - /// @param dispatchTimeout Duration to wait before giving up when policy is TIMEOUT. - /// @param cpuName Optional CPU/Core name grouping for monitoring tools. - CmsisRtos2Thread(const char* threadName, size_t maxQueueSize = 0, FullPolicy fullPolicy = FullPolicy::FAULT, - dmq::Duration dispatchTimeout = dmq::DEFAULT_DISPATCH_TIMEOUT, const char* cpuName = ""); - - CmsisRtos2Thread(const std::string& threadName, size_t maxQueueSize = 0, FullPolicy fullPolicy = FullPolicy::FAULT, - dmq::Duration dispatchTimeout = dmq::DEFAULT_DISPATCH_TIMEOUT, const std::string& cpuName = "") - : CmsisRtos2Thread(threadName.c_str(), maxQueueSize, fullPolicy, dispatchTimeout, cpuName.c_str()) {} - - ~CmsisRtos2Thread(); - - /// Called once to create the worker thread. If watchdogTimeout value - /// provided, the maximum watchdog interval is used. Otherwise no watchdog. - /// @param[in] watchdogTimeout - optional watchdog timeout. - /// @return TRUE if thread is created. FALSE otherwise. - bool CreateThread(std::optional watchdogTimeout = std::nullopt); - - /// Shut down the worker thread. - /// @param[in] policy - DRAIN (default) invokes every message queued before this - /// call first; DISCARD invokes only the message already running and cancels - /// the rest (see dmq::ExitPolicy). Called from the thread's own message - /// handler (a self-exit), queued messages are always discarded. - void ExitThread(ExitPolicy policy = ExitPolicy::DRAIN); - - osThreadId_t GetThreadId(); - static osThreadId_t GetCurrentThreadId(); - - /// Returns true if the calling thread is this thread - virtual bool IsCurrentThread() override; - - /// Set the thread priority. - /// Can be called before or after CreateThread(). - void SetThreadPriority(osPriority_t priority); - - /// Get current priority - osPriority_t GetThreadPriority(); - - dmq::xstring GetThreadName() { return THREAD_NAME; } - - /// Get current queue size - size_t GetQueueSize(); - - /// Sleep for a duration. - /// @param[in] timeout - the duration to sleep. - static void Sleep(dmq::Duration timeout); - - virtual bool DispatchDelegate(std::shared_ptr msg) override; - - /// @brief Register a handler invoked when DispatchDelegate() drops a message: - /// under FullPolicy::DROP (queue full, discarded immediately) or - /// FullPolicy::TIMEOUT (queue stayed full for dispatchTimeout, discarded). - /// Optional; unset by default. Called synchronously on the calling (producer) - /// thread, with the queue depth at the time of the drop. - void SetDroppedHandler(const dmq::UnicastDelegate& handler) { m_droppedHandler = handler; } - void SetDroppedHandler(dmq::UnicastDelegate&& handler) { m_droppedHandler = std::move(handler); } - - /// @brief Register a handler invoked on the worker thread before it processes - /// any message. Use it for per-thread setup (COM, a language runtime attach, - /// thread-local state, affinity). CreateThread() returns only after it completes. - /// @details Must be called while the thread is not running (before CreateThread(), - /// or after ExitThread()); calling it on a running thread faults. It runs again - /// on each CreateThread(). Messages dispatched meanwhile are queued, not lost. - void SetStartHandler(const dmq::UnicastDelegate& handler) { DMQ_ASSERT_TRUE(m_thread == NULL); m_startHandler = handler; } - void SetStartHandler(dmq::UnicastDelegate&& handler) { DMQ_ASSERT_TRUE(m_thread == NULL); m_startHandler = std::move(handler); } - - /// @brief Optional: hold this thread at `gate` once it is created, until - /// `gate->Open()`. Pass nullptr (the default) to start at once. - /// @details CreateThread() still runs the start handler and returns when the - /// thread is ready; the thread then processes nothing, at any priority, until - /// the gate opens. Use one gate for a group of threads so they all start - /// together after setup. See port/os/common/StartGate.h. Must be called while - /// the thread is not running; calling it on a running thread faults. - void SetStartGate(StartGate* gate) { DMQ_ASSERT_TRUE(m_thread == NULL); m_startGate.Set(gate); } - - /// @brief Register a handler invoked on the worker thread after it processes - /// its last message, as the thread exits. Use it to undo SetStartHandler() setup. - /// @details Must be called while the thread is not running; calling it on a - /// running thread faults. The handler is copied when the thread starts. - /// ExitThread() from another thread returns after it completes. If the thread - /// exits itself (ExitThread() from a handler on this thread), it runs after the - /// owning CmsisRtos2Thread may already be destroyed, so it must not touch that object. - void SetExitHandler(const dmq::UnicastDelegate& handler) { DMQ_ASSERT_TRUE(m_thread == NULL); m_exitHandler = handler; } - void SetExitHandler(dmq::UnicastDelegate&& handler) { DMQ_ASSERT_TRUE(m_thread == NULL); m_exitHandler = std::move(handler); } - - /// @brief Register a handler invoked on the worker thread when its queue has - /// been empty for `interval`, then again every `interval` while it stays empty. - /// Any message processed restarts the countdown. Use it for background work that - /// should yield to messages: polling, housekeeping, entering low power. - /// @details Must be called while the thread is not running; calling it on a - /// running thread faults. The handler and interval are copied when the thread - /// starts. Not called once ExitThread() has been requested. - /// @param[in] handler - the idle handler, or an empty delegate to disable. - /// @param[in] interval - quiet time before each call. Must be greater than zero. - /// Defaults to dmq::THREAD_IDLE_INTERVAL (DMQ_THREAD_IDLE_INTERVAL). - void SetIdleHandler(const dmq::UnicastDelegate& handler, dmq::Duration interval = dmq::THREAD_IDLE_INTERVAL) - { - DMQ_ASSERT_TRUE(m_thread == NULL); - DMQ_ASSERT_TRUE(interval > dmq::Duration::zero()); - m_idleHandler = handler; - m_idleInterval = interval; - } - void SetIdleHandler(dmq::UnicastDelegate&& handler, dmq::Duration interval = dmq::THREAD_IDLE_INTERVAL) - { - DMQ_ASSERT_TRUE(m_thread == NULL); - DMQ_ASSERT_TRUE(interval > dmq::Duration::zero()); - m_idleHandler = std::move(handler); - m_idleInterval = interval; - } - - /// @brief Manually update the watchdog alive timestamp. - /// @details The Run() loop refreshes the timestamp automatically on every iteration. - /// Call this from inside long-running message handlers to prevent a false watchdog - /// alarm when a handler legitimately takes longer than watchdogTimeout. - void ThreadCheck(); - - /// @brief Static method to check all registered threads for watchdog expiration. - static void WatchdogCheckAll(); - -#if defined(DMQ_DATABUS_TOOLS) - /// @brief Capture and reset windowed statistics. - ThreadStats SnapshotStats(); -#endif - -private: - CmsisRtos2Thread(const CmsisRtos2Thread&) = delete; - CmsisRtos2Thread& operator=(const CmsisRtos2Thread&) = delete; - - // Entry point - static void Process(void* argument); - void Run(); - - /// Check watchdog is expired. Called by WatchdogCheckAll(). - void WatchdogCheck(); - - /// Get registry head using the "Immortal" Pattern - static CmsisRtos2Thread*& GetWatchdogHead(); - - /// Get registry lock using the "Immortal" Pattern - static dmq::RecursiveMutex& GetWatchdogLock(); - - const dmq::xstring THREAD_NAME; - const dmq::xstring CPU_NAME; - const size_t m_queueSize; - const FullPolicy FULL_POLICY; - const dmq::Duration m_dispatchTimeout; - osPriority_t m_priority; - - osThreadId_t m_thread = NULL; - CmsisRtos2DelegateQueue m_queue; - - // Optional handler invoked when a message is dropped (FullPolicy::DROP or TIMEOUT) - dmq::UnicastDelegate m_droppedHandler; - - // Optional handlers invoked on the worker thread at start, exit and when idle - dmq::UnicastDelegate m_startHandler; - dmq::UnicastDelegate m_exitHandler; - dmq::UnicastDelegate m_idleHandler; - dmq::Duration m_idleInterval = dmq::Duration::zero(); - osSemaphoreId_t m_exitSem = NULL; // Semaphore to signal thread completion - osSemaphoreId_t m_startSem = NULL; // Released by Run() once the start handler has run - bool m_startSync = false; // CreateThread() waits for the start handler (kernel running) - std::atomic m_exit = false; - - // Optional start gate (SetStartGate()): its state, and whether the thread is - // held at it (the watchdog doesn't report a thread waiting by design) - StartGateClient m_startGate; - std::atomic m_discard = false; // ExitPolicy::DISCARD: cancel queued messages instead of invoking - bool* m_selfExitPtr = nullptr; - - // Configurable sizes - static const uint32_t STACK_SIZE = static_cast(dmq::CMSIS_RTOS2_STACK_BYTES); // Bytes, DMQ_CMSIS_RTOS2_STACK_BYTES - static const uint32_t START_FLAG = 0x1U; // Thread flag: CreateThread() has stored m_thread - - // Watchdog related members - std::atomic m_lastAliveTime{dmq::TimePoint()}; - std::atomic m_watchdogTimeout{dmq::Duration(0)}; - CmsisRtos2Thread* m_watchdogNext = nullptr; - -#if defined(DMQ_DATABUS_TOOLS) - osMutexId_t m_statMutex = NULL; // Mutex to protect statistics - // Monitoring statistics members - size_t m_queueDepthMaxWindow = 0; - size_t m_queueDepthMaxAll = 0; - - dmq::Duration m_latencyTotalWindow = dmq::Duration(0); - uint32_t m_latencyCountWindow = 0; - dmq::Duration m_latencyMaxWindow = dmq::Duration(0); - dmq::Duration m_latencyMaxAll = dmq::Duration(0); - - dmq::Duration m_invokeTotalWindow = dmq::Duration(0); - uint32_t m_invokeCountWindow = 0; - dmq::Duration m_invokeMaxWindow = dmq::Duration(0); - dmq::Duration m_invokeMaxAll = dmq::Duration(0); - - uint64_t m_dispatchCountAll = 0; -#endif -}; - -/// @brief Backward-compatible name: existing code referencing dmq::os::Thread -/// keeps compiling unchanged against the CMSIS-RTOS2 port. -using Thread = CmsisRtos2Thread; - -} // namespace dmq::os - -#endif // _THREAD_CMSIS_RTOS2_H diff --git a/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Ticks.h b/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Ticks.h deleted file mode 100644 index acfae3a..0000000 --- a/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Ticks.h +++ /dev/null @@ -1,70 +0,0 @@ -#ifndef CMSIS_RTOS2_TICKS_H -#define CMSIS_RTOS2_TICKS_H - -/// @file CmsisRtos2Ticks.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief Converts between std::chrono durations and CMSIS-RTOS2 kernel ticks. -/// -/// @details -/// Every CMSIS-RTOS2 timeout (osSemaphoreAcquire, osMessageQueuePut/Get, -/// osDelay, ...) and osKernelGetTickCount() are in kernel ticks, and the tick -/// rate is whatever the kernel is configured for (osKernelGetTickFreq()), not -/// necessarily 1 kHz. Every place in this port that passes a timeout to the -/// kernel or reads the tick count goes through these helpers. -/// -/// Included from DelegateOpt.h's early port-include block (before namespace -/// dmq opens), so it doesn't use dmq::Duration; the helpers are templated on -/// the chrono duration type instead, like CmsisRtos2Semaphore::Wait(). - -#include "cmsis_os2.h" -#include -#include - -namespace dmq::os { - - /// @return the kernel tick rate in Hz (1000 if the kernel reports 0). - inline uint32_t CmsisRtos2TickFreq() noexcept { - uint32_t freq = osKernelGetTickFreq(); - return freq != 0 ? freq : 1000u; - } - - /// @brief Convert a duration to a CMSIS-RTOS2 timeout in kernel ticks. - /// @details Rounds up, so a nonzero timeout never becomes 0 (a non-blocking - /// call) and never waits less than asked. duration::max() maps to - /// osWaitForever; a zero or negative duration maps to 0. A finite timeout - /// too long for 32 bits saturates just below osWaitForever. - template - uint32_t CmsisRtos2ToTicks(const std::chrono::duration& d) noexcept { - using DurationT = std::chrono::duration; - if (d == DurationT::max()) - return osWaitForever; - if (d <= DurationT::zero()) - return 0; - constexpr uint64_t maxFinite = static_cast(osWaitForever) - 1u; - // Saturate before converting to microseconds, which would overflow - // int64 for a huge finite seconds/hours value. 2,000,000 hours is more - // than 2^32 ticks at any tick rate of 1 Hz or above. - if (d > std::chrono::hours(2000000)) - return static_cast(maxFinite); - const auto us = std::chrono::ceil(d).count(); - const uint64_t freq = CmsisRtos2TickFreq(); - if (static_cast(us) > (UINT64_MAX - 999999u) / freq) - return static_cast(maxFinite); - const uint64_t ticks = (static_cast(us) * freq + 999999u) / 1000000u; - return static_cast(ticks > maxFinite ? maxFinite : ticks); - } - - /// @brief Convert a kernel tick count to milliseconds. - inline uint64_t CmsisRtos2TicksToMs(uint64_t ticks) noexcept { - const uint64_t freq = CmsisRtos2TickFreq(); - if (freq == 1000u) - return ticks; - // Split to avoid overflowing ticks * 1000 on a long uptime. - return (ticks / freq) * 1000u + ((ticks % freq) * 1000u) / freq; - } - -} // namespace dmq::os - -#endif // CMSIS_RTOS2_TICKS_H diff --git a/DelegateMQ/port/os/common/CurrentThreadStorage.h b/DelegateMQ/port/os/common/CurrentThreadStorage.h deleted file mode 100644 index 7690224..0000000 --- a/DelegateMQ/port/os/common/CurrentThreadStorage.h +++ /dev/null @@ -1,169 +0,0 @@ -#ifndef _CURRENT_THREAD_STORAGE_H -#define _CURRENT_THREAD_STORAGE_H - -/// @file CurrentThreadStorage.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief Per-thread storage behind dmq::ThisThread::GetCurrent(). -/// -/// @details Each port's ThisThread struct (e.g. StdlibThisThread) derives from one -/// of these to supply GetCurrent(), which returns the dmq::IThread whose worker is -/// the calling thread. Values are written only by dmq::CurrentThreadScope (IThread.h), -/// which a worker loop creates on its own thread: -/// * ThreadLocalCurrentThread - C++ thread_local (desktop ports). -/// * RegistryCurrentThread - a fixed table keyed by the RTOS's native thread handle, -/// for RTOS ports, where C++ thread_local is not tied to the RTOS's task switching. -/// * NoCurrentThread - always nullptr (bare metal: no threads). -/// -/// Included from DelegateOpt.h (via each port's ThisThread header), after the -/// DelegateMQ config and Fault.h, which provide DMQ_MAX_CURRENT_THREADS and -/// DMQ_ASSERT_TRUE. - -#include -#include -#include - -namespace dmq { - class IThread; - class CurrentThreadScope; -} - -namespace dmq::os { - -/// @brief Current-thread storage using C++ thread_local, for ports whose threads -/// are native OS threads (stdlib, Win32, Qt, POSIX). -struct ThreadLocalCurrentThread -{ - /// @return the IThread whose worker is the calling thread, or nullptr. - static dmq::IThread* GetCurrent() noexcept { return Slot(); } - -private: - friend class dmq::CurrentThreadScope; - - static dmq::IThread* SetCurrent(dmq::IThread* thread) noexcept - { - dmq::IThread* prev = Slot(); - Slot() = thread; - return prev; - } - - static dmq::IThread*& Slot() noexcept - { - static thread_local dmq::IThread* current = nullptr; - return current; - } -}; - -/// @brief Current-thread storage for RTOS ports: a fixed table of (native thread -/// key, IThread*) slots, one per thread currently inside a CurrentThreadScope. -/// -/// @details GetCurrent() is lock-free: it scans for the calling thread's key, and -/// only that thread ever writes its own slot. SetCurrent() takes Lock only to claim -/// a free slot; it is called only from thread context (CurrentThreadScope), never -/// from an ISR. No heap and no RTOS configuration (task-local storage slots, -/// custom thread data) is required. -/// -/// @tparam GetKey Returns a nonzero key identifying the calling thread (typically -/// its native handle), or 0 when there is no calling thread (e.g. inside an ISR, -/// where the port can detect it); GetCurrent() then returns nullptr. -/// @tparam Lock The port's mutex type (lock()/unlock()). -/// @tparam Capacity Max threads registered at once. Exceeding it faults; raise -/// DMQ_MAX_CURRENT_THREADS (dmq::MAX_CURRENT_THREADS) for more threads. The macro -/// is used directly because this is instantiated before DelegateOpt.h defines -/// the dmq:: constant. -template -class RegistryCurrentThread -{ -public: - /// @return the IThread whose worker is the calling thread, or nullptr. - static dmq::IThread* GetCurrent() noexcept - { - const uintptr_t key = GetKey(); - if (key == 0) - return nullptr; - Slot* slot = Find(key); - return slot ? slot->thread : nullptr; - } - -private: - friend class dmq::CurrentThreadScope; - - struct Slot - { - std::atomic key{ 0 }; // 0 = free - dmq::IThread* thread = nullptr; // written only by the thread owning the key - }; - - static dmq::IThread* SetCurrent(dmq::IThread* thread) - { - const uintptr_t key = GetKey(); - DMQ_ASSERT_TRUE(key != 0); // A CurrentThreadScope needs a calling thread - - Slot* slot = Find(key); - dmq::IThread* prev = slot ? slot->thread : nullptr; - - if (slot) - { - slot->thread = thread; - if (thread == nullptr) - slot->key.store(0, std::memory_order_release); // Release the slot - return prev; - } - - if (thread == nullptr) - return prev; - - // Claim a free slot. Other threads may be claiming too; releases need no lock. - GetLock().lock(); - for (Slot& s : s_slots) - { - if (s.key.load(std::memory_order_acquire) == 0) - { - s.thread = thread; - s.key.store(key, std::memory_order_release); - GetLock().unlock(); - return prev; - } - } - GetLock().unlock(); - - // More threads registered at once than DMQ_MAX_CURRENT_THREADS - DMQ_ASSERT_TRUE(false); - return prev; - } - - static Slot* Find(uintptr_t key) noexcept - { - for (Slot& s : s_slots) - { - if (s.key.load(std::memory_order_acquire) == key) - return &s; - } - return nullptr; - } - - static Lock& GetLock() - { - static Lock lock; - return lock; - } - - static inline Slot s_slots[Capacity]; -}; - -/// @brief For ports without threads (bare metal): GetCurrent() always returns nullptr. -struct NoCurrentThread -{ - /// @return always nullptr. - static dmq::IThread* GetCurrent() noexcept { return nullptr; } - -private: - friend class dmq::CurrentThreadScope; - - static dmq::IThread* SetCurrent(dmq::IThread*) noexcept { return nullptr; } -}; - -} // namespace dmq::os - -#endif diff --git a/DelegateMQ/port/os/common/PortableScopedLock.h b/DelegateMQ/port/os/common/PortableScopedLock.h deleted file mode 100644 index 8593f93..0000000 --- a/DelegateMQ/port/os/common/PortableScopedLock.h +++ /dev/null @@ -1,61 +0,0 @@ -#ifndef _PORTABLE_SCOPED_LOCK_H -#define _PORTABLE_SCOPED_LOCK_H - -/// @file PortableScopedLock.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief Multi-mutex lock for toolchains without std::scoped_lock. -/// -/// @details Some bare-metal standard libraries, built without thread support -/// (e.g. Arm GNU Toolchain 14), provide but no std::scoped_lock. -/// DelegateOpt.h selects this class as dmq::ScopedLock on those toolchains only; -/// everywhere else dmq::ScopedLock is std::scoped_lock. -/// -/// Locks the mutexes in address order, so two locks over the same mutexes can't -/// deadlock, and unlocks in reverse order. A mutex passed twice is locked once. -/// All mutexes must be the same type (every DelegateMQ use is). - -#include -#include -#include - -namespace dmq::os { - -template -class PortableScopedLock { - static_assert((std::is_same_v && ...), - "PortableScopedLock: all mutexes must be the same type"); - static constexpr std::size_t N = 1 + sizeof...(Rest); - M* m_mutexes[N]; - - // A mutex passed twice sorts next to its duplicate. - bool IsDuplicate(std::size_t i) const noexcept { - return i > 0 && m_mutexes[i] == m_mutexes[i - 1]; - } - -public: - explicit PortableScopedLock(M& first, Rest&... rest) : m_mutexes{ &first, &rest... } { - for (std::size_t i = 1; i < N; i++) { // insertion sort by address - M* m = m_mutexes[i]; - std::size_t j = i; - for (; j > 0 && std::less()(m, m_mutexes[j - 1]); j--) - m_mutexes[j] = m_mutexes[j - 1]; - m_mutexes[j] = m; - } - for (std::size_t i = 0; i < N; i++) - if (!IsDuplicate(i)) m_mutexes[i]->lock(); - } - - ~PortableScopedLock() { - for (std::size_t i = N; i-- > 0;) - if (!IsDuplicate(i)) m_mutexes[i]->unlock(); - } - - PortableScopedLock(const PortableScopedLock&) = delete; - PortableScopedLock& operator=(const PortableScopedLock&) = delete; -}; - -} // namespace dmq::os - -#endif // _PORTABLE_SCOPED_LOCK_H diff --git a/DelegateMQ/port/os/common/StartGate.h b/DelegateMQ/port/os/common/StartGate.h deleted file mode 100644 index 561421c..0000000 --- a/DelegateMQ/port/os/common/StartGate.h +++ /dev/null @@ -1,311 +0,0 @@ -#ifndef _DMQ_START_GATE_H -#define _DMQ_START_GATE_H - -/// @file -/// @brief Optional start gate: hold any number of threads until one "go". -/// -/// @details A `dmq::os::Thread` given a gate with `SetStartGate()` is created -/// as usual: `CreateThread()` runs its start handler and returns once the -/// thread is ready, and other threads can dispatch to it. It then waits at the -/// gate and processes nothing, at any priority, until `Open()` is called. Every -/// thread holding at the gate is released at once. -/// -/// Typical startup: create every thread with the same gate, wire up -/// subscriptions and connections, then call `Open()`. No thread runs a -/// message while others are still being created or connected. -/// -/// @code -/// dmq::os::StartGate gate; -/// sensors.SetStartGate(&gate); // before CreateThread() -/// network.SetStartGate(&gate); -/// sensors.CreateThread(); // ready, holding at the gate -/// network.CreateThread(); -/// // ... subscribe, connect; dispatched messages wait in the queues ... -/// gate.Open(); // all gated threads start together -/// @endcode -/// -/// - A thread with no gate (the default) is unaffected. -/// - The start handler runs before the gate, during `CreateThread()`. Keep it -/// to local setup: other threads may not exist yet. -/// - `Open()` is permanent: a thread created (or re-created) after it passes -/// straight through. `Close()` makes the gate hold threads again. -/// - There is no timeout. A gate that is never opened holds its threads -/// until they are told to exit. -/// - `ExitThread()` on a held thread releases it without running any queued -/// message; those messages are canceled as for `ExitPolicy::DISCARD`. -/// - A held thread is not reported by the watchdog. Its watchdog starts when -/// the gate opens. -/// - Lifetime: the gate may be destroyed right after `Open()`, e.g. a local in -/// a startup function. Its destructor waits for every released thread to -/// leave the gate (they may not have run yet). Destroying it while a thread -/// is still held (not opened, not exited) faults. `CreateThread()` uses the -/// gate again, so call `SetStartGate(nullptr)` before re-creating a thread -/// whose gate is gone. On an RTOS, don't destroy it before the scheduler runs. -/// -/// Supported where `DMQ_HAS_START_GATE` is defined (delegate/DelegateSelect.h): -/// every thread port (not bare metal, which has no threads). - -#include "delegate/DelegateOpt.h" -#include "delegate/Semaphore.h" -#include -#include -#include - -#if defined(DMQ_HAS_START_GATE) && defined(DMQ_HAS_SEMAPHORE) - -namespace dmq::os { - -class StartGateClient; - -class StartGate -{ -public: - StartGate() = default; - - /// Waits for every released thread to leave the gate. Faults if a thread - /// is still held: it would wait forever. - ~StartGate() - { - for (;;) - { - { - dmq::LockGuard lock(m_mutex); - DMQ_ASSERT_TRUE(m_held == 0); // a thread still held would never leave - if (m_users == 0) - return; - m_destroying = true; - } - // Signaled under m_mutex by the last thread to leave; relocking - // above means that signal has completed before members go away - m_idle.Wait(dmq::Duration::max()); - } - } - - /// Release every thread created with this gate so far, whether it is - /// already waiting or still on its way to the gate. Threads created later - /// pass straight through until Close(). - void Open() - { - dmq::LockGuard lock(m_mutex); - m_open = true; - m_openCount++; - m_held = 0; - for (Waiter* w = m_waiters; w != nullptr; w = w->next) - w->sem->Signal(); - } - - /// Hold threads created from now on (to reuse the gate for another - /// startup). Threads released by an earlier Open() still start, even if - /// they haven't reached the gate or woken yet. - void Close() - { - dmq::LockGuard lock(m_mutex); - m_open = false; - } - - bool IsOpen() const - { - dmq::LockGuard lock(m_mutex); - return m_open; - } - - StartGate(const StartGate&) = delete; - StartGate& operator=(const StartGate&) = delete; - -private: - friend class StartGateClient; - - /// What a thread got from Attach(): the open count then, and whether the - /// gate was holding (it counts in m_held until released or detached). - struct Ticket - { - uint32_t openCount = 0; - bool held = false; - }; - - /// One per waiting thread, on that thread's stack; `sem` is the thread's - /// own (StartGateClient), so the gate allocates nothing. - struct Waiter - { - dmq::Semaphore* sem = nullptr; - Waiter* next = nullptr; - }; - - /// CreateThread(), before the thread starts: the gate is in use until the - /// thread Detach()es, so it can't be destroyed under it. - Ticket Attach() - { - dmq::LockGuard lock(m_mutex); - m_users++; - Ticket t; - t.openCount = m_openCount; - t.held = !m_open; - if (t.held) - m_held++; - return t; - } - - /// The thread is done with the gate (left Wait(), or was never started). - /// Last access to the gate by that thread. - void Detach(const Ticket& t) - { - dmq::LockGuard lock(m_mutex); - if (t.held && t.openCount == m_openCount) - m_held--; // not released by an Open(), so still counted - m_users--; - if (m_users == 0 && m_destroying) - m_idle.Signal(); - } - - /// Attached while open (passes through even if Close() came since), open - /// now, or opened since the ticket was taken. - bool Released(const Ticket& t) const - { - return !t.held || m_open || m_openCount != t.openCount; - } - - /// On the thread itself, after its start handshake and before its message - /// loop. Blocks until the gate opens (now or since Attach()) or `exit` is - /// set and `sem` signaled (StartGateClient::Wake()). Detaches before - /// returning, so the gate isn't touched afterwards. - /// @return true if the gate opened: the thread enters its loop, and an exit - /// requested meanwhile follows its ExitPolicy (DRAIN runs the queued - /// messages). false if the thread was told to exit while still held: it - /// runs nothing. - bool Wait(const std::atomic& exit, const Ticket& t, dmq::Semaphore& sem) - { - Waiter self; - self.sem = &sem; - bool opened; - bool waiting = false; // decided once, under the lock: on the list or not - { - dmq::LockGuard lock(m_mutex); - opened = Released(t); - if (!opened && !exit.load()) - { - self.next = m_waiters; - m_waiters = &self; - waiting = true; - } - } - - // Open() signals under m_mutex; ExitThread() signals `sem` directly - // after setting `exit`. A signal sent before this wait starts is kept - // by the semaphore, and a stale one only causes an extra check. - while (waiting) - { - sem.Wait(dmq::Duration::max()); - dmq::LockGuard lock(m_mutex); - if (exit.load() || Released(t)) - { - opened = Released(t); - Unlink(&self); - waiting = false; - } - } - - Detach(t); - return opened; - } - - void Unlink(Waiter* target) - { - for (Waiter** pp = &m_waiters; *pp != nullptr; pp = &(*pp)->next) - { - if (*pp == target) - { - *pp = target->next; - return; - } - } - } - - mutable dmq::Mutex m_mutex; - bool m_open = false; - uint32_t m_openCount = 0; // Open() calls; wraps harmlessly (only compared for change) - uint32_t m_users = 0; // threads attached and not yet detached - uint32_t m_held = 0; // of those, attached while closed and not released since - bool m_destroying = false; - Waiter* m_waiters = nullptr; - dmq::Semaphore m_idle; // ~StartGate() waits on it for m_users to reach 0 -}; - -/// A thread port's start gate state: one member per `dmq::os::Thread`, so -/// every port wires the gate the same way. -/// -/// Port calls: `Set()` from SetStartGate(); `OnCreate()` in CreateThread() -/// before the thread exists, and `OnCreateFailed()` if it then can't be -/// created; `Enabled()`/`Wait()`/`Passed()` on the thread before its loop; -/// `Wake()` in ExitThread() after setting the exit flag, and `Leave()` on its -/// self-exit path; `IsHeld()` in WatchdogCheck(). -class StartGateClient -{ -public: - void Set(StartGate* gate) { m_gate = gate; } - StartGate* Get() const { return m_gate; } - - void OnCreate() - { - m_held.store(m_gate != nullptr); - m_attached = false; - if (m_gate) - { - if (!m_wake) - m_wake.emplace(); // created here, not in the Thread constructor (RTOS heap) - m_ticket = m_gate->Attach(); - m_attached = true; - } - } - - void OnCreateFailed() { Leave(); } - - /// ExitThread() on a self-exit, from the thread itself: if it exited from - /// its start handler it never reaches Wait(), so detach here, while the - /// object is alive. No effect once the thread has passed the gate. - void Leave() - { - if (m_attached) - m_gate->Detach(m_ticket); - m_attached = false; - m_held.store(false); - } - - /// True if this thread must wait at a gate before its loop. - bool Enabled() const { return m_attached; } - - /// Thread side. Returns true if the gate opened; see StartGate::Wait(). - /// The gate is not touched after this returns. - bool Wait(const std::atomic& exit) - { - m_attached = false; - return m_gate->Wait(exit, m_ticket, *m_wake); - } - - /// Thread side, after Wait() and after refreshing the watchdog heartbeat: - /// no longer held. - void Passed() { m_held.store(false); } - - /// ExitThread(): wake this thread if it is waiting at its gate. Uses only - /// this object, never the gate, so a destroyed gate is never touched. - void Wake() - { - if (m_wake && m_held.load()) - m_wake->Signal(); - } - - /// Held at the gate: the watchdog skips the thread. - bool IsHeld() const { return m_held.load(); } - -private: - StartGate* m_gate = nullptr; - std::atomic m_held{false}; - bool m_attached = false; - StartGate::Ticket m_ticket; - std::optional m_wake; -}; - -} // namespace dmq::os - -#endif // DMQ_HAS_START_GATE && DMQ_HAS_SEMAPHORE - -#endif // _DMQ_START_GATE_H diff --git a/DelegateMQ/port/os/common/ThreadHooks.h b/DelegateMQ/port/os/common/ThreadHooks.h deleted file mode 100644 index eb23582..0000000 --- a/DelegateMQ/port/os/common/ThreadHooks.h +++ /dev/null @@ -1,109 +0,0 @@ -#ifndef _THREAD_HOOKS_H -#define _THREAD_HOOKS_H - -/// @file ThreadHooks.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// @brief Start, exit and idle handler support shared by the dmq::os::Thread ports. -/// -/// @details Each port exposes SetStartHandler()/SetExitHandler()/SetIdleHandler() -/// and calls these helpers from its worker loop, so the handler semantics stay the -/// same on every port: -/// * The start handler runs on the worker thread before any message, and -/// CreateThread() returns only after it completes. -/// * The exit handler runs on the worker thread after the last message, on every -/// loop return path (ThreadExitGuard). -/// * The idle handler runs on the worker thread once its queue has been empty for -/// the idle interval, then every interval while it stays empty; any processed -/// message restarts the countdown (ThreadIdleTimer). -/// -/// Both helpers take a copy of the handler when the loop starts, so they can run -/// after the owning Thread object has been destroyed (a thread that exits itself). - -#include "delegate/DelegateOpt.h" -#include "delegate/UnicastDelegate.h" - -namespace dmq::os { - -/// @brief Runs a thread's exit handler when the worker loop's stack frame unwinds. -/// Declare it at the top of the loop function, before any return. -class ThreadExitGuard -{ -public: - explicit ThreadExitGuard(const dmq::UnicastDelegate& handler) : m_handler(handler) {} - ~ThreadExitGuard() { Fire(); } - - /// @brief Run the exit handler now rather than at scope exit, e.g. before the - /// loop signals ExitThread() that it has finished. Runs it at most once. - void Fire() - { - if (!m_fired && m_handler) - m_handler(); - m_fired = true; - } - -private: - ThreadExitGuard(const ThreadExitGuard&) = delete; - ThreadExitGuard& operator=(const ThreadExitGuard&) = delete; - - dmq::UnicastDelegate m_handler; - bool m_fired = false; -}; - -/// @brief Tracks when a worker loop's idle handler is next due. -/// @details Usage per loop iteration: bound the queue wait with WaitTime(); if the -/// wait ends with the queue empty and IsDue(), call Run(); after processing a -/// message, call Restart(). All methods are no-ops when no handler is set. -class ThreadIdleTimer -{ -public: - ThreadIdleTimer(const dmq::UnicastDelegate& handler, dmq::Duration interval) - : m_handler(handler), m_interval(interval), m_due(dmq::Clock::now() + interval) {} - - /// @return true if an idle handler is set. - bool Enabled() const { return static_cast(m_handler); } - - /// @brief Bound a queue wait so the loop wakes when the idle handler is due. - /// @param[in] wait - the loop's own wait bound (e.g. the watchdog heartbeat), - /// or a negative duration to mean "wait forever". - /// @return the shorter of `wait` and the time until the idle handler is due - /// (never negative when the idle handler is enabled); `wait` unchanged otherwise. - dmq::Duration WaitTime(dmq::Duration wait) const - { - if (!Enabled()) - return wait; - dmq::Duration untilIdle = m_due - dmq::Clock::now(); - if (untilIdle < dmq::Duration::zero()) - untilIdle = dmq::Duration::zero(); - if (wait < dmq::Duration::zero() || untilIdle < wait) - return untilIdle; - return wait; - } - - /// @return true if the idle handler is set and its interval has elapsed. - bool IsDue() const { return Enabled() && dmq::Clock::now() >= m_due; } - - /// @brief Restart the countdown. Call after processing each message. - void Restart() - { - if (Enabled()) - m_due = dmq::Clock::now() + m_interval; - } - - /// @brief Invoke the idle handler and restart the countdown. - void Run() - { - m_handler(); - Restart(); - } - -private: - const dmq::UnicastDelegate m_handler; - const dmq::Duration m_interval; - dmq::TimePoint m_due; -}; - -} // namespace dmq::os - -#endif diff --git a/DelegateMQ/port/os/common/ThreadMsg.h b/DelegateMQ/port/os/common/ThreadMsg.h deleted file mode 100644 index 6b06e4b..0000000 --- a/DelegateMQ/port/os/common/ThreadMsg.h +++ /dev/null @@ -1,83 +0,0 @@ -#ifndef DMQ_OS_COMMON_THREAD_MSG_H -#define DMQ_OS_COMMON_THREAD_MSG_H - -/// @file ThreadMsg.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief A class to hold a platform-specific thread message that will be passed -/// through a dmq::os::Thread port's OS message queue. -/// -/// @details -/// Identical across every dmq::os::Thread port (FreeRTOS, ThreadX, Zephyr, -/// CMSIS-RTOS2, stdlib, Win32) except Qt, which dispatches via Qt's own -/// signal/slot queued-connection mechanism instead of a ThreadMsg wrapper -- -/// kept as a single shared file here instead of one copy per port directory. - -#include "delegate/DelegateOpt.h" -#include - -namespace dmq::os { - -// Message IDs -#define MSG_DISPATCH_DELEGATE 1 -#define MSG_EXIT_THREAD 2 - -class ThreadMsg -{ -public: - /// Constructor - /// @param[in] id - a unique identifier for the thread message - /// @param[in] data - a pointer to the message data to be typecast - /// by the receiving task based on the id value. - ThreadMsg(int id, std::shared_ptr data = nullptr) - : m_id(id), m_data(data) { - } - - virtual ~ThreadMsg() = default; - - int GetId() const { return m_id; } - std::shared_ptr GetData() const { return m_data; } - - /// Get the message priority - dmq::Priority GetPriority() const { - return m_data ? m_data->GetPriority() : dmq::Priority::NORMAL; - } - -#if defined(DMQ_DATABUS_TOOLS) - void SetEnqueueTime(dmq::TimePoint time) { m_enqueueTime = time; } - dmq::TimePoint GetEnqueueTime() const { return m_enqueueTime; } -#endif - -private: - int m_id; - std::shared_ptr m_data; -#if defined(DMQ_DATABUS_TOOLS) - dmq::TimePoint m_enqueueTime; -#endif - - // Use fixed-block memory allocator if DMQ_ALLOCATOR set - XALLOCATOR -}; - -/// @brief Discard a queued message without invoking it: a sender blocked waiting -/// on it is released and sees the call fail (DelegateMsg::Cancel()). Used for -/// dmq::ExitPolicy::DISCARD and for messages still queued when a thread exits. -inline void CancelThreadMsg(const ThreadMsg& msg) -{ - if (auto delegateMsg = msg.GetData()) - delegateMsg->Cancel(); -} - -/// @brief CancelThreadMsg() every message in a queue of std::shared_ptr, then clear it. -template -void CancelAll(Queue& queue) -{ - for (auto& msg : queue) - CancelThreadMsg(*msg); - queue.clear(); -} - -} // namespace dmq::os - -#endif // DMQ_OS_COMMON_THREAD_MSG_H diff --git a/DelegateMQ/port/os/freertos/FreeRTOSClock.h b/DelegateMQ/port/os/freertos/FreeRTOSClock.h deleted file mode 100644 index f2e63de..0000000 --- a/DelegateMQ/port/os/freertos/FreeRTOSClock.h +++ /dev/null @@ -1,69 +0,0 @@ -#ifndef FREERTOS_CLOCK_H -#define FREERTOS_CLOCK_H - -#include "FreeRTOS.h" -#include "task.h" -#include "FreeRTOSCriticalSection.h" -#include - -namespace dmq::os { - struct FreeRTOSClock { - // 1. Define duration traits. - // NOTE: This assumes configTICK_RATE_HZ is 1000 (1ms ticks). - // If your system uses a different tick rate, change std::milli to std::ratio<1, configTICK_RATE_HZ>. - using rep = int64_t; - using period = std::milli; - using duration = std::chrono::duration; - using time_point = std::chrono::time_point; - static const bool is_steady = true; - - // 2. The critical "now()" function - static time_point now() noexcept { - // Static state to track the tick rollover. - // 1. It must be called at least once per rollover period to detect the wrap. - // 2. Thread/ISR safety: protected by the critical section below. - static TickType_t last = 0; - static uint64_t high = 0; - - // Timer::ProcessTimers() calls this through Timer::GetNow(), and on a - // real Cortex-M target ProcessTimers() may run in a hardware ISR (see - // CLAUDE.md "ISR-Safe Locking"). taskENTER_CRITICAL() and - // xTaskGetTickCount() are task-only, so use FreeRTOSCriticalSection - // (which picks taskENTER_CRITICAL[_FROM_ISR] by context) and the - // matching tick-count call. Nesting inside Timer's own - // FreeRTOSCriticalSection is safe: each instance saves and restores - // its own state, released in LIFO order. - const bool inIsr = detail::IsInsideFreeRTOSInterrupt() != pdFALSE; - FreeRTOSCriticalSection cs; - cs.lock(); - - TickType_t cur = inIsr ? xTaskGetTickCountFromISR() : xTaskGetTickCount(); - - // If TickType_t is 64-bit, we don't need the rollover logic as it essentially never wraps. - // This also prevents a compilation error (shift count >= width of type). - if (sizeof(TickType_t) < 8) { - // Determine the rollover modulus based on the width of TickType_t. - // This makes the logic portable for both 16-bit and 32-bit FreeRTOS ticks. - // Note: Use a ternary to ensure we never shift by 64 even during constexpr evaluation. - constexpr uint32_t SHIFT_AMT = (sizeof(TickType_t) < 8) ? (sizeof(TickType_t) * 8) : 0; - constexpr uint64_t TICK_MODULO = static_cast(1ULL) << SHIFT_AMT; - - // Check for wrap-around - if (cur < last) { - high += TICK_MODULO; - } - } - - last = cur; - - // Combine high part with current tick - uint64_t ticks = high + cur; - - cs.unlock(); - - return time_point(duration(static_cast(ticks))); - } - }; -} // namespace dmq::os - -#endif // FREERTOS_CLOCK_H \ No newline at end of file diff --git a/DelegateMQ/port/os/freertos/FreeRTOSConditionVariable.h b/DelegateMQ/port/os/freertos/FreeRTOSConditionVariable.h deleted file mode 100644 index 4a4bcde..0000000 --- a/DelegateMQ/port/os/freertos/FreeRTOSConditionVariable.h +++ /dev/null @@ -1,136 +0,0 @@ -#ifndef FREERTOS_CONDITION_VARIABLE_H -#define FREERTOS_CONDITION_VARIABLE_H - -#include "FreeRTOS.h" -#include "semphr.h" -#include "task.h" -#include - -namespace dmq::os { - /// @brief Production-grade wrapper around FreeRTOS Semaphore to mimic std::condition_variable - /// @details - /// - Uses a Binary Semaphore (1 token). - /// - ISR-safe notification logic. - /// - Robust tick overflow handling using elapsed time subtraction. - /// - /// @note Limitation: Unlike std::cv, a binary semaphore retains its signal state. - /// If notify() occurs before wait(), the wait will effectively "fall through". - /// Multiple notifies before a wait are coalesced into a single signal. - class FreeRTOSConditionVariable - { - public: - FreeRTOSConditionVariable() - { - // Binary semaphore is sufficient for signaling state changes - m_sem = xSemaphoreCreateBinary(); - - // Critical check: Ensure heap was sufficient - configASSERT(m_sem != NULL); - } - - ~FreeRTOSConditionVariable() - { - if (m_sem) { - vSemaphoreDelete(m_sem); - } - } - - FreeRTOSConditionVariable(const FreeRTOSConditionVariable&) = delete; - FreeRTOSConditionVariable& operator=(const FreeRTOSConditionVariable&) = delete; - - /// @brief Wake up one waiting thread (ISR Safe) - void notify_one() noexcept - { - if (!m_sem) return; - -#if defined(_WIN32) || defined(WIN32) || defined(__linux__) - // Simulator Ports (Windows/Linux): - // "Interrupts" are simulated. The hardware ISR check - // often does not exist. Standard API is safe here. - xSemaphoreGive(m_sem); -#else - // Embedded (e.g., ARM Cortex-M): - // Must check if running in ISR context to use FromISR API. - if (xPortIsInsideInterrupt()) - { - BaseType_t xHigherPriorityTaskWoken = pdFALSE; - xSemaphoreGiveFromISR(m_sem, &xHigherPriorityTaskWoken); - portYIELD_FROM_ISR(xHigherPriorityTaskWoken); - } - else - { - xSemaphoreGive(m_sem); - } -#endif - } - - /// @brief Wait indefinitely until predicate is true - template - void wait(Lock& lock, Predicate pred) - { - while (!pred()) - { - if (lock.owns_lock()) - lock.unlock(); - - // Wait indefinitely - BaseType_t ret = xSemaphoreTake(m_sem, portMAX_DELAY); - configASSERT(ret == pdTRUE); - - if (!lock.owns_lock()) - lock.lock(); - } - } - - /// @brief Wait until predicate is true or timeout expires - /// @details Uses overflow-safe subtraction logic to track elapsed ticks. - template - bool wait_for(Lock& lock, std::chrono::milliseconds timeout, Predicate pred) - { - const TickType_t timeoutTicks = pdMS_TO_TICKS(timeout.count()); - const TickType_t start = xTaskGetTickCount(); - - while (!pred()) - { - TickType_t now = xTaskGetTickCount(); - - // Overflow-safe elapsed time calculation - TickType_t elapsed = now - start; - - if (elapsed >= timeoutTicks) - { - if (!lock.owns_lock()) - lock.lock(); - return pred(); // Timeout expired, check predicate one last time - } - - TickType_t remaining = timeoutTicks - elapsed; - - if (lock.owns_lock()) - lock.unlock(); - - // Wait for the semaphore or timeout - BaseType_t res = xSemaphoreTake(m_sem, remaining); - - if (!lock.owns_lock()) - lock.lock(); - - if (res == pdFALSE) - { - // Semaphore timeout occurred - return pred(); - } - - // If success (res == pdTRUE), loop around and check pred() again. - // If pred() is still false, it was a spurious wakeup or coalesced signal. - } - - return true; - } - - private: - SemaphoreHandle_t m_sem = NULL; - }; -} // namespace dmq::os - -#endif // FREERTOS_CONDITION_VARIABLE_H \ No newline at end of file diff --git a/DelegateMQ/port/os/freertos/FreeRTOSCriticalSection.h b/DelegateMQ/port/os/freertos/FreeRTOSCriticalSection.h deleted file mode 100644 index 4421bd8..0000000 --- a/DelegateMQ/port/os/freertos/FreeRTOSCriticalSection.h +++ /dev/null @@ -1,122 +0,0 @@ -#ifndef FREERTOS_CRITICAL_SECTION_H -#define FREERTOS_CRITICAL_SECTION_H - -/// @file FreeRTOSCriticalSection.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief ISR-safe critical section for FreeRTOS. -/// -/// @details -/// Unlike ThreadX/Zephyr/CMSIS-RTOS2, FreeRTOS has no single primitive that -/// is safe to call from BOTH thread and ISR context: it splits critical -/// sections into two separate APIs -- taskENTER_CRITICAL()/EXIT() for task -/// context, taskENTER_CRITICAL_FROM_ISR()/EXIT_FROM_ISR() for ISR context -- -/// and expects the caller to already know which one applies. Calling the -/// wrong one for the current context is undefined behavior. -/// -/// This type resolves that at runtime via xPortIsInsideInterrupt(), so -/// lock()/unlock() work correctly from either context without the caller -/// needing to know which one it's in -- exactly the contract -/// dmq::util::Timer::GetLock() needs, since Timer::ProcessTimers() is -/// documented as callable from the highest-priority context available. -/// -/// xPortIsInsideInterrupt() is provided by every real ARM Cortex-M FreeRTOS -/// port this project supports (ARM_CM3, CM4F, CM7, CM23, CM33, CM55 -- -/// e.g. the stm32-freertos sample), detected via reading the ARM Cortex-M -/// core register whose value is meaningless outside a real Cortex-M CPU. -/// The desktop simulator ports (POSIX, Win32 -- used by freertos-linux, -/// freertos-bare-metal, databus-freertos) do not provide it: they run as -/// an ordinary host-OS thread with no real hardware interrupt to detect, -/// so "always task context" is the correct (and only meaningful) answer -/// there. dmq::os::detail::IsInsideFreeRTOSInterrupt() below selects -/// between the two at compile time via the __arm__/__ARM_ARCH compiler -/// predefines (set by arm-none-eabi-gcc, never set when GCC/Clang builds -/// the desktop simulators for x86_64) -- no new DMQ_* build option needed, -/// and no risk of colliding with FreeRTOS's own xPortIsInsideInterrupt() -/// symbol, since we never redefine it under that name ourselves. -/// -/// @note Scoping assumption: this assumes ARM Cortex-M is the embedded -/// target, true for every FreeRTOS port this project currently supports. -/// A RISC-V or Xtensa FreeRTOS port would need the detection below -/// extended for its own architecture predefines. -/// -/// *** NARROW PURPOSE -- DO NOT USE THIS AS A GENERAL-PURPOSE LOCK *** -/// On the ISR path this masks interrupts up to configMAX_SYSCALL_INTERRUPT_PRIORITY -/// for as long as it is held; on the task path it disables the scheduler -/// and masks interrupts the same way. Only use it to protect something -/// genuinely tiny and bounded that may be touched from ISR context. Do NOT -/// use it in place of dmq::Mutex / dmq::RecursiveMutex for ordinary -/// thread-to-thread synchronization (e.g. DataBus internals, a Thread's -/// message queue) -- anything that can block, take a while, or run for an -/// unbounded time must not run with interrupts globally masked; that is a -/// real-time correctness bug on hardware, not just a style issue. -/// -/// *** NOT RE-LOCKABLE ON THE SAME INSTANCE *** -/// Unlike dmq::RecursiveMutex, calling lock() twice on the SAME instance -/// without an intervening unlock() is incorrect: the second lock() call -/// overwrites the single saved-interrupt-state member with the (already -/// masked) inner state, so the outer unlock() restores the wrong state. -/// There is no "recursive" variant of this type -- it has no ownership -/// concept to make recursion meaningful, and Timer's own usage never -/// nests. Locking two DIFFERENT instances in proper LIFO lock/unlock -/// order is fine: each instance saves and restores its own state -/// independently. - -#include "FreeRTOS.h" -#include "task.h" - -namespace dmq::os { - - namespace detail { -#if defined(__arm__) || defined(__ARM_ARCH) - // Real ARM Cortex-M FreeRTOS port -- it provides - // xPortIsInsideInterrupt() itself; call the real thing. - inline BaseType_t IsInsideFreeRTOSInterrupt() { return xPortIsInsideInterrupt(); } -#else - // Desktop simulator port (POSIX/Win32) -- no real hardware - // interrupt to detect; always task context. - inline BaseType_t IsInsideFreeRTOSInterrupt() { return pdFALSE; } -#endif - } // namespace detail - - // ========================================================================= - // FreeRTOSCriticalSection - // See the file-level comment above before using this type anywhere new. - // ========================================================================= - class FreeRTOSCriticalSection { - public: - FreeRTOSCriticalSection() = default; - - void lock() { - if (detail::IsInsideFreeRTOSInterrupt() != pdFALSE) { - m_savedInterruptStatus = taskENTER_CRITICAL_FROM_ISR(); - m_lockedFromIsr = true; - } else { - taskENTER_CRITICAL(); - m_lockedFromIsr = false; - } - } - - void unlock() { - if (m_lockedFromIsr) { - taskEXIT_CRITICAL_FROM_ISR(m_savedInterruptStatus); - } else { - taskEXIT_CRITICAL(); - } - } - - // No try_lock(): interrupt masking cannot fail to "acquire", so a - // try_lock() here would always trivially succeed and isn't meaningful. - - FreeRTOSCriticalSection(const FreeRTOSCriticalSection&) = delete; - FreeRTOSCriticalSection& operator=(const FreeRTOSCriticalSection&) = delete; - - private: - UBaseType_t m_savedInterruptStatus = 0; - bool m_lockedFromIsr = false; - }; - -} // namespace dmq::os - -#endif // FREERTOS_CRITICAL_SECTION_H diff --git a/DelegateMQ/port/os/freertos/FreeRTOSDelegateQueue.h b/DelegateMQ/port/os/freertos/FreeRTOSDelegateQueue.h deleted file mode 100644 index ee28e75..0000000 --- a/DelegateMQ/port/os/freertos/FreeRTOSDelegateQueue.h +++ /dev/null @@ -1,191 +0,0 @@ -#ifndef FREERTOS_DELEGATE_QUEUE_H -#define FREERTOS_DELEGATE_QUEUE_H - -/// @file FreeRTOSDelegateQueue.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief Thin RAII wrapper around a pair of FreeRTOS xQueue primitives used -/// by dmq::os::Thread to carry pending ThreadMsg pointers, with priority -/// support. See the Priority enum in delegate/DelegateMsg.h for the -/// cross-port ordering contract this class must uphold. -/// -/// @details -/// *** DO NOT "SIMPLIFY" THIS BACK TO ONE QUEUE + xQueueSendToFront() *** -/// An earlier version of this class used a single xQueue and called -/// xQueueSendToFront() for HIGH priority messages. That is WRONG: sending to -/// the front of a single queue makes HIGH messages a LIFO stack relative to -/// each other, not a FIFO lane. Concretely, starting from [Normal1]: -/// 1. HIGH-A sent to front -> [HIGH-A, Normal1] -/// 2. HIGH-B sent to front -> [HIGH-B, HIGH-A, Normal1] -/// The consumer then dequeues HIGH-B before HIGH-A, even though A arrived -/// first -- exactly backwards. See DelegateMsg.h's Priority comment for the -/// required contract (HIGH jumps ahead of NORMAL, but FIFO is preserved -/// within each priority). -/// -/// The fix: two independent xQueue instances, one per priority lane, each -/// always pushed to the BACK (xQueueSendToBack, never xQueueSendToFront). -/// FreeRTOS gives no way to block on "either of two queues has data" the way -/// a std::condition_variable can wait on an arbitrary predicate, so a -/// counting semaphore is used as a shared "doorbell": every successful Send() -/// (to either lane) gives the semaphore once; Receive() takes the semaphore -/// (the single blocking wait) and then does a non-blocking pop, checking the -/// HIGH lane first so it still drains ahead of NORMAL. This mirrors -/// StdlibThread's two-std::deque + one-condition_variable design and -/// ZephyrDelegateQueue's two-k_msgq + k_poll design -- same shape, RTOS-native -/// primitives. -/// -/// Each lane is sized to the full requested 'capacity' (like -/// ZephyrDelegateQueue), so worst-case combined depth is 2x capacity rather -/// than exactly capacity -- this doubles queue memory relative to the old -/// single-queue design. The semaphore's max count is sized to match (2x -/// capacity) so a Send() that already found room in its lane can never fail -/// to give the semaphore. -/// -/// Isolates the native xQueueCreate/xQueueSendToBack/xQueueReceive/ -/// vQueueDelete/xSemaphoreCreateCounting calls behind a small type so -/// Thread.cpp's DispatchDelegate()/Run() read as policy and dispatch logic, -/// not FreeRTOS API plumbing. This class owns no policy decisions of its own -/// (FullPolicy, timeout computation, and stats stay in Thread.cpp) -- it only -/// knows how to move ThreadMsg* pointers through two fixed-capacity FreeRTOS -/// queues in priority order. -/// -/// @note Requires configUSE_COUNTING_SEMAPHORES == 1 in the application's -/// FreeRTOSConfig.h (needed for xSemaphoreCreateCounting). - -#include "FreeRTOS.h" -#include "task.h" -#include "queue.h" -#include "semphr.h" -#include "port/os/common/ThreadMsg.h" - -namespace dmq::os { - -class FreeRTOSDelegateQueue -{ -public: - FreeRTOSDelegateQueue() = default; - ~FreeRTOSDelegateQueue() { Destroy(); } - - FreeRTOSDelegateQueue(const FreeRTOSDelegateQueue&) = delete; - FreeRTOSDelegateQueue& operator=(const FreeRTOSDelegateQueue&) = delete; - - /// Create the underlying HIGH and NORMAL queues, each with room for - /// 'capacity' pointers, plus the counting semaphore doorbell (max count - /// 2 * capacity, matching the combined capacity of both lanes). - /// @return true on success, false if any FreeRTOS object could not be - /// created (OOM). - bool Create(size_t capacity) - { - if (m_highQueue && m_normalQueue && m_countSem) - return true; - - if (!m_highQueue) - m_highQueue = xQueueCreate(static_cast(capacity), sizeof(ThreadMsg*)); - if (!m_normalQueue) - m_normalQueue = xQueueCreate(static_cast(capacity), sizeof(ThreadMsg*)); - if (!m_countSem) - m_countSem = xSemaphoreCreateCounting(static_cast(capacity * 2), 0); - - if (!m_highQueue || !m_normalQueue || !m_countSem) { - Destroy(); - return false; - } - return true; - } - - bool IsCreated() const { return m_highQueue != nullptr && m_normalQueue != nullptr && m_countSem != nullptr; } - - /// Send a message pointer. 'highPriority' routes to the HIGH lane, which - /// Receive() always drains first; otherwise the NORMAL lane. Both lanes - /// are always pushed to the BACK -- see the file-level comment for why - /// "send to front" must never be reintroduced here. 'waitTicks' is 0 for - /// non-blocking, portMAX_DELAY to block forever, or a finite tick count - /// for a bounded wait; it applies only to the queue push (each lane has - /// its own independent capacity -- there is no combined-depth wait across - /// both). Giving the doorbell semaphore never blocks and cannot fail: its - /// max count (2 * capacity) matches the combined lane capacity, so a - /// Send() that already found room in its lane always has room in the - /// semaphore's count too. - /// @return true if the message was enqueued. - bool Send(ThreadMsg* msg, bool highPriority, TickType_t waitTicks) - { - QueueHandle_t q = highPriority ? m_highQueue : m_normalQueue; - if (xQueueSendToBack(q, &msg, waitTicks) != pdPASS) - return false; - xSemaphoreGive(m_countSem); - return true; - } - - /// Receive a message pointer, blocking up to 'waitTicks'. The HIGH lane - /// is always checked -- and drained -- first, so a pending HIGH message - /// is returned even if NORMAL messages arrived earlier. Blocks on the - /// doorbell semaphore (the single native wait), then does a - /// non-blocking pop from whichever lane has data; the semaphore count - /// guarantees at least one lane is non-empty once the take succeeds. - /// @return the message, or nullptr on timeout. - ThreadMsg* Receive(TickType_t waitTicks) - { - if (xSemaphoreTake(m_countSem, waitTicks) != pdPASS) - return nullptr; // timed out waiting for either lane - - ThreadMsg* msg = nullptr; - if (xQueueReceive(m_highQueue, &msg, 0) == pdPASS) - return msg; - if (xQueueReceive(m_normalQueue, &msg, 0) == pdPASS) - return msg; - return nullptr; - } - - /// Combined number of messages waiting across both lanes. - size_t Size() const - { - if (!m_highQueue || !m_normalQueue) - return 0; - return static_cast(uxQueueMessagesWaiting(m_highQueue)) - + static_cast(uxQueueMessagesWaiting(m_normalQueue)); - } - - /// Remove and delete every pending message in both lanes without - /// blocking. Used during shutdown once the owning thread has stopped - /// consuming the queues. - /// Each message is canceled first (CancelThreadMsg()), releasing a sender - /// blocked waiting on it. - void DrainAndDelete() - { - ThreadMsg* msg = nullptr; - while (xQueueReceive(m_highQueue, &msg, 0) == pdPASS) { - CancelThreadMsg(*msg); // Release a sender blocked on it - delete msg; - } - while (xQueueReceive(m_normalQueue, &msg, 0) == pdPASS) { - CancelThreadMsg(*msg); // Release a sender blocked on it - delete msg; - } - } - - void Destroy() - { - if (m_highQueue) { - vQueueDelete(m_highQueue); - m_highQueue = nullptr; - } - if (m_normalQueue) { - vQueueDelete(m_normalQueue); - m_normalQueue = nullptr; - } - if (m_countSem) { - vSemaphoreDelete(m_countSem); - m_countSem = nullptr; - } - } - -private: - QueueHandle_t m_highQueue = nullptr; - QueueHandle_t m_normalQueue = nullptr; - SemaphoreHandle_t m_countSem = nullptr; -}; - -} // namespace dmq::os - -#endif // FREERTOS_DELEGATE_QUEUE_H diff --git a/DelegateMQ/port/os/freertos/FreeRTOSMutex.h b/DelegateMQ/port/os/freertos/FreeRTOSMutex.h deleted file mode 100644 index a7c90d3..0000000 --- a/DelegateMQ/port/os/freertos/FreeRTOSMutex.h +++ /dev/null @@ -1,103 +0,0 @@ -#ifndef FREERTOS_MUTEX_H -#define FREERTOS_MUTEX_H - -#include "FreeRTOS.h" -#include "semphr.h" - -namespace dmq::os { - - // ========================================================================= - // FreeRTOSMutex (Non-Recursive) - // Matches std::mutex behavior - // ========================================================================= - class FreeRTOSMutex { - public: - FreeRTOSMutex() { - m_handle = xSemaphoreCreateMutex(); - configASSERT(m_handle); - } - - ~FreeRTOSMutex() { - if (m_handle) { - vSemaphoreDelete(m_handle); - } - } - - void lock() { - if (m_handle) { - BaseType_t ret = xSemaphoreTake(m_handle, portMAX_DELAY); - configASSERT(ret == pdTRUE); - } - } - - bool try_lock() { - if (m_handle) { - // Wait time of 0 ticks = non-blocking attempt - return xSemaphoreTake(m_handle, 0) == pdTRUE; - } - return false; - } - - void unlock() { - if (m_handle) { - xSemaphoreGive(m_handle); - } - } - - FreeRTOSMutex(const FreeRTOSMutex&) = delete; - FreeRTOSMutex& operator=(const FreeRTOSMutex&) = delete; - - private: - SemaphoreHandle_t m_handle = nullptr; - }; - - // ========================================================================= - // FreeRTOSRecursiveMutex (Recursive) - // Matches std::recursive_mutex behavior - // ========================================================================= - class FreeRTOSRecursiveMutex { - public: - FreeRTOSRecursiveMutex() { - // Requires configUSE_RECURSIVE_MUTEXES == 1 in FreeRTOSConfig.h - m_handle = xSemaphoreCreateRecursiveMutex(); - configASSERT(m_handle); - } - - ~FreeRTOSRecursiveMutex() { - if (m_handle) { - vSemaphoreDelete(m_handle); - } - } - - void lock() { - if (m_handle) { - BaseType_t ret = xSemaphoreTakeRecursive(m_handle, portMAX_DELAY); - configASSERT(ret == pdTRUE); - } - } - - // Added try_lock (Required by std::unique_lock) - bool try_lock() { - if (m_handle) { - // Wait time of 0 ticks = non-blocking attempt - return xSemaphoreTakeRecursive(m_handle, 0) == pdTRUE; - } - return false; - } - - void unlock() { - if (m_handle) { - xSemaphoreGiveRecursive(m_handle); - } - } - - FreeRTOSRecursiveMutex(const FreeRTOSRecursiveMutex&) = delete; - FreeRTOSRecursiveMutex& operator=(const FreeRTOSRecursiveMutex&) = delete; - - private: - SemaphoreHandle_t m_handle = nullptr; - }; - -} // namespace dmq::os - -#endif // FREERTOS_MUTEX_H \ No newline at end of file diff --git a/DelegateMQ/port/os/freertos/FreeRTOSThisThread.h b/DelegateMQ/port/os/freertos/FreeRTOSThisThread.h deleted file mode 100644 index 1dffb88..0000000 --- a/DelegateMQ/port/os/freertos/FreeRTOSThisThread.h +++ /dev/null @@ -1,54 +0,0 @@ -#ifndef FREERTOS_THIS_THREAD_H -#define FREERTOS_THIS_THREAD_H - -/// @file FreeRTOSThisThread.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief Portable sleep_for()/yield() for the calling thread, FreeRTOS backend. -/// -/// @details -/// This is dmq::ThisThread for this port (see DelegateOpt.h). GetCurrent() -/// uses RegistryCurrentThread, keyed by the calling task's handle. Exists so -/// library internals that need to delay or yield (e.g. RetryMonitor backoff) -/// aren't forced to pull in the full dmq::os::Thread class -- which also -/// drags in the message queue, watchdog, and stats machinery -- just to -/// sleep. dmq::os::Thread::Sleep() forwards here too, so the FreeRTOS delay -/// call is implemented exactly once. - -#include "FreeRTOS.h" -#include "task.h" -#include "FreeRTOSMutex.h" -#include "FreeRTOSCriticalSection.h" -#include "port/os/common/CurrentThreadStorage.h" -#include - -namespace dmq::os { - - /// @brief Key for RegistryCurrentThread: the calling task's handle, or 0 - /// inside an ISR (detected on ARM Cortex-M; see FreeRTOSCriticalSection.h). - /// @TODO: On a non-ARM FreeRTOS port (RISC-V, Xtensa, ...), extend - /// detail::IsInsideFreeRTOSInterrupt() for that architecture; until then, - /// dmq::ThisThread::GetCurrent() from an ISR returns the interrupted task's - /// IThread instead of nullptr. See docs/PORTING.md, "Current Thread". - inline uintptr_t FreeRTOSCurrentThreadKey() { - if (detail::IsInsideFreeRTOSInterrupt()) - return 0; - return reinterpret_cast(xTaskGetCurrentTaskHandle()); - } - - struct FreeRTOSThisThread : RegistryCurrentThread { - template - static void sleep_for(std::chrono::duration d) { - const auto ms = std::chrono::duration_cast(d); - vTaskDelay(pdMS_TO_TICKS(ms.count())); - } - - static void yield() noexcept { - taskYIELD(); - } - }; - -} // namespace dmq::os - -#endif // FREERTOS_THIS_THREAD_H diff --git a/DelegateMQ/port/os/freertos/FreeRTOSThread.cpp b/DelegateMQ/port/os/freertos/FreeRTOSThread.cpp deleted file mode 100644 index 54dc503..0000000 --- a/DelegateMQ/port/os/freertos/FreeRTOSThread.cpp +++ /dev/null @@ -1,652 +0,0 @@ -// Compiles to nothing unless DMQ_THREAD_FREERTOS is selected, so every DelegateMQ source -// file can be added to a build (see src/DelegateMQ.cpp). -#include "delegate/DelegateSelect.h" -#if defined(DMQ_THREAD_FREERTOS) - -#include "DelegateMQ.h" -#include "FreeRTOSThread.h" -#include "port/os/common/ThreadMsg.h" -#include "port/os/common/ThreadHooks.h" -#include "extras/util/Fault.h" -#include - -#ifndef DMQ_ASSERT_TRUE -#define DMQ_ASSERT_TRUE(x) configASSERT(x) -#endif - -namespace dmq::os { - -using namespace dmq; -using namespace dmq::util; - -//---------------------------------------------------------------------------- -// Thread Constructor -//---------------------------------------------------------------------------- -FreeRTOSThread::FreeRTOSThread(const char* threadName, size_t maxQueueSize, FullPolicy fullPolicy, dmq::Duration dispatchTimeout, const char* cpuName) - : THREAD_NAME(threadName) - , CPU_NAME(cpuName) - , FULL_POLICY(fullPolicy) - , m_dispatchTimeout(dispatchTimeout) - , m_exit(false) -{ - m_queueSize = (maxQueueSize == 0) ? DEFAULT_QUEUE_SIZE : maxQueueSize; -#if defined(_MSC_VER) -#pragma warning(push) -#pragma warning(disable: 6326) -#endif - m_priority = configMAX_PRIORITIES > 2 ? configMAX_PRIORITIES - 2 : tskIDLE_PRIORITY + 1; -#if defined(_MSC_VER) -#pragma warning(pop) -#endif -} - -//---------------------------------------------------------------------------- -// Destructor -//---------------------------------------------------------------------------- -FreeRTOSThread::~FreeRTOSThread() -{ - ExitThread(); - - { - const dmq::LockGuard lock(GetWatchdogLock()); - FreeRTOSThread** pp = &GetWatchdogHead(); - while (*pp != nullptr) - { - if (*pp == this) - { - *pp = this->m_watchdogNext; - this->m_watchdogNext = nullptr; - break; - } - pp = &((*pp)->m_watchdogNext); - } - } - - if (m_exitSem) { - vSemaphoreDelete(m_exitSem); - m_exitSem = nullptr; - } - - if (m_startSem) { - vSemaphoreDelete(m_startSem); - m_startSem = nullptr; - } -} - -//---------------------------------------------------------------------------- -// SetStackMem (Static Stack Configuration) -//---------------------------------------------------------------------------- -void FreeRTOSThread::SetStackMem(StackType_t* stackBuffer, uint32_t stackSizeInWords) -{ - if (stackBuffer && stackSizeInWords > 0) { - m_stackBuffer = stackBuffer; - m_stackSize = stackSizeInWords; - } -} - -//---------------------------------------------------------------------------- -// CreateThread -//---------------------------------------------------------------------------- -bool FreeRTOSThread::CreateThread(std::optional watchdogTimeout) -{ - if (IsThreadCreated()) - return true; - - // Reset from a previous ExitThread(), so the thread can be created again - m_exit.store(false); - // Held from creation, so the watchdog never sees a gated thread as hung - // before it reaches the gate (e.g. created before the scheduler runs) - m_startGate.OnCreate(); - // No watchdog unless one is given below; set before the task exists - m_watchdogTimeout.store(0); - m_discard.store(false); - - // 1. Create Synchronization Semaphore (Critical for cleanup) - if (!m_exitSem) { - m_exitSem = xSemaphoreCreateBinary(); - DMQ_ASSERT_TRUE(m_exitSem != nullptr); - } - - // 2. Create the Queue NOW (Synchronously) - // We must do this BEFORE creating the task so it's ready for immediate use. - if (!m_queue.IsCreated()) { - if (!m_queue.Create(m_queueSize)) { - printf("Error: Thread '%s' failed to create queue.\n", THREAD_NAME.c_str()); - m_startGate.OnCreateFailed(); - return false; - } - } - - m_lastAliveTime.store(static_cast(Timer::GetNow().time_since_epoch().count())); - - if (watchdogTimeout.has_value()) - { - m_watchdogTimeout.store(static_cast(watchdogTimeout.value().count())); - - const dmq::LockGuard lock(GetWatchdogLock()); - - // Add to watchdog registry if not already present - bool found = false; - FreeRTOSThread* p = GetWatchdogHead(); - while (p != nullptr) - { - if (p == this) - { - found = true; - break; - } - p = p->m_watchdogNext; - } - - if (!found) - { - m_watchdogNext = GetWatchdogHead(); - GetWatchdogHead() = this; - } - } - - // If the scheduler is running, CreateThread() waits for the start handler. - // Before vTaskStartScheduler() it cannot block; the start handler then runs - // when the scheduler starts, still before any message is processed. - m_startSync = (xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED); - if (m_startSync && !m_startSem) { - m_startSem = xSemaphoreCreateBinary(); - DMQ_ASSERT_TRUE(m_startSem != nullptr); - } - - // 3. Create Task - if (m_stackBuffer != nullptr) - { - // --- STATIC ALLOCATION --- - m_thread = xTaskCreateStatic( - (TaskFunction_t)&FreeRTOSThread::Process, - THREAD_NAME.c_str(), - m_stackSize, - this, - m_priority, - m_stackBuffer, - &m_tcb - ); - } - else - { - // --- DYNAMIC ALLOCATION (Heap) --- - // m_stackSize is the DMQ_FREERTOS_STACK_WORDS default here: SetStackMem() - // changes it only together with a static buffer (the branch above). - BaseType_t xReturn = xTaskCreate( - (TaskFunction_t)&FreeRTOSThread::Process, - THREAD_NAME.c_str(), - m_stackSize, - this, - m_priority, - &m_thread); - - if (xReturn != pdPASS) { - printf("Error: Failed to create task '%s'. OOM?\n", THREAD_NAME.c_str()); - m_watchdogTimeout.store(0); // no task to refresh the heartbeat - m_startGate.OnCreateFailed(); - return false; - } - } - - DMQ_ASSERT_TRUE(m_thread != nullptr); - - if (m_startSync) { - // m_thread is now stored: let Run() proceed to the start handler (see Run()), - // then wait for it to complete. - xTaskNotifyGive(m_thread); - xSemaphoreTake(m_startSem, portMAX_DELAY); - } - return true; -} - -//---------------------------------------------------------------------------- -// ExitThread -//---------------------------------------------------------------------------- -void FreeRTOSThread::ExitThread(ExitPolicy policy) -{ - if (m_queue.IsCreated()) { - // Set before m_exit: Run() reads it for every message ahead of the exit message - m_discard.store(policy == ExitPolicy::DISCARD); - m_exit.store(true); - - // A thread held at its start gate isn't waiting on its queue: wake it so it - // sees the exit flag (set above) and leaves. Never touches the gate itself, - // which may be destroyed once the thread is released. - m_startGate.Wake(); - - // Check self-exit BEFORE attempting to enqueue the exit message. If - // this thread is destroying itself from within its own dispatched - // callback, it is not consuming its own queue right now -- it is - // blocked here, inside ExitThread(). A blocking Send() would - // deadlock forever if the queue happened to be full. No message needs - // to be queued in that case: Run()'s dispatch loop already checks - // m_selfExitPtr immediately after the current callback invoke - // returns, and unwinds without touching 'this' again. - if (xTaskGetCurrentTaskHandle() == m_thread) { - if (m_selfExitPtr) { *m_selfExitPtr = true; m_selfExitPtr = nullptr; } - m_startGate.Leave(); // exited from its start handler: never reaches the gate - } else { - ThreadMsg* msg = new (std::nothrow) ThreadMsg(MSG_EXIT_THREAD); - - if (msg) { - // Block until message is sent. This ensures the thread WILL receive it. - // If the thread is deadlocked, we hang here, which is better than - // hanging at the semaphore after dropping the message. - if (!m_queue.Send(msg, /*highPriority=*/false, portMAX_DELAY)) { - delete msg; - } - } - - if (m_exitSem) { - xSemaphoreTake(m_exitSem, portMAX_DELAY); - } - } - - // The thread has finished (or, on a self-exit, is in its last handler): - // stop watchdog checks. Not earlier, so a thread that hangs while - // ExitThread() waits for it is still reported. - m_watchdogTimeout.store(0); - - m_queue.DrainAndDelete(); - m_queue.Destroy(); - m_thread = nullptr; - } -} - -//---------------------------------------------------------------------------- -// Getters / Setters -//---------------------------------------------------------------------------- -TaskHandle_t FreeRTOSThread::GetThreadId() { return m_thread; } -TaskHandle_t FreeRTOSThread::GetCurrentThreadId() { return xTaskGetCurrentTaskHandle(); } -bool FreeRTOSThread::IsCurrentThread() -{ - return GetThreadId() == GetCurrentThreadId(); -} - -//---------------------------------------------------------------------------- -// GetQueueSize -//---------------------------------------------------------------------------- -size_t FreeRTOSThread::GetQueueSize() -{ - return m_queue.Size(); -} - -void FreeRTOSThread::Sleep(dmq::Duration timeout) { - dmq::ThisThread::sleep_for(timeout); -} - -void FreeRTOSThread::SetThreadPriority(int priority) { - m_priority = priority; - if (m_thread) { - vTaskPrioritySet(m_thread, static_cast(m_priority)); - } -} - -//---------------------------------------------------------------------------- -// DispatchDelegate -//---------------------------------------------------------------------------- -bool FreeRTOSThread::DispatchDelegate(std::shared_ptr msg) -{ - if (!m_queue.IsCreated()) { - printf("[Thread] Error: Dispatch called but queue is null (%s)\n", THREAD_NAME.c_str()); - return false; - } - - // If using XALLOCATOR explicit operator new required. See xallocator.h. - ThreadMsg* threadMsg = new (std::nothrow) ThreadMsg(MSG_DISPATCH_DELEGATE, msg); - - if (threadMsg == nullptr) { - printf("[Thread] CRITICAL: 'new ThreadMsg' returned NULL! System Heap full? (%s)\n", THREAD_NAME.c_str()); - return false; - } -#if defined(DMQ_DATABUS_TOOLS) - threadMsg->SetEnqueueTime(Timer::GetNow()); -#endif - - // Compute send timeout based on policy. - TickType_t timeout; - if (FULL_POLICY == FullPolicy::TIMEOUT) - timeout = pdMS_TO_TICKS(std::chrono::duration_cast(m_dispatchTimeout).count()); - else - timeout = 0; // DROP and FAULT: non-blocking - - // High priority routes to the HIGH lane (drained before NORMAL), preserving - // FIFO order within each lane -- see FreeRTOSDelegateQueue.h for why this is - // NOT xQueueSendToFront (that would make HIGH messages LIFO, not FIFO). - bool sent = m_queue.Send(threadMsg, msg->GetPriority() == Priority::HIGH, timeout); - - if (!sent) { - if (FULL_POLICY == FullPolicy::FAULT) { - printf("[Thread] CRITICAL: Queue full on thread '%s'! TRIGGERING FAULT.\n", THREAD_NAME.c_str()); - DMQ_ASSERT_TRUE(sent); - } else if (FULL_POLICY == FullPolicy::TIMEOUT) { - printf("[Thread] WARNING: Queue post timed out on '%s' — possible deadlock. Message dropped.\n", THREAD_NAME.c_str()); - if (m_droppedHandler) - m_droppedHandler(GetQueueSize()); - } else { // DROP - if (m_droppedHandler) - m_droppedHandler(GetQueueSize()); - } - delete threadMsg; - return false; - } - -#if defined(DMQ_DATABUS_TOOLS) - // Update monitoring stats - size_t currentDepth = GetQueueSize(); - size_t oldDepth = m_queueDepthMaxWindow.load(); - while (currentDepth > oldDepth && !m_queueDepthMaxWindow.compare_exchange_weak(oldDepth, currentDepth)); - - oldDepth = m_queueDepthMaxAll.load(); - while (currentDepth > oldDepth && !m_queueDepthMaxAll.compare_exchange_weak(oldDepth, currentDepth)); -#endif - - return true; -} - -//---------------------------------------------------------------------------- -// Process & Run -//---------------------------------------------------------------------------- -void FreeRTOSThread::Process(void* instance) -{ - FreeRTOSThread* thread = static_cast(instance); - DMQ_ASSERT_TRUE(thread != nullptr); - thread->Run(); - vTaskDelete(NULL); -} - -//---------------------------------------------------------------------------- -// WatchdogCheckAll -//---------------------------------------------------------------------------- -void FreeRTOSThread::WatchdogCheckAll() -{ - const dmq::LockGuard lock(GetWatchdogLock()); - FreeRTOSThread* p = GetWatchdogHead(); - while (p != nullptr) - { - p->WatchdogCheck(); - p = p->m_watchdogNext; - } -} - -//---------------------------------------------------------------------------- -// WatchdogCheck -//---------------------------------------------------------------------------- -void FreeRTOSThread::WatchdogCheck() -{ - if (m_startGate.IsHeld()) - return; // held at its start gate by design, not hung - - auto now = static_cast(Timer::GetNow().time_since_epoch().count()); - auto lastAlive = m_lastAliveTime.load(); - auto watchdogTimeout = m_watchdogTimeout.load(); - - if (watchdogTimeout > 0) - { - auto delta = now - lastAlive; - if (delta > watchdogTimeout) - { - WatchdogHandler(THREAD_NAME.c_str()); - } - } -} - -//---------------------------------------------------------------------------- -// ThreadCheck -//---------------------------------------------------------------------------- -void FreeRTOSThread::ThreadCheck() -{ - m_lastAliveTime.store(static_cast(Timer::GetNow().time_since_epoch().count())); -} - -void FreeRTOSThread::Run() -{ - bool selfExit = false; - m_selfExitPtr = &selfExit; - - // Exit and idle handlers are copied onto this stack frame so they work on - // every return path, including a self-exit where 'this' may already be freed. - ThreadExitGuard exitGuard(m_exitHandler); - ThreadIdleTimer idle(m_idleHandler, m_idleInterval); - - // xTaskCreateStatic() stores m_thread only after this task may already be - // running; wait for CreateThread() so the start handler can use it. - const bool startSync = m_startSync; - if (startSync) - ulTaskNotifyTake(pdTRUE, portMAX_DELAY); - - // dmq::ThisThread::GetCurrent() returns this thread from here on. Reset - // before the exit handler runs (and destroyed before exitGuard on a - // self-exit), so the exit handler sees nullptr. - std::optional currentScope; - currentScope.emplace(this); - - if (m_startHandler) - m_startHandler(); - - // A start handler that exited this thread (ExitThread() on itself) leaves - // right after the signal below: once CreateThread() returns, the Thread may - // be destroyed, so nothing after the signal may touch 'this'. - const bool exitedInStart = selfExit; - - if (startSync) - xSemaphoreGive(m_startSem); - if (exitedInStart) - return; - - // Optional start gate: wait here, ready but processing nothing, until it opens - if (m_startGate.Enabled()) - { - const bool opened = m_startGate.Wait(m_exit); - // Before Passed(): no stale watchdog read - m_lastAliveTime.store(static_cast(Timer::GetNow().time_since_epoch().count())); - m_startGate.Passed(); - // ExitThread() while held: run nothing. Cancel each queued message - // (DISCARD) until the exit message. Consuming them also keeps - // ExitThread()'s blocking send of the exit message from waiting on a - // full queue. - if (!opened) - m_discard.store(true); - } - - ThreadMsg* msg = nullptr; - while (!selfExit) - { - m_lastAliveTime.store(static_cast(Timer::GetNow().time_since_epoch().count())); - auto watchdogTimeout = m_watchdogTimeout.load(); - - // If watchdog active, use a finite timeout so we can periodically update - // m_lastAliveTime while idle. If an idle handler is set, wake no later - // than when it is due. Otherwise, block forever to save power. - TickType_t waitTicks = portMAX_DELAY; - if (watchdogTimeout > 0) - { - waitTicks = pdMS_TO_TICKS(watchdogTimeout / dmq::WATCHDOG_HEARTBEAT_DIVISOR); - if (waitTicks == 0) waitTicks = 1; - } - if (idle.Enabled()) - { - auto ms = std::chrono::ceil(idle.WaitTime(dmq::Duration(-1))).count(); - TickType_t idleTicks = pdMS_TO_TICKS(ms); - if (ms > 0 && idleTicks == 0) idleTicks = 1; - if (idleTicks < waitTicks) waitTicks = idleTicks; - } - - msg = m_queue.Receive(waitTicks); - if (msg == nullptr) - { - // Exit requested but no exit message arrived (e.g. it could not be allocated) - if (m_exit.load()) - break; - - // Timed out with the queue empty: run the idle handler if it is due - if (idle.IsDue()) - { - idle.Run(); - // The idle handler exited this thread (and may have deleted it): leave - // without touching 'this', as the message path does - if (selfExit) - return; - } - } - else - { - - int msgId = msg->GetId(); - if (msgId == MSG_DISPATCH_DELEGATE && m_discard.load()) - { - // ExitPolicy::DISCARD: skip messages queued ahead of the exit message - CancelThreadMsg(*msg); - } - else if (msgId == MSG_DISPATCH_DELEGATE) - { -#if defined(DMQ_DATABUS_TOOLS) - // Update latency stats before invoking - dmq::Duration latency = Timer::GetNow() - msg->GetEnqueueTime(); - int64_t latNs = std::chrono::duration_cast(latency).count(); - - { - const dmq::LockGuard lock(m_statsLock); - m_latencyTotalWindow += latNs; - m_latencyCountWindow += 1; - if (latNs > m_latencyMaxWindow) m_latencyMaxWindow = latNs; - if (latNs > m_latencyMaxAll) m_latencyMaxAll = latNs; - m_dispatchCountAll += 1; - } -#endif - - auto delegateMsg = msg->GetData(); - DMQ_ASSERT_TRUE(delegateMsg); - auto invoker = delegateMsg->GetInvoker(); - DMQ_ASSERT_TRUE(invoker); - -#if defined(DMQ_DATABUS_TOOLS) - dmq::TimePoint start = Timer::GetNow(); -#endif -#if defined(__cpp_exceptions) && !defined(DMQ_ASSERTS) - bool success = false; - try { - success = invoker->Invoke(delegateMsg); - if (!selfExit) DMQ_ASSERT_TRUE(success); - } - catch (const std::bad_alloc& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled bad_alloc in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::invalid_argument& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled invalid_argument in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::runtime_error& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled runtime_error in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::exception& e) { - printf("[Thread:%s] Unhandled exception in delegate callback: %s\n", THREAD_NAME.c_str(), e.what()); - DMQ_ASSERT(); - } - catch (...) { - printf("[Thread:%s] Unhandled unknown exception in delegate callback.\n", THREAD_NAME.c_str()); - DMQ_ASSERT(); - } -#else - bool success = invoker->Invoke(delegateMsg); - if (!selfExit) DMQ_ASSERT_TRUE(success); -#endif - if (selfExit) { - delete msg; - return; - } - -#if defined(DMQ_DATABUS_TOOLS) - dmq::Duration invokeTime = Timer::GetNow() - start; - int64_t invokeNs = std::chrono::duration_cast(invokeTime).count(); - { - const dmq::LockGuard lock(m_statsLock); - m_invokeTotalWindow += invokeNs; - m_invokeCountWindow += 1; - if (invokeNs > m_invokeMaxWindow) m_invokeMaxWindow = invokeNs; - if (invokeNs > m_invokeMaxAll) m_invokeMaxAll = invokeNs; - } -#endif - } - - delete msg; - - if (msgId == MSG_EXIT_THREAD) { - break; - } - - // Any message restarts the idle countdown - idle.Restart(); - } - } - - // Run the exit handler before signalling ExitThread(), so it returns only after it - currentScope.reset(); - exitGuard.Fire(); - - // Clear before signalling: once ExitThread() returns, 'this' may be destroyed - m_selfExitPtr = nullptr; - if (m_exitSem) { - xSemaphoreGive(m_exitSem); - } -} - -#if defined(DMQ_DATABUS_TOOLS) -//---------------------------------------------------------------------------- -// SnapshotStats -//---------------------------------------------------------------------------- -FreeRTOSThread::ThreadStats FreeRTOSThread::SnapshotStats() -{ - ThreadStats stats; - stats.cpu_name = CPU_NAME; - stats.thread_name = THREAD_NAME; - stats.queue_depth = GetQueueSize(); - stats.queue_depth_max_window = m_queueDepthMaxWindow.exchange(0); - stats.queue_depth_max_all = m_queueDepthMaxAll.load(); - stats.queue_size_limit = m_queueSize; - - { - const dmq::LockGuard lock(m_statsLock); - uint32_t count = m_latencyCountWindow; - m_latencyCountWindow = 0; - int64_t total = m_latencyTotalWindow; - m_latencyTotalWindow = 0; - - if (count > 0) { - stats.latency_avg_ms = (float)total / (static_cast(count) * 1000000.0f); - } else { - stats.latency_avg_ms = 0.0f; - } - - stats.latency_max_window_ms = (float)m_latencyMaxWindow / 1000000.0f; - m_latencyMaxWindow = 0; - stats.latency_max_all_ms = (float)m_latencyMaxAll / 1000000.0f; - - uint32_t iCount = m_invokeCountWindow; - m_invokeCountWindow = 0; - int64_t iTotal = m_invokeTotalWindow; - m_invokeTotalWindow = 0; - - if (iCount > 0) { - stats.invoke_avg_ms = (float)iTotal / (static_cast(iCount) * 1000000.0f); - } else { - stats.invoke_avg_ms = 0.0f; - } - - stats.invoke_max_window_ms = (float)m_invokeMaxWindow / 1000000.0f; - m_invokeMaxWindow = 0; - stats.invoke_max_all_ms = (float)m_invokeMaxAll / 1000000.0f; - - stats.dispatch_count = m_dispatchCountAll; - } - - return stats; -} -#endif - -} // namespace dmq::os - -#endif // DMQ_THREAD_FREERTOS diff --git a/DelegateMQ/port/os/freertos/FreeRTOSThread.h b/DelegateMQ/port/os/freertos/FreeRTOSThread.h deleted file mode 100644 index fa2df68..0000000 --- a/DelegateMQ/port/os/freertos/FreeRTOSThread.h +++ /dev/null @@ -1,329 +0,0 @@ -#ifndef _THREAD_FREERTOS_H -#define _THREAD_FREERTOS_H - -/// @file FreeRTOSThread.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// @brief FreeRTOS implementation of the DelegateMQ IThread interface. -/// -/// @details -/// This class provides a concrete implementation of the `IThread` interface using -/// FreeRTOS primitives (Tasks and Queues). It enables DelegateMQ to dispatch -/// asynchronous delegates to a dedicated FreeRTOS task. -/// -/// @note This implementation is a basic port. For reference, the stdlib and win32 -/// implementations provide additional features: -/// 1. Synchronized Startup: CreateThread() blocks until the worker thread is ready. -/// -/// **Key Features:** -/// * **Task Integration:** Wraps a FreeRTOS `xTaskCreate` call to establish a -/// dedicated worker loop. -/// * **FullPolicy Support:** Configurable back-pressure (DROP or TIMEOUT) when the -/// message queue is full. -/// * **Priority Support:** Normal and High priorities, as two FIFO queue lanes drained -/// HIGH first, so same-priority messages keep dispatch order (see -/// `FreeRTOSDelegateQueue` for why one queue + `xQueueSendToFront()` is wrong). -/// * **Queue-Based Dispatch:** Uses `FreeRTOSDelegateQueue` (a thin RAII wrapper -/// around a FreeRTOS `QueueHandle_t`) to receive and process incoming delegate -/// messages in a thread-safe manner. -/// * **Thread Identification:** Implements `GetThreadId()` using `TaskHandle_t` -/// to ensure correct thread context checks (used by `AsyncInvoke` optimizations). -/// * **Graceful Shutdown:** Provides mechanisms (`ExitThread`) to cleanup resources, -/// though typical embedded tasks often run forever. -/// * **Watchdog Integration:** Optional heartbeat mechanism detects stalled or deadlocked -/// threads. Enable by passing a timeout to CreateThread(). Requires -/// Thread::WatchdogCheckAll() to be called periodically from a context that can preempt -/// watched threads -- the highest-priority task in the system, not an ISR. -/// * **Start Gate:** Optional `SetStartGate(StartGate*)`, called before `CreateThread()`, -/// holds the thread ready but processing no messages, at any priority, until -/// `StartGate::Open()` releases every thread sharing the gate at once. - -#include "delegate/IThread.h" -#include "delegate/UnicastDelegate.h" -#include "extras/util/Timer.h" -#include "port/os/common/ThreadMsg.h" -#include "port/os/common/StartGate.h" -#include "FreeRTOSDelegateQueue.h" -#include "FreeRTOS.h" -#include "task.h" -#include "queue.h" -#include "semphr.h" -#include -#include -#include -#include - -namespace dmq::os { - -/// @brief Policy applied when the FreeRTOS task queue is full (see dmq::FullPolicy -/// in DelegateOpt.h for the canonical definition, shared by every dmq::os::Thread port). -/// DROP/FAULT map to xQueueSend() with timeout 0; TIMEOUT to a finite timeout. -/// FAULT is the default. For embedded targets where the caller may be an ISR or -/// high-priority task, consider DROP to avoid blocking at an unsafe context. -using FullPolicy = dmq::FullPolicy; - -/// @brief What ExitThread() does with queued messages. See dmq::ExitPolicy in DelegateOpt.h. -using ExitPolicy = dmq::ExitPolicy; - -class FreeRTOSThread : public dmq::IThread -{ - XALLOCATOR -public: -#if defined(DMQ_DATABUS_TOOLS) - /// @brief Statistics captured for thread monitoring. - struct ThreadStats { - dmq::xstring cpu_name; - dmq::xstring thread_name; - size_t queue_depth; // Current depth - size_t queue_depth_max_window;// Max depth since last snapshot - size_t queue_depth_max_all; // All-time max depth - size_t queue_size_limit; // Max allowed - float latency_avg_ms; // Avg wait in window - float latency_max_window_ms; // Max wait since last snapshot - float latency_max_all_ms; // All-time max wait - float invoke_avg_ms; // Avg execution in window - float invoke_max_window_ms; // Max execution since last snapshot - float invoke_max_all_ms; // All-time max execution - uint64_t dispatch_count; // Total dispatches (all-time) - }; -#endif - - /// Default queue size if 0 is passed - static const size_t DEFAULT_QUEUE_SIZE = dmq::DEFAULT_QUEUE_SIZE; - - /// Constructor - /// @param threadName Name for the FreeRTOS task - /// @param maxQueueSize Max number of messages in queue (0 = Default dmq::DEFAULT_QUEUE_SIZE) - /// @param fullPolicy Action when queue is full: FAULT (default), DROP, or TIMEOUT. - /// @param dispatchTimeout Duration to wait before giving up when policy is TIMEOUT. - /// @param cpuName Optional CPU/Core name grouping for monitoring tools. - FreeRTOSThread(const char* threadName, size_t maxQueueSize = 0, FullPolicy fullPolicy = FullPolicy::FAULT, - dmq::Duration dispatchTimeout = dmq::DEFAULT_DISPATCH_TIMEOUT, const char* cpuName = ""); - - FreeRTOSThread(const std::string& threadName, size_t maxQueueSize = 0, FullPolicy fullPolicy = FullPolicy::FAULT, - dmq::Duration dispatchTimeout = dmq::DEFAULT_DISPATCH_TIMEOUT, const std::string& cpuName = "") - : FreeRTOSThread(threadName.c_str(), maxQueueSize, fullPolicy, dispatchTimeout, cpuName.c_str()) {} - - /// Destructor - ~FreeRTOSThread(); - - /// Called once to create the worker thread. If watchdogTimeout value - /// provided, the maximum watchdog interval is used. Otherwise no watchdog. - /// @param[in] watchdogTimeout - optional watchdog timeout. - /// @return TRUE if thread is created. FALSE otherwise. - bool CreateThread(std::optional watchdogTimeout = std::nullopt); - - /// Returns true if the thread is created - bool IsThreadCreated() const { return m_thread != nullptr; } - - /// Shut down the worker thread. - /// @param[in] policy - DRAIN (default) invokes every message queued before this - /// call first; DISCARD invokes only the message already running and cancels - /// the rest (see dmq::ExitPolicy). Called from the thread's own message - /// handler (a self-exit), queued messages are always discarded. - void ExitThread(ExitPolicy policy = ExitPolicy::DRAIN); - - /// Get the ID of this thread instance - TaskHandle_t GetThreadId(); - - /// Get the ID of the currently executing thread - static TaskHandle_t GetCurrentThreadId(); - - /// Returns true if the calling thread is this thread - virtual bool IsCurrentThread() override; - - /// Get thread name - dmq::xstring GetThreadName() { return THREAD_NAME; } - - /// Get current queue size - size_t GetQueueSize(); - - /// Sleep for a duration. - /// @param[in] timeout - the duration to sleep. - static void Sleep(dmq::Duration timeout); - - /// Set the FreeRTOS Task Priority. - /// Can be called before or after CreateThread(). - /// @param priority FreeRTOS priority level (0 to configMAX_PRIORITIES-1) - void SetThreadPriority(int priority); - - /// Optional: Provide a static buffer for the task stack to avoid Heap usage. - /// @param stackBuffer Pointer to a buffer of type StackType_t. - /// @param stackSizeInWords Size of the buffer in WORDS (not bytes). - void SetStackMem(StackType_t* stackBuffer, uint32_t stackSizeInWords); - - // IThread Interface Implementation - virtual bool DispatchDelegate(std::shared_ptr msg) override; - - /// @brief Register a handler invoked when DispatchDelegate() drops a message: - /// under FullPolicy::DROP (queue full, discarded immediately) or - /// FullPolicy::TIMEOUT (queue stayed full for dispatchTimeout, discarded). - /// Optional; unset by default. Called synchronously on the calling (producer) - /// thread, with the queue depth at the time of the drop. - void SetDroppedHandler(const dmq::UnicastDelegate& handler) { m_droppedHandler = handler; } - void SetDroppedHandler(dmq::UnicastDelegate&& handler) { m_droppedHandler = std::move(handler); } - - /// @brief Register a handler invoked on the worker thread before it processes - /// any message. Use it for per-thread setup (COM, a language runtime attach, - /// thread-local state, affinity). CreateThread() returns only after it completes. - /// @details Must be called while the thread is not running (before CreateThread(), - /// or after ExitThread()); calling it on a running thread faults. It runs again - /// on each CreateThread(). Messages dispatched meanwhile are queued, not lost. - void SetStartHandler(const dmq::UnicastDelegate& handler) { DMQ_ASSERT_TRUE(!IsThreadCreated()); m_startHandler = handler; } - void SetStartHandler(dmq::UnicastDelegate&& handler) { DMQ_ASSERT_TRUE(!IsThreadCreated()); m_startHandler = std::move(handler); } - - /// @brief Optional: hold this thread at `gate` once it is created, until - /// `gate->Open()`. Pass nullptr (the default) to start at once. - /// @details CreateThread() still runs the start handler and returns when the - /// thread is ready; the thread then processes nothing, at any priority, until - /// the gate opens. Use one gate for a group of threads so they all start - /// together after setup. See port/os/common/StartGate.h. Must be called while - /// the thread is not running; calling it on a running thread faults. - void SetStartGate(StartGate* gate) { DMQ_ASSERT_TRUE(!IsThreadCreated()); m_startGate.Set(gate); } - - /// @brief Register a handler invoked on the worker thread after it processes - /// its last message, as the thread exits. Use it to undo SetStartHandler() setup. - /// @details Must be called while the thread is not running; calling it on a - /// running thread faults. The handler is copied when the thread starts. - /// ExitThread() from another thread returns after it completes. If the thread - /// exits itself (ExitThread() from a handler on this thread), it runs after the - /// owning FreeRTOSThread may already be destroyed, so it must not touch that object. - void SetExitHandler(const dmq::UnicastDelegate& handler) { DMQ_ASSERT_TRUE(!IsThreadCreated()); m_exitHandler = handler; } - void SetExitHandler(dmq::UnicastDelegate&& handler) { DMQ_ASSERT_TRUE(!IsThreadCreated()); m_exitHandler = std::move(handler); } - - /// @brief Register a handler invoked on the worker thread when its queue has - /// been empty for `interval`, then again every `interval` while it stays empty. - /// Any message processed restarts the countdown. Use it for background work that - /// should yield to messages: polling, housekeeping, entering low power. - /// @details Must be called while the thread is not running; calling it on a - /// running thread faults. The handler and interval are copied when the thread - /// starts. Not called once ExitThread() has been requested. - /// @param[in] handler - the idle handler, or an empty delegate to disable. - /// @param[in] interval - quiet time before each call. Must be greater than zero. - /// Defaults to dmq::THREAD_IDLE_INTERVAL (DMQ_THREAD_IDLE_INTERVAL). - void SetIdleHandler(const dmq::UnicastDelegate& handler, dmq::Duration interval = dmq::THREAD_IDLE_INTERVAL) - { - DMQ_ASSERT_TRUE(!IsThreadCreated()); - DMQ_ASSERT_TRUE(interval > dmq::Duration::zero()); - m_idleHandler = handler; - m_idleInterval = interval; - } - void SetIdleHandler(dmq::UnicastDelegate&& handler, dmq::Duration interval = dmq::THREAD_IDLE_INTERVAL) - { - DMQ_ASSERT_TRUE(!IsThreadCreated()); - DMQ_ASSERT_TRUE(interval > dmq::Duration::zero()); - m_idleHandler = std::move(handler); - m_idleInterval = interval; - } - - /// @brief Manually update the watchdog alive timestamp. - /// @details The Run() loop refreshes the timestamp automatically on every iteration. - /// Call this from inside long-running message handlers to prevent a false watchdog - /// alarm when a handler legitimately takes longer than watchdogTimeout. - void ThreadCheck(); - - /// @brief Check all registered threads for watchdog expiration. - /// @details Call this from the highest-priority task in the system. - static void WatchdogCheckAll(); - -#if defined(DMQ_DATABUS_TOOLS) - /// @brief Capture and reset windowed statistics. - ThreadStats SnapshotStats(); -#endif - -private: - FreeRTOSThread(const FreeRTOSThread&) = delete; - FreeRTOSThread& operator=(const FreeRTOSThread&) = delete; - - /// Entry point for the thread - static void Process(void* instance); - - // Run loop called by Process - void Run(); - - /// Check watchdog is expired for this instance. - void WatchdogCheck(); - - /// Get registry head using the "Immortal" Pattern - static FreeRTOSThread*& GetWatchdogHead() - { - static FreeRTOSThread* head = nullptr; - return head; - } - - /// Get registry lock using the "Immortal" Pattern - static dmq::RecursiveMutex& GetWatchdogLock() - { - static dmq::RecursiveMutex* lock = new dmq::RecursiveMutex(); - return *lock; - } - - const dmq::xstring THREAD_NAME; - const dmq::xstring CPU_NAME; - const FullPolicy FULL_POLICY; - const dmq::Duration m_dispatchTimeout; - size_t m_queueSize; - int m_priority; - - TaskHandle_t m_thread = nullptr; - FreeRTOSDelegateQueue m_queue; - - // Optional handler invoked when a message is dropped (FullPolicy::DROP or TIMEOUT) - dmq::UnicastDelegate m_droppedHandler; - - // Optional handlers invoked on the worker thread at start, exit and when idle - dmq::UnicastDelegate m_startHandler; - dmq::UnicastDelegate m_exitHandler; - dmq::UnicastDelegate m_idleHandler; - dmq::Duration m_idleInterval = dmq::Duration::zero(); - SemaphoreHandle_t m_exitSem = nullptr; // Synchronization for safe destruction - SemaphoreHandle_t m_startSem = nullptr; // Given by Run() once the start handler has run - bool m_startSync = false; // CreateThread() waits for the start handler (scheduler running) - std::atomic m_exit = false; - std::atomic m_discard = false; // ExitPolicy::DISCARD: cancel queued messages instead of invoking - bool* m_selfExitPtr = nullptr; - - // Static allocation support - StackType_t* m_stackBuffer = nullptr; - uint32_t m_stackSize = dmq::FREERTOS_STACK_WORDS; // Default size (words), see DMQ_FREERTOS_STACK_WORDS - StaticTask_t m_tcb; // TCB storage for static creation - - // Watchdog related members - std::atomic m_lastAliveTime{0}; - std::atomic m_watchdogTimeout{0}; - - // Optional start gate (SetStartGate()): its state, and whether the thread is - // held at it (the watchdog doesn't report a thread waiting by design) - StartGateClient m_startGate; - FreeRTOSThread* m_watchdogNext = nullptr; - -#if defined(DMQ_DATABUS_TOOLS) - // Monitoring statistics members - std::atomic m_queueDepthMaxWindow{0}; - std::atomic m_queueDepthMaxAll{0}; - - // Use a mutex to protect 64-bit stats on 32-bit platforms without libatomic - dmq::RecursiveMutex m_statsLock; - int64_t m_latencyTotalWindow{0}; - uint32_t m_latencyCountWindow{0}; - int64_t m_latencyMaxWindow{0}; - int64_t m_latencyMaxAll{0}; - - int64_t m_invokeTotalWindow{0}; - uint32_t m_invokeCountWindow{0}; - int64_t m_invokeMaxWindow{0}; - int64_t m_invokeMaxAll{0}; - - uint64_t m_dispatchCountAll{0}; -#endif -}; - -/// @brief Backward-compatible name: existing code referencing dmq::os::Thread -/// keeps compiling unchanged against the FreeRTOS port. -using Thread = FreeRTOSThread; - -} // namespace dmq::os - - -#endif diff --git a/DelegateMQ/port/os/nuttx/NuttXClock.h b/DelegateMQ/port/os/nuttx/NuttXClock.h deleted file mode 100644 index 08c866c..0000000 --- a/DelegateMQ/port/os/nuttx/NuttXClock.h +++ /dev/null @@ -1,35 +0,0 @@ -#ifndef NUTTX_CLOCK_H -#define NUTTX_CLOCK_H - -/// @file NuttXClock.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief dmq::Clock backing for NuttX, using the POSIX clock_gettime() -/// call NuttX provides directly (CLOCK_MONOTONIC) rather than a kernel- -/// specific tick counter like k_uptime_get()/tx_time_get(). NuttX's POSIX -/// layer already exposes nanosecond resolution, so no k_ticks-to-duration -/// conversion is needed here. - -#include -#include -#include - -namespace dmq::os { - struct NuttXClock { - using rep = int64_t; - using period = std::nano; - using duration = std::chrono::duration; - using time_point = std::chrono::time_point; - static const bool is_steady = true; - - static time_point now() noexcept { - struct timespec ts; - clock_gettime(CLOCK_MONOTONIC, &ts); - rep ns = static_cast(ts.tv_sec) * 1000000000LL + static_cast(ts.tv_nsec); - return time_point(duration(ns)); - } - }; -} // namespace dmq::os - -#endif // NUTTX_CLOCK_H diff --git a/DelegateMQ/port/os/nuttx/NuttXCriticalSection.h b/DelegateMQ/port/os/nuttx/NuttXCriticalSection.h deleted file mode 100644 index c0c0d4d..0000000 --- a/DelegateMQ/port/os/nuttx/NuttXCriticalSection.h +++ /dev/null @@ -1,82 +0,0 @@ -#ifndef NUTTX_CRITICAL_SECTION_H -#define NUTTX_CRITICAL_SECTION_H - -/// @file NuttXCriticalSection.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief ISR-safe critical section for NuttX. -/// -/// @details -/// pthread_mutex_lock() is a priority-inheritance-aware, thread-only -/// primitive on NuttX, like every other RTOS mutex in this library -- it -/// cannot be used from ISR context. This type uses up_irq_save()/ -/// up_irq_restore(flags) instead: NuttX's own architecture-portable -/// interrupt-masking primitive (declared in ), implemented on -/// every supported CPU architecture and used throughout NuttX's own kernel -/// for exactly this purpose -- protecting something tiny that both ISR and -/// thread code touch. This is the same save/disable/restore technique -/// ThreadXCriticalSection and ZephyrCriticalSection use, just NuttX's own -/// primitive instead of a vendor CMSIS-Core intrinsic. -/// -/// @warning up_irq_save()/up_irq_restore() are only reachable from -/// application code in a NuttX FLAT build (the default for most boards, -/// where apps and the kernel share one address space). In a PROTECTED or -/// KERNEL build, application code runs in unprivileged userspace with no -/// access to this call, and dmq::util::Timer::ProcessTimers() must instead -/// be driven from kernel-side code (e.g. a NuttX interrupt handler or a -/// kernel-mode work queue) on those configurations. -/// -/// *** NARROW PURPOSE -- DO NOT USE THIS AS A GENERAL-PURPOSE LOCK *** -/// Holding this masks ALL maskable interrupts on the CPU for as long as it -/// is held. Only use it to protect something genuinely tiny and bounded -/// that may be touched from ISR context. Do NOT use it in place of -/// dmq::Mutex / dmq::RecursiveMutex for ordinary thread-to-thread -/// synchronization (e.g. DataBus internals, a Thread's message queue) -- -/// anything that can block, take a while, or run for an unbounded time -/// must not run with interrupts globally masked; that is a real-time -/// correctness bug on hardware, not just a style issue. -/// -/// *** NOT RE-LOCKABLE ON THE SAME INSTANCE *** -/// Unlike dmq::RecursiveMutex, calling lock() twice on the SAME instance -/// without an intervening unlock() is incorrect: the second lock() call -/// overwrites the single saved irqstate_t with the (already masked) inner -/// state, so the outer unlock() restores the wrong state. There is no -/// "recursive" variant of this type -- it has no ownership concept to make -/// recursion meaningful, and Timer's own usage never nests. Locking two -/// DIFFERENT instances in proper LIFO lock/unlock order is fine: each -/// instance saves and restores its own state independently. - -#include - -namespace dmq::os { - - // ========================================================================= - // NuttXCriticalSection - // See the file-level comment above before using this type anywhere new. - // ========================================================================= - class NuttXCriticalSection { - public: - NuttXCriticalSection() = default; - - void lock() { - m_flags = up_irq_save(); - } - - void unlock() { - up_irq_restore(m_flags); - } - - // No try_lock(): interrupt masking cannot fail to "acquire", so a - // try_lock() here would always trivially succeed and isn't meaningful. - - NuttXCriticalSection(const NuttXCriticalSection&) = delete; - NuttXCriticalSection& operator=(const NuttXCriticalSection&) = delete; - - private: - irqstate_t m_flags = 0; - }; - -} // namespace dmq::os - -#endif // NUTTX_CRITICAL_SECTION_H diff --git a/DelegateMQ/port/os/nuttx/NuttXDelegateQueue.h b/DelegateMQ/port/os/nuttx/NuttXDelegateQueue.h deleted file mode 100644 index a44d3b1..0000000 --- a/DelegateMQ/port/os/nuttx/NuttXDelegateQueue.h +++ /dev/null @@ -1,186 +0,0 @@ -#ifndef NUTTX_DELEGATE_QUEUE_H -#define NUTTX_DELEGATE_QUEUE_H - -/// @file NuttXDelegateQueue.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief Thin RAII wrapper around a POSIX mqueue used by dmq::os::Thread -/// to carry pending ThreadMsg pointers, with priority support. -/// -/// @details -/// Unlike Zephyr's k_msgq (strict FIFO, no native priority -- see -/// ZephyrDelegateQueue.h's two-k_msgq workaround), POSIX mq_send() takes a -/// msg_prio argument directly: a higher-priority message is dequeued ahead -/// of lower-priority ones already queued, FIFO within the same priority. -/// A single mqd_t therefore handles both dmq::Priority lanes, the same way -/// CmsisRtos2DelegateQueue.h uses osMessageQueuePut's native msg_prio -- -/// no second queue needed here. This class owns no policy decisions of its -/// own (FullPolicy, timeout computation, and stats stay in Thread.cpp) -- -/// it only knows how to move ThreadMsg* pointers through a named POSIX -/// message queue. -/// -/// Each instance opens its own uniquely-named queue (process id + a -/// monotonic counter) since POSIX message queues live in a global, -/// filesystem-like namespace -- two dmq::os::Thread instances must never -/// collide on the same name. Destroy() closes and unlinks it. - -#include "port/os/common/ThreadMsg.h" -#include "delegate/DelegateOpt.h" -#include -#include -#include -#include -#include -#include -#include - -namespace dmq::os { - -class NuttXDelegateQueue -{ -public: - /// Sentinel meaning "block forever" for Send()/Receive()'s timeout - /// parameter -- dmq::Duration has no dedicated "infinite" value of its - /// own, so this mirrors the K_FOREVER/osWaitForever sentinel every - /// other dmq::os::Thread port already needs. - static constexpr dmq::Duration WAIT_FOREVER = dmq::Duration::max(); - - NuttXDelegateQueue() = default; - ~NuttXDelegateQueue() { Destroy(); } - - NuttXDelegateQueue(const NuttXDelegateQueue&) = delete; - NuttXDelegateQueue& operator=(const NuttXDelegateQueue&) = delete; - - /// Create the underlying queue with room for 'capacity' pointers. - /// @return true on success, false if mq_open() failed. - bool Create(size_t capacity) - { - if (m_mqd != INVALID_MQD) - return true; - - static std::atomic s_counter{0}; - std::snprintf(m_name, sizeof(m_name), "/dmq_q_%u_%u", - static_cast(getpid()), s_counter.fetch_add(1)); - - struct mq_attr attr; - std::memset(&attr, 0, sizeof(attr)); - attr.mq_maxmsg = static_cast(capacity); - attr.mq_msgsize = static_cast(sizeof(ThreadMsg*)); - - m_mqd = mq_open(m_name, O_CREAT | O_RDWR, 0600, &attr); - if (m_mqd != INVALID_MQD) { - mq_unlink(m_name); - } - return m_mqd != INVALID_MQD; - } - - bool IsCreated() const { return m_mqd != INVALID_MQD; } - - /// Send a message pointer. 'highPriority' is passed as mq_send()'s - /// native msg_prio argument -- a higher-priority message is delivered - /// ahead of lower-priority ones already queued, no second queue needed. - /// 'timeout' is Duration::zero() for non-blocking, WAIT_FOREVER to block - /// forever, or a finite duration for a bounded wait. - /// @return true if the message was enqueued. - bool Send(ThreadMsg* msg, bool highPriority, dmq::Duration timeout) - { - unsigned prio = highPriority ? 1u : 0u; - const char* data = reinterpret_cast(&msg); - - if (timeout == WAIT_FOREVER) - return mq_send(m_mqd, data, sizeof(msg), prio) == 0; - - struct timespec ts; - clock_gettime(CLOCK_REALTIME, &ts); - AddDuration(ts, timeout); - return mq_timedsend(m_mqd, data, sizeof(msg), prio, &ts) == 0; - } - - /// Receive a message pointer, blocking up to 'timeout'. The - /// high-priority lane is always delivered first since it is the - /// kernel's own mqueue ordering, not something this wrapper implements. - /// @return the message, or nullptr on timeout. - ThreadMsg* Receive(dmq::Duration timeout) - { - char buf[sizeof(ThreadMsg*)]; - unsigned prio = 0; - ssize_t n; - - if (timeout == WAIT_FOREVER) { - n = mq_receive(m_mqd, buf, sizeof(buf), &prio); - } else { - struct timespec ts; - clock_gettime(CLOCK_REALTIME, &ts); - AddDuration(ts, timeout); - n = mq_timedreceive(m_mqd, buf, sizeof(buf), &prio, &ts); - } - - if (n == static_cast(sizeof(ThreadMsg*))) { - ThreadMsg* msg = nullptr; - std::memcpy(&msg, buf, sizeof(msg)); - return msg; - } - return nullptr; - } - - /// Current number of messages waiting in the queue. - size_t Size() const - { - if (m_mqd == INVALID_MQD) - return 0; - struct mq_attr attr; - if (mq_getattr(m_mqd, &attr) == 0) - return static_cast(attr.mq_curmsgs); - return 0; - } - - /// Remove and delete every pending message without blocking. Used during - /// shutdown once the owning thread has stopped consuming the queue. - /// Each message is canceled first (CancelThreadMsg()), releasing a sender - /// blocked waiting on it. - void DrainAndDelete() - { - while (true) { - ThreadMsg* msg = Receive(dmq::Duration::zero()); - if (!msg) - break; - CancelThreadMsg(*msg); // Release a sender blocked on it - delete msg; - } - } - - void Destroy() - { - if (m_mqd != INVALID_MQD) { - mq_close(m_mqd); - mq_unlink(m_name); - m_mqd = INVALID_MQD; - } - } - -private: - static constexpr mqd_t INVALID_MQD = static_cast(-1); - - /// Add 'timeout' (clamped to zero for a non-positive/immediate wait) to - /// 'ts' in place, carrying seconds/nanoseconds correctly. - static void AddDuration(struct timespec& ts, dmq::Duration timeout) - { - if (timeout < dmq::Duration::zero()) - timeout = dmq::Duration::zero(); - auto ns = std::chrono::duration_cast(timeout).count(); - ts.tv_sec += static_cast(ns / 1000000000LL); - ts.tv_nsec += static_cast(ns % 1000000000LL); - if (ts.tv_nsec >= 1000000000L) { - ts.tv_nsec -= 1000000000L; - ts.tv_sec += 1; - } - } - - mqd_t m_mqd = INVALID_MQD; - char m_name[32] = {0}; -}; - -} // namespace dmq::os - -#endif // NUTTX_DELEGATE_QUEUE_H diff --git a/DelegateMQ/port/os/nuttx/NuttXMutex.h b/DelegateMQ/port/os/nuttx/NuttXMutex.h deleted file mode 100644 index 48152ca..0000000 --- a/DelegateMQ/port/os/nuttx/NuttXMutex.h +++ /dev/null @@ -1,88 +0,0 @@ -#ifndef NUTTX_MUTEX_H -#define NUTTX_MUTEX_H - -/// @file NuttXMutex.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief dmq::Mutex / dmq::RecursiveMutex backing for NuttX, using its -/// native POSIX pthread_mutex_t directly (NuttX implements the real POSIX -/// threading API, unlike FreeRTOS/ThreadX/Zephyr/CMSIS-RTOS2, which each -/// need a bespoke kernel-object wrapper here). - -#include - -namespace dmq::os { - - // ========================================================================= - // NuttXMutex (Non-Recursive) - // ========================================================================= - class NuttXMutex { - public: - NuttXMutex() { - pthread_mutex_init(&m_mutex, nullptr); - } - - ~NuttXMutex() { - pthread_mutex_destroy(&m_mutex); - } - - void lock() { - pthread_mutex_lock(&m_mutex); - } - - // REQUIRED for std::unique_lock compatibility - bool try_lock() { - return pthread_mutex_trylock(&m_mutex) == 0; - } - - void unlock() { - pthread_mutex_unlock(&m_mutex); - } - - NuttXMutex(const NuttXMutex&) = delete; - NuttXMutex& operator=(const NuttXMutex&) = delete; - - private: - pthread_mutex_t m_mutex; - }; - - // ========================================================================= - // NuttXRecursiveMutex (Recursive) - // ========================================================================= - class NuttXRecursiveMutex { - public: - NuttXRecursiveMutex() { - pthread_mutexattr_t attr; - pthread_mutexattr_init(&attr); - pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); - pthread_mutex_init(&m_mutex, &attr); - pthread_mutexattr_destroy(&attr); - } - - ~NuttXRecursiveMutex() { - pthread_mutex_destroy(&m_mutex); - } - - void lock() { - pthread_mutex_lock(&m_mutex); - } - - bool try_lock() { - return pthread_mutex_trylock(&m_mutex) == 0; - } - - void unlock() { - pthread_mutex_unlock(&m_mutex); - } - - NuttXRecursiveMutex(const NuttXRecursiveMutex&) = delete; - NuttXRecursiveMutex& operator=(const NuttXRecursiveMutex&) = delete; - - private: - pthread_mutex_t m_mutex; - }; - -} // namespace dmq::os - -#endif // NUTTX_MUTEX_H diff --git a/DelegateMQ/port/os/nuttx/NuttXSemaphore.h b/DelegateMQ/port/os/nuttx/NuttXSemaphore.h deleted file mode 100644 index 1d3e560..0000000 --- a/DelegateMQ/port/os/nuttx/NuttXSemaphore.h +++ /dev/null @@ -1,102 +0,0 @@ -#ifndef NUTTX_SEMAPHORE_H -#define NUTTX_SEMAPHORE_H - -/// @file NuttXSemaphore.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief dmq::Semaphore backing for NuttX, using its native POSIX sem_t -/// directly instead of the generic dmq::ConditionVariable + dmq::Mutex -/// implementation in delegate/Semaphore.h. -/// -/// @details -/// NuttX has no dmq::ConditionVariable port (no DMQ_HAS_CV) -- not because -/// it lacks pthread_cond_t (it has a real one), but because a native -/// sem_t is a more direct fit for what dmq::Semaphore actually needs, the -/// same reasoning ZephyrSemaphore.h and CmsisRtos2Semaphore.h give for -/// their own RTOSes: no need to build a semaphore out of a mutex + -/// condition variable when the platform already has a real one. DelegateOpt.h -/// resolves dmq::Semaphore to this type on NuttX; see the "Semaphore" -/// comment next to DMQ_THREAD_NUTTX's `using Semaphore = ...;` there. -/// -/// @note This header is included from DelegateOpt.h's early port-include -/// block, before "namespace dmq { ... }" opens and dmq::Duration is defined -/// inside it (including it any later would nest as dmq::dmq::os instead of -/// dmq::os) -- so, like ZephyrSemaphore.h and CmsisRtos2Semaphore.h, Wait() -/// is templated on the chrono duration type instead of depending on -/// dmq::Duration directly. A dmq::Duration argument still deduces through -/// it seamlessly at the call site, since dmq::Duration is itself a -/// std::chrono::duration specialization. -/// -/// @note sem_timedwait() takes an ABSOLUTE CLOCK_REALTIME deadline, not a -/// relative duration -- this computes that deadline from clock_gettime() -/// plus the caller's relative timeout, the standard POSIX idiom. - -#include -#include -#include - -namespace dmq::os { - - // ========================================================================= - // NuttXSemaphore - // Binary semaphore (max count 1), matching the semantics of the generic - // dmq::Semaphore this replaces: Signal() when already signaled is a - // no-op (not a counting semaphore), and Wait() consumes exactly one - // pending signal. - // ========================================================================= - class NuttXSemaphore { - public: - NuttXSemaphore() { - sem_init(&m_sem, 0, 0); - } - - ~NuttXSemaphore() { - sem_destroy(&m_sem); - } - - /// Called to wait on a semaphore to be signaled. - /// @param[in] timeout - semaphore timeout - /// @return Return true if semaphore signaled, false if timeout occurred. - template - bool Wait(const std::chrono::duration& timeout) { - using DurationT = std::chrono::duration; - if (timeout == DurationT::max()) { - return sem_wait(&m_sem) == 0; - } - - struct timespec ts; - clock_gettime(CLOCK_REALTIME, &ts); - auto ns = std::chrono::duration_cast(timeout).count(); - ts.tv_sec += static_cast(ns / 1000000000LL); - ts.tv_nsec += static_cast(ns % 1000000000LL); - if (ts.tv_nsec >= 1000000000L) { - ts.tv_nsec -= 1000000000L; - ts.tv_sec += 1; - } - return sem_timedwait(&m_sem, &ts) == 0; - } - - /// Called to signal a semaphore. - void Signal() { - int val = 0; - if (sem_getvalue(&m_sem, &val) == 0) { - if (val <= 0) { - sem_post(&m_sem); - } - } else { - // Fallback if sem_getvalue fails - sem_post(&m_sem); - } - } - - NuttXSemaphore(const NuttXSemaphore&) = delete; - NuttXSemaphore& operator=(const NuttXSemaphore&) = delete; - - private: - sem_t m_sem; - }; - -} // namespace dmq::os - -#endif // NUTTX_SEMAPHORE_H diff --git a/DelegateMQ/port/os/nuttx/NuttXThisThread.h b/DelegateMQ/port/os/nuttx/NuttXThisThread.h deleted file mode 100644 index 7d2c54e..0000000 --- a/DelegateMQ/port/os/nuttx/NuttXThisThread.h +++ /dev/null @@ -1,54 +0,0 @@ -#ifndef NUTTX_THIS_THREAD_H -#define NUTTX_THIS_THREAD_H - -/// @file NuttXThisThread.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief Portable sleep_for()/yield() for the calling thread, NuttX backend. -/// -/// @details -/// This is dmq::ThisThread for this port (see DelegateOpt.h). GetCurrent() -/// uses RegistryCurrentThread, keyed by the calling thread's id. Exists so -/// library internals that need to delay or yield (e.g. RetryMonitor backoff) -/// aren't forced to pull in the full dmq::os::Thread class -- which also -/// drags in the message queue, watchdog, and stats machinery -- just to -/// sleep. dmq::os::Thread::Sleep() forwards here too, so the NuttX delay -/// call is implemented exactly once. - -#include -#include -#include "NuttXMutex.h" -#include -#include -#include "port/os/common/CurrentThreadStorage.h" -#include - -namespace dmq::os { - - /// @brief Key for RegistryCurrentThread: the calling thread's id plus one (pid 0 - /// is the idle task, and 0 means "none"), or 0 inside an interrupt handler. - inline uintptr_t NuttXCurrentThreadKey() { - if (up_interrupt_context()) - return 0; - return static_cast(pthread_self()) + 1; - } - - struct NuttXThisThread : RegistryCurrentThread { - template - static void sleep_for(std::chrono::duration d) { - const auto ms = std::chrono::duration_cast(d); - struct timespec ts; - ts.tv_sec = static_cast(ms.count() / 1000); - ts.tv_nsec = static_cast((ms.count() % 1000) * 1000000L); - nanosleep(&ts, nullptr); - } - - static void yield() noexcept { - sched_yield(); - } - }; - -} // namespace dmq::os - -#endif // NUTTX_THIS_THREAD_H diff --git a/DelegateMQ/port/os/nuttx/NuttXThread.cpp b/DelegateMQ/port/os/nuttx/NuttXThread.cpp deleted file mode 100644 index da28bb0..0000000 --- a/DelegateMQ/port/os/nuttx/NuttXThread.cpp +++ /dev/null @@ -1,664 +0,0 @@ -// Compiles to nothing unless DMQ_THREAD_NUTTX is selected, so every DelegateMQ source -// file can be added to a build (see src/DelegateMQ.cpp). -#include "delegate/DelegateSelect.h" -#if defined(DMQ_THREAD_NUTTX) - -#include "DelegateMQ.h" -#include "NuttXThread.h" -#include "port/os/common/ThreadMsg.h" -#include "port/os/common/ThreadHooks.h" -#include "extras/util/Fault.h" -#include -#include // for memset -#include - -// Define DMQ_ASSERT_TRUE if not already defined -#ifndef DMQ_ASSERT_TRUE -#define DMQ_ASSERT_TRUE(x) assert(x) -#endif - -namespace dmq::os { - -using namespace dmq::util; - -//---------------------------------------------------------------------------- -// Thread Constructor -//---------------------------------------------------------------------------- -NuttXThread::NuttXThread(const char* threadName, size_t maxQueueSize, FullPolicy fullPolicy, dmq::Duration dispatchTimeout, const char* cpuName) - : THREAD_NAME(threadName) - , CPU_NAME(cpuName) - , m_queueSize((maxQueueSize == 0) ? DEFAULT_QUEUE_SIZE : maxQueueSize) - , FULL_POLICY(fullPolicy) - , m_dispatchTimeout(dispatchTimeout) - , m_exit(false) -{ - m_priority = dmq::NUTTX_THREAD_PRIORITY; // Default SCHED_FIFO priority (typically 1-255), DMQ_NUTTX_THREAD_PRIORITY - - sem_init(&m_exitSem, 0, 0); - sem_init(&m_goSem, 0, 0); - sem_init(&m_startSem, 0, 0); - -#if defined(DMQ_DATABUS_TOOLS) - pthread_mutex_init(&m_statMutex, nullptr); -#endif -} - -//---------------------------------------------------------------------------- -// Thread Destructor -//---------------------------------------------------------------------------- -NuttXThread::~NuttXThread() -{ - ExitThread(); - - sem_destroy(&m_exitSem); - sem_destroy(&m_goSem); - sem_destroy(&m_startSem); - -#if defined(DMQ_DATABUS_TOOLS) - pthread_mutex_destroy(&m_statMutex); -#endif - - const dmq::LockGuard lock(GetWatchdogLock()); - NuttXThread** pp = &GetWatchdogHead(); - while (*pp != nullptr) - { - if (*pp == this) - { - *pp = this->m_watchdogNext; - this->m_watchdogNext = nullptr; - break; - } - pp = &((*pp)->m_watchdogNext); - } -} - -//---------------------------------------------------------------------------- -// CreateThread -//---------------------------------------------------------------------------- -bool NuttXThread::CreateThread(std::optional watchdogTimeout) -{ - if (!m_created.load()) - { - // Reset from a previous ExitThread(), so the thread can be created again - m_exit.store(false); - // Held from creation, so the watchdog never sees a gated thread as hung - // before it reaches the gate (e.g. created before the scheduler runs) - m_startGate.OnCreate(); - // Set before the thread exists: its loop reads the timeout before its - // first queue wait, and an idle thread waits forever with no timeout - m_lastAliveTime.store(Timer::GetNow()); - m_watchdogTimeout.store(watchdogTimeout.value_or(dmq::Duration(0))); - m_discard.store(false); - - // 1. Create the message queue - DMQ_ASSERT_TRUE(m_queue.Create(m_queueSize)); - - // 2. Create the pthread - pthread_attr_t attr; - pthread_attr_init(&attr); - pthread_attr_setstacksize(&attr, STACK_SIZE); - - struct sched_param sp; - sp.sched_priority = m_priority; - pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED); - pthread_attr_setschedpolicy(&attr, SCHED_FIFO); - pthread_attr_setschedparam(&attr, &sp); - - int rc = pthread_create(&m_thread, &attr, NuttXThread::Process, this); - pthread_attr_destroy(&attr); - DMQ_ASSERT_TRUE(rc == 0); - -#if defined(PTHREAD_NAME_MAX) || defined(CONFIG_TASK_NAME_SIZE) - // NuttX supports naming a pthread for debugging (non-portable POSIX - // extension); harmless no-op if unsupported on a given configuration. - pthread_setname_np(m_thread, THREAD_NAME.c_str()); -#endif - - // pthread_create() stores m_thread only after the (SCHED_FIFO, possibly - // higher priority) thread may already be running: release Run() to the - // start handler now, then wait for it to complete. - sem_post(&m_goSem); - sem_wait(&m_startSem); - - m_created.store(true); - m_lastAliveTime.store(Timer::GetNow()); - - if (watchdogTimeout.has_value()) - { - - const dmq::LockGuard lock(GetWatchdogLock()); - - // Add to watchdog registry if not already present - bool found = false; - NuttXThread* p = GetWatchdogHead(); - while (p != nullptr) - { - if (p == this) - { - found = true; - break; - } - p = p->m_watchdogNext; - } - - if (!found) - { - m_watchdogNext = GetWatchdogHead(); - GetWatchdogHead() = this; - } - } - } - return true; -} - -//---------------------------------------------------------------------------- -// ExitThread -//---------------------------------------------------------------------------- -void NuttXThread::ExitThread(ExitPolicy policy) -{ - if (m_created.load()) - { - // Set before m_exit: Run() reads it for every message ahead of the exit message - m_discard.store(policy == ExitPolicy::DISCARD); - m_exit.store(true); - - // A thread held at its start gate isn't waiting on its queue: wake it so it - // sees the exit flag (set above) and leaves. Never touches the gate itself, - // which may be destroyed once the thread is released. - m_startGate.Wake(); - - // Check self-exit BEFORE attempting to enqueue the exit message. If - // this thread is destroying itself from within its own dispatched - // callback, it is not consuming its own queue right now -- it is - // blocked here, inside ExitThread(). A blocking mq_send() would - // deadlock forever if the queue happened to be full. No message - // needs to be queued in that case: Run()'s dispatch loop already - // checks m_selfExitPtr immediately after the current callback - // invoke returns, and unwinds without touching 'this' again. - // - // Crucially, a self-exiting thread must NOT touch m_queue here: it - // is still physically executing on its own stack (unwinding back - // through Invoke()/Run()), and it cannot pthread_join() itself. Set - // the flag and return immediately; the actual cleanup (queue - // drain/destroy, pthread_join) is deferred to a later ExitThread() - // call made from a different thread context -- typically - // ~NuttXThread() -- once m_selfExited tells that call it's safe to - // skip the message/semaphore handshake below (the thread already - // returned/is returning on its own) and go straight to the join. - if (pthread_equal(pthread_self(), m_thread)) { - m_selfExited.store(true); - if (m_selfExitPtr) { *m_selfExitPtr = true; m_selfExitPtr = nullptr; } - m_startGate.Leave(); // exited from its start handler: never reaches the gate - // Self-exit: this thread runs no more messages, and the object may be - // destroyed once this handler returns. Stop watchdog checks now. - m_watchdogTimeout.store(dmq::Duration(0)); - return; - } - - if (!m_selfExited.load()) - { - // Send exit message - ThreadMsg* msg = new (std::nothrow) ThreadMsg(MSG_EXIT_THREAD); - if (msg) - { - // Wait forever to ensure message is sent - if (!m_queue.Send(msg, /*highPriority=*/false, NuttXDelegateQueue::WAIT_FOREVER)) - { - delete msg; - } - } - - // Wait for thread to actually finish before joining. - sem_wait(&m_exitSem); - } - - // pthread_join() blocks until the kernel has fully torn the thread - // down, the race-free way to wait for that -- sem_wait() above only - // proves Run() is about to return, not that the kernel has finished - // unlinking it from scheduler structures. It is also the right call - // in the deferred self-exit case: the thread has already returned or - // is in the process of returning on its own, so this either returns - // immediately or waits only as long as that natural teardown takes. - pthread_join(m_thread, nullptr); - - // The thread has finished (or, on a self-exit, is in its last handler): - // stop watchdog checks. Not earlier, so a thread that hangs while - // ExitThread() waits for it is still reported. - m_watchdogTimeout.store(dmq::Duration(0)); - - m_queue.DrainAndDelete(); - m_queue.Destroy(); - - // Reset flag to mark as exited. This prevents a double-entry deadlock: - // ~NuttXThread() calls ExitThread() unconditionally, so if ExitThread() - // was already called explicitly, the second call must be a no-op. - m_created.store(false); - - // Allow this object to be reused for a fresh CreateThread()/Run() cycle. - m_selfExited.store(false); - } -} - -//---------------------------------------------------------------------------- -// SetThreadPriority -//---------------------------------------------------------------------------- -void NuttXThread::SetThreadPriority(int priority) -{ - m_priority = priority; - if (m_created.load()) { - struct sched_param sp; - sp.sched_priority = m_priority; - pthread_setschedparam(m_thread, SCHED_FIFO, &sp); - } -} - -//---------------------------------------------------------------------------- -// GetThreadId -//---------------------------------------------------------------------------- -pthread_t NuttXThread::GetThreadId() -{ - return m_thread; -} - -//---------------------------------------------------------------------------- -// GetCurrentThreadId -//---------------------------------------------------------------------------- -pthread_t NuttXThread::GetCurrentThreadId() -{ - return pthread_self(); -} - -//---------------------------------------------------------------------------- -// IsCurrentThread -//---------------------------------------------------------------------------- -bool NuttXThread::IsCurrentThread() -{ - if (!m_created.load()) - return false; - return pthread_equal(GetThreadId(), GetCurrentThreadId()) != 0; -} - -//---------------------------------------------------------------------------- -// GetQueueSize -//---------------------------------------------------------------------------- -size_t NuttXThread::GetQueueSize() -{ - return m_queue.Size(); -} - -void NuttXThread::Sleep(dmq::Duration timeout) { - dmq::ThisThread::sleep_for(timeout); -} - -//---------------------------------------------------------------------------- -// DispatchDelegate -//---------------------------------------------------------------------------- -bool NuttXThread::DispatchDelegate(std::shared_ptr msg) -{ - DMQ_ASSERT_TRUE(m_created.load()); - - // 1. Allocate message container - ThreadMsg* threadMsg = new (std::nothrow) ThreadMsg(MSG_DISPATCH_DELEGATE, msg); - if (!threadMsg) return false; -#if defined(DMQ_DATABUS_TOOLS) - threadMsg->SetEnqueueTime(Timer::GetNow()); -#endif - - // 2. Send pointer to queue - dmq::Duration timeout; - if (FULL_POLICY == FullPolicy::TIMEOUT) - timeout = m_dispatchTimeout; - else - timeout = dmq::Duration::zero(); // DROP and FAULT: non-blocking - - // High priority routes through mq_send()'s native msg_prio argument. - bool sent = m_queue.Send(threadMsg, msg->GetPriority() == dmq::Priority::HIGH, timeout); - if (!sent) - { - if (FULL_POLICY == FullPolicy::FAULT) { - printf("[Thread] CRITICAL: Queue full on thread '%s'! TRIGGERING FAULT.\n", THREAD_NAME.c_str()); - DMQ_ASSERT_TRUE(sent); - } else if (FULL_POLICY == FullPolicy::TIMEOUT) { - printf("[Thread] WARNING: Queue post timed out on '%s' — possible deadlock. Message dropped.\n", THREAD_NAME.c_str()); - if (m_droppedHandler) - m_droppedHandler(GetQueueSize()); - } else { // DROP - if (m_droppedHandler) - m_droppedHandler(GetQueueSize()); - } - // Failed to enqueue (queue full or timed out) - delete threadMsg; - return false; - } - -#if defined(DMQ_DATABUS_TOOLS) - // Update monitoring stats - { - pthread_mutex_lock(&m_statMutex); - size_t currentDepth = GetQueueSize(); - if (currentDepth > m_queueDepthMaxWindow) m_queueDepthMaxWindow = currentDepth; - if (currentDepth > m_queueDepthMaxAll) m_queueDepthMaxAll = currentDepth; - pthread_mutex_unlock(&m_statMutex); - } -#endif - - return true; -} - -//---------------------------------------------------------------------------- -// Process (Static Entry Point) -//---------------------------------------------------------------------------- -void* NuttXThread::Process(void* arg) -{ - NuttXThread* thread = static_cast(arg); - if (thread) - { - thread->Run(); - } - return nullptr; -} - -//---------------------------------------------------------------------------- -// WatchdogCheck -//---------------------------------------------------------------------------- -void NuttXThread::WatchdogCheck() -{ - if (m_startGate.IsHeld()) - return; // held at its start gate by design, not hung - - auto now = Timer::GetNow(); - auto lastAlive = m_lastAliveTime.load(); - auto watchdogTimeout = m_watchdogTimeout.load(); - - if (watchdogTimeout.count() > 0) - { - auto delta = now - lastAlive; - if (delta > watchdogTimeout) - { - WatchdogHandler(THREAD_NAME.c_str()); - } - } -} - -//---------------------------------------------------------------------------- -// ThreadCheck -//---------------------------------------------------------------------------- -void NuttXThread::ThreadCheck() -{ - m_lastAliveTime.store(Timer::GetNow()); -} - -//---------------------------------------------------------------------------- -// WatchdogCheckAll -//---------------------------------------------------------------------------- -void NuttXThread::WatchdogCheckAll() -{ - const dmq::LockGuard lock(GetWatchdogLock()); - NuttXThread* p = GetWatchdogHead(); - while (p != nullptr) - { - p->WatchdogCheck(); - p = p->m_watchdogNext; - } -} - -//---------------------------------------------------------------------------- -// GetWatchdogHead -//---------------------------------------------------------------------------- -NuttXThread*& NuttXThread::GetWatchdogHead() -{ - static NuttXThread* head = nullptr; - return head; -} - -//---------------------------------------------------------------------------- -// GetWatchdogLock -//---------------------------------------------------------------------------- -dmq::RecursiveMutex& NuttXThread::GetWatchdogLock() -{ - static dmq::RecursiveMutex* lock = new dmq::RecursiveMutex(); - return *lock; -} - -//---------------------------------------------------------------------------- -// Run (Member Function Loop) -//---------------------------------------------------------------------------- -void NuttXThread::Run() -{ - bool selfExit = false; - m_selfExitPtr = &selfExit; - - // Exit and idle handlers are copied onto this stack frame so they work on - // every return path, including a self-exit where 'this' may already be freed. - ThreadExitGuard exitGuard(m_exitHandler); - ThreadIdleTimer idle(m_idleHandler, m_idleInterval); - - // Wait for CreateThread() to store m_thread (see CreateThread()) - sem_wait(&m_goSem); - - // dmq::ThisThread::GetCurrent() returns this thread from here on. Reset - // before the exit handler runs (and destroyed before exitGuard on a - // self-exit), so the exit handler sees nullptr. - std::optional currentScope; - currentScope.emplace(this); - - if (m_startHandler) - m_startHandler(); - - // A start handler that exited this thread (ExitThread() on itself) leaves - // right after the signal below: once CreateThread() returns, the Thread may - // be destroyed, so nothing after the signal may touch 'this'. - const bool exitedInStart = selfExit; - - sem_post(&m_startSem); - if (exitedInStart) - return; - - // Optional start gate: wait here, ready but processing nothing, until it opens - if (m_startGate.Enabled()) - { - const bool opened = m_startGate.Wait(m_exit); - m_lastAliveTime.store(Timer::GetNow()); // before Passed(): no stale watchdog read - m_startGate.Passed(); - // ExitThread() while held: run nothing. Cancel each queued message - // (DISCARD) until the exit message. Consuming them also keeps - // ExitThread()'s blocking send of the exit message from waiting on a - // full queue. - if (!opened) - m_discard.store(true); - } - - ThreadMsg* msg = nullptr; - while (!selfExit) - { - dmq::Duration watchdogTimeout; - { - m_lastAliveTime.store(Timer::GetNow()); - watchdogTimeout = m_watchdogTimeout.load(); - } - - // If watchdog active, use a finite timeout so we can periodically update - // m_lastAliveTime while idle. If an idle handler is set, wake no later - // than when it is due. Otherwise, block forever to save power. - dmq::Duration waitOption = NuttXDelegateQueue::WAIT_FOREVER; - if (watchdogTimeout.count() > 0) - { - waitOption = watchdogTimeout / dmq::WATCHDOG_HEARTBEAT_DIVISOR; - if (waitOption <= dmq::Duration::zero()) - waitOption = std::chrono::duration_cast(std::chrono::milliseconds(1)); - } - if (idle.Enabled()) - waitOption = idle.WaitTime(watchdogTimeout.count() > 0 ? waitOption : dmq::Duration(-1)); - - // Block for a message or timeout - msg = m_queue.Receive(waitOption); - if (msg == nullptr) - { - // Exit requested but no exit message arrived (e.g. it could not be allocated) - if (m_exit.load()) - break; - - // Timed out with the queue empty: run the idle handler if it is due - if (idle.IsDue()) - { - idle.Run(); - // The idle handler exited this thread (and may have deleted it): leave - // without touching 'this', as the message path does - if (selfExit) - return; - } - } - else - { - int msgId = msg->GetId(); - if (msgId == MSG_DISPATCH_DELEGATE && m_discard.load()) - { - // ExitPolicy::DISCARD: skip messages queued ahead of the exit message - CancelThreadMsg(*msg); - } - else if (msgId == MSG_DISPATCH_DELEGATE) - { -#if defined(DMQ_DATABUS_TOOLS) - // Update latency stats before invoking - dmq::Duration latency = Timer::GetNow() - msg->GetEnqueueTime(); - { - pthread_mutex_lock(&m_statMutex); - m_latencyTotalWindow += latency; - m_latencyCountWindow++; - if (latency > m_latencyMaxWindow) m_latencyMaxWindow = latency; - if (latency > m_latencyMaxAll) m_latencyMaxAll = latency; - m_dispatchCountAll++; - pthread_mutex_unlock(&m_statMutex); - } -#endif - - auto delegateMsg = msg->GetData(); - DMQ_ASSERT_TRUE(delegateMsg); - auto invoker = delegateMsg->GetInvoker(); - DMQ_ASSERT_TRUE(invoker); - -#if defined(DMQ_DATABUS_TOOLS) - dmq::TimePoint start = Timer::GetNow(); -#endif -#if defined(__cpp_exceptions) && !defined(DMQ_ASSERTS) - bool success = false; - try { - success = invoker->Invoke(delegateMsg); - if (!selfExit) DMQ_ASSERT_TRUE(success); - } - catch (const std::bad_alloc& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled bad_alloc in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::invalid_argument& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled invalid_argument in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::runtime_error& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled runtime_error in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::exception& e) { - printf("[Thread:%s] Unhandled exception in delegate callback: %s\n", THREAD_NAME.c_str(), e.what()); - DMQ_ASSERT(); - } - catch (...) { - printf("[Thread:%s] Unhandled unknown exception in delegate callback.\n", THREAD_NAME.c_str()); - DMQ_ASSERT(); - } -#else - bool success = invoker->Invoke(delegateMsg); - if (!selfExit) DMQ_ASSERT_TRUE(success); -#endif - if (selfExit) { - delete msg; - return; - } - -#if defined(DMQ_DATABUS_TOOLS) - dmq::Duration invokeTime = Timer::GetNow() - start; - { - pthread_mutex_lock(&m_statMutex); - m_invokeTotalWindow += invokeTime; - m_invokeCountWindow++; - if (invokeTime > m_invokeMaxWindow) m_invokeMaxWindow = invokeTime; - if (invokeTime > m_invokeMaxAll) m_invokeMaxAll = invokeTime; - pthread_mutex_unlock(&m_statMutex); - } -#endif - } - - delete msg; - - if (msgId == MSG_EXIT_THREAD) { - break; - } - - // Any message restarts the idle countdown - idle.Restart(); - } - } - - // Run the exit handler before signalling ExitThread(), so it returns only after it - currentScope.reset(); - exitGuard.Fire(); - - // Clear before signalling: once ExitThread() returns, 'this' may be destroyed - m_selfExitPtr = nullptr; - // Signal that we are about to exit - sem_post(&m_exitSem); -} - -#if defined(DMQ_DATABUS_TOOLS) -//---------------------------------------------------------------------------- -// SnapshotStats -//---------------------------------------------------------------------------- -NuttXThread::ThreadStats NuttXThread::SnapshotStats() -{ - pthread_mutex_lock(&m_statMutex); - ThreadStats stats; - stats.cpu_name = CPU_NAME; - stats.thread_name = THREAD_NAME; - stats.queue_depth = GetQueueSize(); - stats.queue_depth_max_window = m_queueDepthMaxWindow; - stats.queue_depth_max_all = m_queueDepthMaxAll; - stats.queue_size_limit = m_queueSize; - - if (m_latencyCountWindow > 0) { - stats.latency_avg_ms = (float)std::chrono::duration_cast(m_latencyTotalWindow).count() / (static_cast(m_latencyCountWindow) * 1000.0f); - } else { - stats.latency_avg_ms = 0.0f; - } - - stats.latency_max_window_ms = (float)std::chrono::duration_cast(m_latencyMaxWindow).count() / 1000.0f; - stats.latency_max_all_ms = (float)std::chrono::duration_cast(m_latencyMaxAll).count() / 1000.0f; - - if (m_invokeCountWindow > 0) { - stats.invoke_avg_ms = (float)std::chrono::duration_cast(m_invokeTotalWindow).count() / (static_cast(m_invokeCountWindow) * 1000.0f); - } else { - stats.invoke_avg_ms = 0.0f; - } - - stats.invoke_max_window_ms = (float)std::chrono::duration_cast(m_invokeMaxWindow).count() / 1000.0f; - stats.invoke_max_all_ms = (float)std::chrono::duration_cast(m_invokeMaxAll).count() / 1000.0f; - - stats.dispatch_count = m_dispatchCountAll; - - // Reset windowed stats - m_queueDepthMaxWindow = 0; - m_latencyTotalWindow = Duration(0); - m_latencyCountWindow = 0; - m_latencyMaxWindow = Duration(0); - - m_invokeTotalWindow = Duration(0); - m_invokeCountWindow = 0; - m_invokeMaxWindow = Duration(0); - - pthread_mutex_unlock(&m_statMutex); - return stats; -} -#endif - -} // namespace dmq::os - -#endif // DMQ_THREAD_NUTTX diff --git a/DelegateMQ/port/os/nuttx/NuttXThread.h b/DelegateMQ/port/os/nuttx/NuttXThread.h deleted file mode 100644 index 1f7a175..0000000 --- a/DelegateMQ/port/os/nuttx/NuttXThread.h +++ /dev/null @@ -1,294 +0,0 @@ -#ifndef _THREAD_NUTTX_H -#define _THREAD_NUTTX_H - -/// @file NuttXThread.h -/// @brief NuttX RTOS implementation of the DelegateMQ IThread interface. -/// -/// @note This implementation is a basic port. For reference, the stdlib and win32 -/// implementations provide additional features: -/// 1. Synchronized Startup: CreateThread() blocks until the worker thread is ready. -/// -/// **Key Features:** -/// * **Task Integration:** Wraps `pthread_create` to establish a dedicated worker loop. -/// NuttX implements the real POSIX threading API, so this port builds on -/// pthread_t/pthread_create/pthread_join directly rather than a bespoke -/// kernel-object wrapper. -/// * **FullPolicy Support:** Configurable back-pressure (DROP or TIMEOUT) when the -/// message queue is full. -/// * **Priority Support:** Normal and High priorities, using POSIX mq_send()'s -/// native msg_prio argument -- see NuttXDelegateQueue.h. -/// * **Queue-Based Dispatch:** Uses `NuttXDelegateQueue` (a thin RAII wrapper -/// around a POSIX mqueue) to receive and process incoming delegate -/// messages in a thread-safe manner. -/// * **Watchdog Integration:** Optional heartbeat mechanism detects stalled or deadlocked -/// threads. Enable by passing a timeout to CreateThread(). Requires -/// Thread::WatchdogCheckAll() to be called periodically from a context that can preempt -/// watched threads -- the highest-priority task in the system, not an ISR. -/// * **Start Gate:** Optional `SetStartGate(StartGate*)`, called before `CreateThread()`, -/// holds the thread ready but processing no messages, at any priority, until -/// `StartGate::Open()` releases every thread sharing the gate at once. - -#include "delegate/IThread.h" -#include "delegate/UnicastDelegate.h" -#include "port/os/common/ThreadMsg.h" -#include "port/os/common/StartGate.h" -#include "NuttXDelegateQueue.h" -#include "extras/util/Timer.h" -#include -#include -#include -#include -#include -#include - -namespace dmq::os { - -/// @brief Policy applied when the thread message queue is full. See dmq::FullPolicy -/// in DelegateOpt.h for the canonical definition, shared by every dmq::os::Thread port. -using FullPolicy = dmq::FullPolicy; - -/// @brief What ExitThread() does with queued messages. See dmq::ExitPolicy in DelegateOpt.h. -using ExitPolicy = dmq::ExitPolicy; - -class NuttXThread : public dmq::IThread -{ -public: -#if defined(DMQ_DATABUS_TOOLS) - /// @brief Statistics captured for thread monitoring. - struct ThreadStats { - dmq::xstring cpu_name; - dmq::xstring thread_name; - size_t queue_depth; // Current depth - size_t queue_depth_max_window;// Max depth since last snapshot - size_t queue_depth_max_all; // All-time max depth - size_t queue_size_limit; // Max allowed - float latency_avg_ms; // Avg wait in window - float latency_max_window_ms; // Max wait since last snapshot - float latency_max_all_ms; // All-time max wait - float invoke_avg_ms; // Avg execution in window - float invoke_max_window_ms; // Max execution since last snapshot - float invoke_max_all_ms; // All-time max execution - uint64_t dispatch_count; // Total dispatches (all-time) - }; -#endif - - /// Default queue size if 0 is passed - static const size_t DEFAULT_QUEUE_SIZE = dmq::DEFAULT_QUEUE_SIZE; - - /// Constructor - /// @param threadName Name for the NuttX pthread - /// @param maxQueueSize Max number of messages in queue (0 = Default dmq::DEFAULT_QUEUE_SIZE) - /// @param fullPolicy Action when queue is full: FAULT (default), DROP, or TIMEOUT. - /// @param dispatchTimeout Duration to wait before giving up when policy is TIMEOUT. - /// @param cpuName Optional CPU/Core name grouping for monitoring tools. - NuttXThread(const char* threadName, size_t maxQueueSize = 0, FullPolicy fullPolicy = FullPolicy::FAULT, - dmq::Duration dispatchTimeout = dmq::DEFAULT_DISPATCH_TIMEOUT, const char* cpuName = ""); - - NuttXThread(const std::string& threadName, size_t maxQueueSize = 0, FullPolicy fullPolicy = FullPolicy::FAULT, - dmq::Duration dispatchTimeout = dmq::DEFAULT_DISPATCH_TIMEOUT, const std::string& cpuName = "") - : NuttXThread(threadName.c_str(), maxQueueSize, fullPolicy, dispatchTimeout, cpuName.c_str()) {} - - ~NuttXThread(); - - /// Called once to create the worker thread. If watchdogTimeout value - /// provided, the maximum watchdog interval is used. Otherwise no watchdog. - /// @param[in] watchdogTimeout - optional watchdog timeout. - /// @return TRUE if thread is created. FALSE otherwise. - bool CreateThread(std::optional watchdogTimeout = std::nullopt); - - /// Shut down the worker thread. - /// @param[in] policy - DRAIN (default) invokes every message queued before this - /// call first; DISCARD invokes only the message already running and cancels - /// the rest (see dmq::ExitPolicy). Called from the thread's own message - /// handler (a self-exit), queued messages are always discarded. - void ExitThread(ExitPolicy policy = ExitPolicy::DRAIN); - - pthread_t GetThreadId(); - static pthread_t GetCurrentThreadId(); - - /// Returns true if the calling thread is this thread - virtual bool IsCurrentThread() override; - - /// Set the pthread scheduling priority (SCHED_FIFO). Can be called - /// before or after CreateThread(). - void SetThreadPriority(int priority); - - dmq::xstring GetThreadName() { return THREAD_NAME; } - - /// Get current queue size - size_t GetQueueSize(); - - /// Sleep for a duration. - /// @param[in] timeout - the duration to sleep. - static void Sleep(dmq::Duration timeout); - - virtual bool DispatchDelegate(std::shared_ptr msg) override; - - /// @brief Register a handler invoked when DispatchDelegate() drops a message: - /// under FullPolicy::DROP (queue full, discarded immediately) or - /// FullPolicy::TIMEOUT (queue stayed full for dispatchTimeout, discarded). - /// Optional; unset by default. Called synchronously on the calling (producer) - /// thread, with the queue depth at the time of the drop. - void SetDroppedHandler(const dmq::UnicastDelegate& handler) { m_droppedHandler = handler; } - void SetDroppedHandler(dmq::UnicastDelegate&& handler) { m_droppedHandler = std::move(handler); } - - /// @brief Register a handler invoked on the worker thread before it processes - /// any message. Use it for per-thread setup (COM, a language runtime attach, - /// thread-local state, affinity). CreateThread() returns only after it completes. - /// @details Must be called while the thread is not running (before CreateThread(), - /// or after ExitThread()); calling it on a running thread faults. It runs again - /// on each CreateThread(). Messages dispatched meanwhile are queued, not lost. - void SetStartHandler(const dmq::UnicastDelegate& handler) { DMQ_ASSERT_TRUE(!m_created.load()); m_startHandler = handler; } - void SetStartHandler(dmq::UnicastDelegate&& handler) { DMQ_ASSERT_TRUE(!m_created.load()); m_startHandler = std::move(handler); } - - /// @brief Optional: hold this thread at `gate` once it is created, until - /// `gate->Open()`. Pass nullptr (the default) to start at once. - /// @details CreateThread() still runs the start handler and returns when the - /// thread is ready; the thread then processes nothing, at any priority, until - /// the gate opens. Use one gate for a group of threads so they all start - /// together after setup. See port/os/common/StartGate.h. Must be called while - /// the thread is not running; calling it on a running thread faults. - void SetStartGate(StartGate* gate) { DMQ_ASSERT_TRUE(!m_created.load()); m_startGate.Set(gate); } - - /// @brief Register a handler invoked on the worker thread after it processes - /// its last message, as the thread exits. Use it to undo SetStartHandler() setup. - /// @details Must be called while the thread is not running; calling it on a - /// running thread faults. The handler is copied when the thread starts. - /// ExitThread() from another thread returns after it completes. If the thread - /// exits itself (ExitThread() from a handler on this thread), it runs after the - /// owning NuttXThread may already be destroyed, so it must not touch that object. - void SetExitHandler(const dmq::UnicastDelegate& handler) { DMQ_ASSERT_TRUE(!m_created.load()); m_exitHandler = handler; } - void SetExitHandler(dmq::UnicastDelegate&& handler) { DMQ_ASSERT_TRUE(!m_created.load()); m_exitHandler = std::move(handler); } - - /// @brief Register a handler invoked on the worker thread when its queue has - /// been empty for `interval`, then again every `interval` while it stays empty. - /// Any message processed restarts the countdown. Use it for background work that - /// should yield to messages: polling, housekeeping, entering low power. - /// @details Must be called while the thread is not running; calling it on a - /// running thread faults. The handler and interval are copied when the thread - /// starts. Not called once ExitThread() has been requested. - /// @param[in] handler - the idle handler, or an empty delegate to disable. - /// @param[in] interval - quiet time before each call. Must be greater than zero. - /// Defaults to dmq::THREAD_IDLE_INTERVAL (DMQ_THREAD_IDLE_INTERVAL). - void SetIdleHandler(const dmq::UnicastDelegate& handler, dmq::Duration interval = dmq::THREAD_IDLE_INTERVAL) - { - DMQ_ASSERT_TRUE(!m_created.load()); - DMQ_ASSERT_TRUE(interval > dmq::Duration::zero()); - m_idleHandler = handler; - m_idleInterval = interval; - } - void SetIdleHandler(dmq::UnicastDelegate&& handler, dmq::Duration interval = dmq::THREAD_IDLE_INTERVAL) - { - DMQ_ASSERT_TRUE(!m_created.load()); - DMQ_ASSERT_TRUE(interval > dmq::Duration::zero()); - m_idleHandler = std::move(handler); - m_idleInterval = interval; - } - - /// @brief Manually update the watchdog alive timestamp. - /// @details The Run() loop refreshes the timestamp automatically on every iteration. - /// Call this from inside long-running message handlers to prevent a false watchdog - /// alarm when a handler legitimately takes longer than watchdogTimeout. - void ThreadCheck(); - - /// @brief Static method to check all registered threads for watchdog expiration. - static void WatchdogCheckAll(); - -#if defined(DMQ_DATABUS_TOOLS) - /// @brief Capture and reset windowed statistics. - ThreadStats SnapshotStats(); -#endif - -private: - NuttXThread(const NuttXThread&) = delete; - NuttXThread& operator=(const NuttXThread&) = delete; - - // NuttXThread entry point - static void* Process(void* arg); - void Run(); - - /// Check watchdog is expired. Called by WatchdogCheckAll(). - void WatchdogCheck(); - - /// Get registry head using the "Immortal" Pattern - static NuttXThread*& GetWatchdogHead(); - - /// Get registry lock using the "Immortal" Pattern - static dmq::RecursiveMutex& GetWatchdogLock(); - - const dmq::xstring THREAD_NAME; - const dmq::xstring CPU_NAME; - const size_t m_queueSize; - const FullPolicy FULL_POLICY; - const dmq::Duration m_dispatchTimeout; - int m_priority; - - pthread_t m_thread{}; - NuttXDelegateQueue m_queue; - - // Optional handler invoked when a message is dropped (FullPolicy::DROP or TIMEOUT) - dmq::UnicastDelegate m_droppedHandler; - - // Optional handlers invoked on the worker thread at start, exit and when idle - dmq::UnicastDelegate m_startHandler; - dmq::UnicastDelegate m_exitHandler; - dmq::UnicastDelegate m_idleHandler; - dmq::Duration m_idleInterval = dmq::Duration::zero(); - sem_t m_exitSem{}; // Semaphore to signal thread completion - sem_t m_goSem{}; // Posted by CreateThread() once m_thread is stored - sem_t m_startSem{}; // Posted by Run() once the start handler has run - std::atomic m_exit = false; - - // Optional start gate (SetStartGate()): its state, and whether the thread is - // held at it (the watchdog doesn't report a thread waiting by design) - StartGateClient m_startGate; - std::atomic m_discard = false; // ExitPolicy::DISCARD: cancel queued messages instead of invoking - std::atomic m_created = false; - bool* m_selfExitPtr = nullptr; - - // Set when the thread terminates itself (ExitThread() called from within - // its own dispatched callback). A self-exiting thread cannot join or free - // its own stack, so a later ExitThread() call (typically from - // ~NuttXThread(), made from a different thread context) checks this to - // skip the message-send/semaphore handshake and go straight to the - // pthread_join() cleanup instead. - std::atomic m_selfExited = false; - - // Stack size in bytes, applied via pthread_attr_setstacksize() before - // pthread_create(); NuttX allocates and frees the stack itself, unlike - // the Zephyr/CMSIS-RTOS2 ports which must k_aligned_alloc()/k_free() it - // manually. - static const size_t STACK_SIZE = dmq::NUTTX_STACK_BYTES; // DMQ_NUTTX_STACK_BYTES - - // Watchdog related members - std::atomic m_lastAliveTime{dmq::TimePoint()}; - std::atomic m_watchdogTimeout{dmq::Duration(0)}; - NuttXThread* m_watchdogNext = nullptr; - -#if defined(DMQ_DATABUS_TOOLS) - pthread_mutex_t m_statMutex; // Mutex to protect statistics - // Monitoring statistics members - size_t m_queueDepthMaxWindow = 0; - size_t m_queueDepthMaxAll = 0; - - dmq::Duration m_latencyTotalWindow = dmq::Duration(0); - uint32_t m_latencyCountWindow = 0; - dmq::Duration m_latencyMaxWindow = dmq::Duration(0); - dmq::Duration m_latencyMaxAll = dmq::Duration(0); - - dmq::Duration m_invokeTotalWindow = dmq::Duration(0); - uint32_t m_invokeCountWindow = 0; - dmq::Duration m_invokeMaxWindow = dmq::Duration(0); - dmq::Duration m_invokeMaxAll = dmq::Duration(0); - - uint64_t m_dispatchCountAll = 0; -#endif -}; - -/// @brief Backward-compatible name: existing code referencing dmq::os::Thread -/// keeps compiling unchanged against the NuttX port. -using Thread = NuttXThread; - -} // namespace dmq::os - -#endif // _THREAD_NUTTX_H diff --git a/DelegateMQ/port/os/posix/PosixThread.cpp b/DelegateMQ/port/os/posix/PosixThread.cpp deleted file mode 100644 index 67f7fd0..0000000 --- a/DelegateMQ/port/os/posix/PosixThread.cpp +++ /dev/null @@ -1,723 +0,0 @@ -// Compiles to nothing unless DMQ_THREAD_POSIX is selected, so every DelegateMQ source -// file can be added to a build (see src/DelegateMQ.cpp). -#include "delegate/DelegateSelect.h" -#if defined(DMQ_THREAD_POSIX) - -#include "DelegateMQ.h" -#include "PosixThread.h" -#include "port/os/common/ThreadHooks.h" -#include "extras/util/Fault.h" -#include -#include - -// Thread-local pointer into Process()'s stack frame. Set non-null only while -// Process() is running on a given thread. ExitThread() writes true through it -// when the thread destroys its own owning object so Process() can exit without -// touching freed members. -static thread_local bool* t_self_exit = nullptr; - -namespace dmq::os { - -using namespace dmq::util; - -//---------------------------------------------------------------------------- -// MakeAbsTimeout -//---------------------------------------------------------------------------- -void PosixThread::MakeAbsTimeout(dmq::Duration timeout, struct timespec& ts) -{ - clock_gettime(CLOCK_MONOTONIC, &ts); - long long ns = std::chrono::duration_cast(timeout).count(); - ts.tv_sec += static_cast(ns / 1000000000LL); - ts.tv_nsec += static_cast(ns % 1000000000LL); - if (ts.tv_nsec >= 1000000000L) { - ts.tv_nsec -= 1000000000L; - ts.tv_sec += 1; - } -} - -//---------------------------------------------------------------------------- -// Thread -//---------------------------------------------------------------------------- -PosixThread::PosixThread(const char* threadName, size_t maxQueueSize, FullPolicy fullPolicy, dmq::Duration dispatchTimeout, const char* cpuName) - : THREAD_NAME(threadName) - , CPU_NAME(cpuName) - , MAX_QUEUE_SIZE(maxQueueSize == 0 ? dmq::THREAD_DESKTOP_QUEUE_SIZE : maxQueueSize) - , FULL_POLICY(fullPolicy) - , m_dispatchTimeout(dispatchTimeout) - , m_exit(false) -{ - pthread_mutex_init(&m_startMutex, nullptr); - pthread_cond_init(&m_startCv, nullptr); - pthread_mutex_init(&m_mutex, nullptr); - - // Both condition variables use CLOCK_MONOTONIC (not the default CLOCK_REALTIME) - // so pthread_cond_timedwait() deadlines are immune to wall-clock jumps (NTP - // steps, manual clock changes) -- consistent with dmq::Clock (std::chrono:: - // steady_clock) being what dmq::Duration/dmq::TimePoint are measured against. - pthread_condattr_t attr; - pthread_condattr_init(&attr); - pthread_condattr_setclock(&attr, CLOCK_MONOTONIC); - pthread_cond_init(&m_cvNotEmpty, &attr); - pthread_cond_init(&m_cvNotFull, &attr); - pthread_condattr_destroy(&attr); -} - -//---------------------------------------------------------------------------- -// ~Thread -//---------------------------------------------------------------------------- -PosixThread::~PosixThread() -{ - ExitThread(); - - { - const std::lock_guard lock(GetWatchdogLock()); - PosixThread** pp = &GetWatchdogHead(); - while (*pp != nullptr) - { - if (*pp == this) - { - *pp = this->m_watchdogNext; - this->m_watchdogNext = nullptr; - break; - } - pp = &((*pp)->m_watchdogNext); - } - } - - pthread_cond_destroy(&m_cvNotFull); - pthread_cond_destroy(&m_cvNotEmpty); - pthread_mutex_destroy(&m_mutex); - pthread_cond_destroy(&m_startCv); - pthread_mutex_destroy(&m_startMutex); -} - -//---------------------------------------------------------------------------- -// CreateThread -//---------------------------------------------------------------------------- -bool PosixThread::CreateThread(std::optional watchdogTimeout) -{ - if (!m_threadCreated) - { - m_exit = false; - // Held from creation, so the watchdog never sees a gated thread as hung - // before it reaches the gate (e.g. created before the scheduler runs) - m_startGate.OnCreate(); - // Set before the thread exists: its loop reads the timeout before its - // first queue wait, and an idle thread waits forever with no timeout - m_lastAliveTime.store(Timer::GetNow()); - m_watchdogTimeout.store(watchdogTimeout.value_or(dmq::Duration(0))); - m_started = false; - - // Held until m_thread is stored and named. Process() takes this lock - // before running the start handler, which may call IsCurrentThread() or - // dispatch to this thread (both read m_thread). - pthread_mutex_lock(&m_mutex); - int rc = pthread_create(&m_thread, nullptr, &PosixThread::ThreadEntry, this); - if (rc != 0) { - pthread_mutex_unlock(&m_mutex); - m_watchdogTimeout.store(dmq::Duration(0)); // no thread to refresh the heartbeat - m_startGate.OnCreateFailed(); - return false; - } - m_threadCreated = true; - - // Set the thread name for debugging (glibc extension, name truncated to - // 15 chars + NUL -- Linux's TASK_COMM_LEN limit). Not part of the POSIX - // standard, so this is opportunistic and guarded rather than depended on. -#if defined(__linux__) - pthread_setname_np(m_thread, THREAD_NAME.substr(0, 15).c_str()); -#endif - pthread_mutex_unlock(&m_mutex); - - // Wait for the thread to enter the Process method - pthread_mutex_lock(&m_startMutex); - while (!m_started) - pthread_cond_wait(&m_startCv, &m_startMutex); - pthread_mutex_unlock(&m_startMutex); - - m_lastAliveTime.store(Timer::GetNow()); - - // Caller wants a watchdog timer? - if (watchdogTimeout.has_value()) - { - - // Add to watchdog registry if not already present - { - dmq::LockGuard lock(GetWatchdogLock()); - bool found = false; - PosixThread* p = GetWatchdogHead(); - while (p != nullptr) - { - if (p == this) - { - found = true; - break; - } - p = p->m_watchdogNext; - } - if (!found) - { - m_watchdogNext = GetWatchdogHead(); - GetWatchdogHead() = this; - } - } - } - } - return true; -} - -//---------------------------------------------------------------------------- -// ThreadEntry -//---------------------------------------------------------------------------- -void* PosixThread::ThreadEntry(void* arg) -{ - static_cast(arg)->Process(); - return nullptr; -} - -//---------------------------------------------------------------------------- -// GetThreadId -//---------------------------------------------------------------------------- -pthread_t PosixThread::GetThreadId() -{ - if (!m_threadCreated) - throw std::invalid_argument("Thread pointer is null"); - - return m_thread; -} - -//---------------------------------------------------------------------------- -// GetCurrentThreadId -//---------------------------------------------------------------------------- -pthread_t PosixThread::GetCurrentThreadId() -{ - return pthread_self(); -} - -//---------------------------------------------------------------------------- -// IsCurrentThread -//---------------------------------------------------------------------------- -bool PosixThread::IsCurrentThread() -{ - if (!m_threadCreated) - return false; - - return pthread_equal(pthread_self(), m_thread) != 0; -} - -//---------------------------------------------------------------------------- -// GetQueueSize -//---------------------------------------------------------------------------- -size_t PosixThread::GetQueueSize() -{ - pthread_mutex_lock(&m_mutex); - size_t size = (m_highQueue.size() + m_normalQueue.size()); - pthread_mutex_unlock(&m_mutex); - return size; -} - -void PosixThread::Sleep(dmq::Duration timeout) { - dmq::ThisThread::sleep_for(timeout); -} - -//---------------------------------------------------------------------------- -// ExitThread -//---------------------------------------------------------------------------- -void PosixThread::ExitThread(ExitPolicy policy) -{ - if (!m_threadCreated) return; - - auto threadMsg = xmake_shared(MSG_EXIT_THREAD, nullptr); - - // Messages taken off the queues without being invoked; canceled outside the lock - decltype(m_highQueue) discardedHigh; - decltype(m_normalQueue) discardedNormal; - - pthread_mutex_lock(&m_mutex); - - // Set exit flag INSIDE lock before notifying. - // This ensures that when a blocked producer wakes up, it sees m_exit == true immediately. - m_exit.store(true); - - // DISCARD: empty the queues so the exit message is the next one processed - if (policy == ExitPolicy::DISCARD) - { - discardedHigh.swap(m_highQueue); - discardedNormal.swap(m_normalQueue); - } - - // Explicitly allow Exit message to bypass the MAX_QUEUE_SIZE limit. - // We do not wait on m_cvNotFull here to prevent deadlock during shutdown. - // Queued last, so DRAIN invokes every message already queued first. - m_normalQueue.push_back(threadMsg); - - // Wake up consumers - pthread_cond_signal(&m_cvNotEmpty); - // Wake up blocked producers (DispatchDelegate) - pthread_cond_broadcast(&m_cvNotFull); - - pthread_mutex_unlock(&m_mutex); - - CancelAll(discardedHigh); - CancelAll(discardedNormal); - - // A thread held at its start gate isn't waiting on its queue: wake it so it - // sees the exit flag (set above) and leaves. Never touches the gate itself, - // which may be destroyed once the thread is released. - m_startGate.Wake(); - - // Prevent deadlock if ExitThread is called from within the thread itself - if (!pthread_equal(pthread_self(), m_thread)) - { - pthread_join(m_thread, nullptr); - } - else - { - // We are killing ourselves. Detach so the OS cleans up the thread naturally. - pthread_detach(m_thread); - // Signal Process() (running on this thread) to exit without touching - // 'this' again — the owning object is about to be freed. - if (t_self_exit) *t_self_exit = true; - m_startGate.Leave(); // exited from its start handler: never reaches the gate - } - - // The thread has finished (or, on a self-exit, is in its last handler): - // stop watchdog checks. Not earlier, so a thread that hangs while - // ExitThread() waits for it is still reported. - m_watchdogTimeout.store(dmq::Duration(0)); - - pthread_mutex_lock(&m_mutex); - m_threadCreated = false; - // Normally empty. After a self-exit the loop returns without draining, - // so anything still queued is discarded here. - discardedHigh.swap(m_highQueue); - discardedNormal.swap(m_normalQueue); - // Final cleanup notification - pthread_cond_broadcast(&m_cvNotFull); - pthread_mutex_unlock(&m_mutex); - - CancelAll(discardedHigh); - CancelAll(discardedNormal); -} - -//---------------------------------------------------------------------------- -// DispatchDelegate -//---------------------------------------------------------------------------- -bool PosixThread::DispatchDelegate(std::shared_ptr msg) -{ - if (m_exit.load() || !m_threadCreated) return false; - - pthread_mutex_lock(&m_mutex); - - // [BACK PRESSURE / DROP / FAULT / TIMEOUT LOGIC] - if (MAX_QUEUE_SIZE > 0 && (m_highQueue.size() + m_normalQueue.size()) >= MAX_QUEUE_SIZE) - { - if (FULL_POLICY == FullPolicy::DROP) - { - size_t depth = m_highQueue.size() + m_normalQueue.size(); - pthread_mutex_unlock(&m_mutex); - if (m_droppedHandler) - m_droppedHandler(depth); - return false; // silently discard - } - - if (FULL_POLICY == FullPolicy::FAULT) - { - pthread_mutex_unlock(&m_mutex); - printf("[Thread] CRITICAL: Queue full on thread '%s'! TRIGGERING FAULT.\n", THREAD_NAME.c_str()); - DMQ_ASSERT_TRUE(false); - return false; - } - - if (FULL_POLICY == FullPolicy::TIMEOUT) - { - struct timespec ts; - MakeAbsTimeout(m_dispatchTimeout, ts); - bool hasSpace = false; - while (true) - { - if ((m_highQueue.size() + m_normalQueue.size()) < MAX_QUEUE_SIZE || m_exit.load()) - { - hasSpace = true; - break; - } - int rc = pthread_cond_timedwait(&m_cvNotFull, &m_mutex, &ts); - if (rc == ETIMEDOUT) - { - hasSpace = false; - break; - } - } - if (!hasSpace) - { - size_t depth = m_highQueue.size() + m_normalQueue.size(); - pthread_mutex_unlock(&m_mutex); - printf("[Thread] WARNING: Queue post timed out on '%s' — possible deadlock. Message dropped.\n", THREAD_NAME.c_str()); - if (m_droppedHandler) - m_droppedHandler(depth); - return false; - } - // space found (or exit signaled) — fall through to push/abort check below - } - } - - // If using XALLOCATOR explicit operator new required. See xallocator.h. - auto threadMsg = xmake_shared(MSG_DISPATCH_DELEGATE, msg); -#if defined(DMQ_DATABUS_TOOLS) - threadMsg->SetEnqueueTime(Timer::GetNow()); -#endif - - // If we woke up because of exit (or exit happened while waiting), abort - if (m_exit.load()) - { - pthread_mutex_unlock(&m_mutex); - return false; - } - - if (threadMsg->GetPriority() == dmq::Priority::HIGH) - m_highQueue.push_back(threadMsg); - else - m_normalQueue.push_back(threadMsg); - -#if defined(DMQ_DATABUS_TOOLS) - // Update monitoring stats - size_t currentDepth = (m_highQueue.size() + m_normalQueue.size()); - if (currentDepth > m_queueDepthMaxWindow) m_queueDepthMaxWindow = currentDepth; - if (currentDepth > m_queueDepthMaxAll) m_queueDepthMaxAll = currentDepth; -#endif - - pthread_cond_signal(&m_cvNotEmpty); - pthread_mutex_unlock(&m_mutex); - - return true; -} - -//---------------------------------------------------------------------------- -// Process -//---------------------------------------------------------------------------- -void PosixThread::Process() -{ - // selfExit is set by ExitThread() when the thread destroys its own owner. - // It lives on this stack frame so it remains valid even after 'this' is freed. - bool selfExit = false; - t_self_exit = &selfExit; - - // Exit and idle handlers are copied onto this stack frame so they work on - // every return path, including a self-exit where 'this' may already be freed. - ThreadExitGuard exitGuard(m_exitHandler); - ThreadIdleTimer idle(m_idleHandler, m_idleInterval); - - // Wait for CreateThread() to finish storing m_thread - pthread_mutex_lock(&m_mutex); - pthread_mutex_unlock(&m_mutex); - - // dmq::ThisThread::GetCurrent() returns this thread from here on. Declared - // after exitGuard, so it is cleared again before the exit handler runs. - dmq::CurrentThreadScope currentScope(this); - - if (m_startHandler) - m_startHandler(); - - // A start handler that exited this thread (ExitThread() on itself) leaves - // right after the signal below: once CreateThread() returns, the Thread may - // be destroyed, so nothing after the signal may touch 'this'. - const bool exitedInStart = selfExit; - - // Signal that the thread has started processing to notify CreateThread - pthread_mutex_lock(&m_startMutex); - m_started = true; - pthread_cond_signal(&m_startCv); - pthread_mutex_unlock(&m_startMutex); - if (exitedInStart) { t_self_exit = nullptr; return; } - - // Optional start gate: wait here, ready but processing nothing, until it opens - if (m_startGate.Enabled()) - { - const bool opened = m_startGate.Wait(m_exit); - m_lastAliveTime.store(Timer::GetNow()); // before Passed(): no stale watchdog read - m_startGate.Passed(); - if (!opened) - { - // ExitThread() while held: leave without running any message. - // ExitThread() cancels what is still queued once this thread ends. - t_self_exit = nullptr; - return; - } - } - - while (!selfExit) - { - dmq::Duration watchdogTimeout; - { - m_lastAliveTime.store(Timer::GetNow()); - watchdogTimeout = m_watchdogTimeout.load(); - } - - std::shared_ptr msg; - - pthread_mutex_lock(&m_mutex); - - auto queueReady = [this]() { return !(m_highQueue.empty() && m_normalQueue.empty()) || m_exit.load(); }; - - // Wait for message to be added to the queue. - // If watchdog active, use a finite timeout so we can periodically update - // m_lastAliveTime while idle. If an idle handler is set, wake no later - // than when it is due. Otherwise, block forever (negative wait time). - dmq::Duration waitTime = idle.WaitTime(watchdogTimeout.count() > 0 ? watchdogTimeout / dmq::WATCHDOG_HEARTBEAT_DIVISOR : dmq::Duration(-1)); - if (waitTime >= dmq::Duration::zero()) - { - struct timespec ts; - MakeAbsTimeout(waitTime, ts); - while (!queueReady()) - { - int rc = pthread_cond_timedwait(&m_cvNotEmpty, &m_mutex, &ts); - if (rc == ETIMEDOUT) - break; // Timeout reached, break to update m_lastAliveTime - } - } - else - { - while (!queueReady()) - pthread_cond_wait(&m_cvNotEmpty, &m_mutex); - } - - // Always update alive time immediately after waking up - m_lastAliveTime.store(Timer::GetNow()); - - // If queue still empty, either exit (if requested), run the idle handler - // if it is due, or loop again (timeout). - if (m_highQueue.empty() && m_normalQueue.empty()) - { - bool doExit = m_exit.load(); - pthread_mutex_unlock(&m_mutex); - if (doExit) { t_self_exit = nullptr; return; } - if (idle.IsDue()) - idle.Run(); - continue; - } - - // Get highest priority message within queue - if (!m_highQueue.empty()) { - msg = m_highQueue.front(); - m_highQueue.pop_front(); - } else { - msg = m_normalQueue.front(); - m_normalQueue.pop_front(); - } - - // Unblock producers now that space is available - if (MAX_QUEUE_SIZE > 0) - pthread_cond_signal(&m_cvNotFull); - - pthread_mutex_unlock(&m_mutex); - - switch (msg->GetId()) - { - case MSG_DISPATCH_DELEGATE: - { -#if defined(DMQ_DATABUS_TOOLS) - // Update latency stats before invoking - dmq::Duration latency = Timer::GetNow() - msg->GetEnqueueTime(); - { - pthread_mutex_lock(&m_mutex); - m_latencyTotalWindow += latency; - m_latencyCountWindow++; - if (latency > m_latencyMaxWindow) m_latencyMaxWindow = latency; - if (latency > m_latencyMaxAll) m_latencyMaxAll = latency; - m_dispatchCountAll++; - pthread_mutex_unlock(&m_mutex); - } -#endif - - auto delegateMsg = msg->GetData(); - DMQ_ASSERT_TRUE(delegateMsg); - auto invoker = delegateMsg->GetInvoker(); - DMQ_ASSERT_TRUE(invoker); - -#if defined(DMQ_DATABUS_TOOLS) - dmq::TimePoint start = Timer::GetNow(); -#endif -#if defined(__cpp_exceptions) && !defined(DMQ_ASSERTS) - try { - bool success = invoker->Invoke(delegateMsg); - if (!selfExit) DMQ_ASSERT_TRUE(success); - } - catch (const std::bad_alloc& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled bad_alloc in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::invalid_argument& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled invalid_argument in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::runtime_error& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled runtime_error in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::exception& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled exception in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (...) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled unknown exception in delegate callback." << std::endl; - DMQ_ASSERT(); - } -#else - bool success = invoker->Invoke(delegateMsg); - if (!selfExit) DMQ_ASSERT_TRUE(success); -#endif - if (selfExit) { - t_self_exit = nullptr; - return; - } -#if defined(DMQ_DATABUS_TOOLS) - dmq::Duration invokeTime = Timer::GetNow() - start; - if (!selfExit) { - pthread_mutex_lock(&m_mutex); - m_invokeTotalWindow += invokeTime; - m_invokeCountWindow++; - if (invokeTime > m_invokeMaxWindow) m_invokeMaxWindow = invokeTime; - if (invokeTime > m_invokeMaxAll) m_invokeMaxAll = invokeTime; - pthread_mutex_unlock(&m_mutex); - } -#endif - break; - } - - case MSG_EXIT_THREAD: - { - t_self_exit = nullptr; - return; - } - - default: - { - DMQ_ASSERT(); - break; - } - } - - // Any message restarts the idle countdown - idle.Restart(); - - // msg goes out of scope here — may trigger self-destruction of 'this'. - // After this point do not access any member; check selfExit in while(). - } - t_self_exit = nullptr; -} - -//---------------------------------------------------------------------------- -// WatchdogCheckAll -//---------------------------------------------------------------------------- -void PosixThread::WatchdogCheckAll() -{ - const std::lock_guard lock(GetWatchdogLock()); - PosixThread* p = GetWatchdogHead(); - while (p != nullptr) - { - p->WatchdogCheck(); - p = p->m_watchdogNext; - } -} - -//---------------------------------------------------------------------------- -// WatchdogCheck -//---------------------------------------------------------------------------- -void PosixThread::WatchdogCheck() -{ - if (m_startGate.IsHeld()) - return; // held at its start gate by design, not hung - - auto now = Timer::GetNow(); - auto lastAlive = m_lastAliveTime.load(); - auto watchdogTimeout = m_watchdogTimeout.load(); - - if (watchdogTimeout.count() > 0) - { - auto delta = now - lastAlive; - if (delta > watchdogTimeout) - { - WatchdogHandler(THREAD_NAME.c_str()); - } - } -} - -//---------------------------------------------------------------------------- -// ThreadCheck -//---------------------------------------------------------------------------- -void PosixThread::ThreadCheck() -{ - m_lastAliveTime.store(Timer::GetNow()); -} - -//---------------------------------------------------------------------------- -// GetWatchdogHead -//---------------------------------------------------------------------------- -PosixThread*& PosixThread::GetWatchdogHead() -{ - static PosixThread* head = nullptr; - return head; -} - -//---------------------------------------------------------------------------- -// GetWatchdogLock -//---------------------------------------------------------------------------- -dmq::RecursiveMutex& PosixThread::GetWatchdogLock() -{ - static dmq::RecursiveMutex* lock = new dmq::RecursiveMutex(); - return *lock; -} - -#if defined(DMQ_DATABUS_TOOLS) -//---------------------------------------------------------------------------- -// SnapshotStats -//---------------------------------------------------------------------------- -PosixThread::ThreadStats PosixThread::SnapshotStats() -{ - pthread_mutex_lock(&m_mutex); - ThreadStats stats; - stats.cpu_name = CPU_NAME; - stats.thread_name = THREAD_NAME; - stats.queue_depth = (m_highQueue.size() + m_normalQueue.size()); - stats.queue_depth_max_window = m_queueDepthMaxWindow; - stats.queue_depth_max_all = m_queueDepthMaxAll; - stats.queue_size_limit = MAX_QUEUE_SIZE; - - if (m_latencyCountWindow > 0) { - stats.latency_avg_ms = (float)std::chrono::duration_cast(m_latencyTotalWindow).count() / (static_cast(m_latencyCountWindow) * 1000.0f); - } else { - stats.latency_avg_ms = 0.0f; - } - - stats.latency_max_window_ms = (float)std::chrono::duration_cast(m_latencyMaxWindow).count() / 1000.0f; - stats.latency_max_all_ms = (float)std::chrono::duration_cast(m_latencyMaxAll).count() / 1000.0f; - - if (m_invokeCountWindow > 0) { - stats.invoke_avg_ms = (float)std::chrono::duration_cast(m_invokeTotalWindow).count() / (static_cast(m_invokeCountWindow) * 1000.0f); - } else { - stats.invoke_avg_ms = 0.0f; - } - - stats.invoke_max_window_ms = (float)std::chrono::duration_cast(m_invokeMaxWindow).count() / 1000.0f; - stats.invoke_max_all_ms = (float)std::chrono::duration_cast(m_invokeMaxAll).count() / 1000.0f; - - stats.dispatch_count = m_dispatchCountAll; - - // Reset windowed stats - m_queueDepthMaxWindow = 0; - m_latencyTotalWindow = dmq::Duration(0); - m_latencyCountWindow = 0; - m_latencyMaxWindow = dmq::Duration(0); - - m_invokeTotalWindow = dmq::Duration(0); - m_invokeCountWindow = 0; - m_invokeMaxWindow = dmq::Duration(0); - - pthread_mutex_unlock(&m_mutex); - return stats; -} -#endif - -} // namespace dmq::os - -#endif // DMQ_THREAD_POSIX diff --git a/DelegateMQ/port/os/posix/PosixThread.h b/DelegateMQ/port/os/posix/PosixThread.h deleted file mode 100644 index 41d8806..0000000 --- a/DelegateMQ/port/os/posix/PosixThread.h +++ /dev/null @@ -1,329 +0,0 @@ -#ifndef _THREAD_POSIX_H -#define _THREAD_POSIX_H - -/// @file PosixThread.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief Raw POSIX implementation of the DelegateMQ IThread interface. -/// -/// @details -/// This class provides a native POSIX implementation of the `IThread` interface using -/// `pthread_create`/`pthread_mutex_t`/`pthread_cond_t` directly, rather than going through -/// `std::thread`/`std::mutex`/`std::condition_variable` the way `StdlibThread` does. It -/// creates a dedicated worker thread with an event loop capable of processing asynchronous -/// delegates and system messages -- mirroring `Win32Thread`'s relationship to `StdlibThread` -/// (native OS API instead of the C++ standard library), but for POSIX. -/// -/// `dmq::Mutex`, `dmq::ConditionVariable`, `dmq::Clock`, and `dmq::ThisThread` are NOT -/// reimplemented here -- they still resolve to `std::mutex`/`std::condition_variable`/ -/// `std::chrono::steady_clock`/`std::this_thread` (see `DelegateOpt.h`'s -/// `DMQ_THREAD_STDLIB || DMQ_THREAD_WIN32 || DMQ_THREAD_QT || DMQ_THREAD_POSIX` branches), -/// since those are already thin, efficient wrappers over these same POSIX primitives under -/// glibc/libstdc++. This file is the only thing `DMQ_THREAD_POSIX` adds. -/// -/// **Key Features:** -/// * **Priority Queue:** One FIFO `std::deque` per priority level, so high-priority -/// delegate messages (e.g. system signals) are processed before normal ones, and -/// messages of the same priority are processed in the order they were dispatched. -/// * **Queue Full Policy:** Configurable `FullPolicy` (DROP, FAULT, or TIMEOUT), always enforced -- -/// `maxQueueSize == 0` falls back to `dmq::THREAD_DESKTOP_QUEUE_SIZE` rather than disabling -/// the cap, since this port backs its queue with a plain `std::deque` and would otherwise -/// grow without bound if the destination thread is dead/stuck. TIMEOUT waits up to -/// `dispatchTimeout` for the consumer before logging and dropping; DROP silently discards -/// immediately. FAULT (the default) triggers a system fault. -/// * **Monotonic Timed Waits:** The condition variables are created with `pthread_condattr_setclock( -/// CLOCK_MONOTONIC)` so `pthread_cond_timedwait()` deadlines are immune to `CLOCK_REALTIME` -/// jumps (NTP steps, manual clock changes) -- unlike a naive POSIX cv using the default clock. -/// `pthread_condattr_setclock()` itself is a common POSIX extension (present on Linux's glibc -/// and musl) rather than a portable POSIX-standard guarantee -- e.g. not implemented on Darwin/ -/// macOS -- which is the one place this port leans on more than the base POSIX spec. -/// * **Watchdog Integration:** Includes a built-in heartbeat mechanism. If the thread loop -/// stalls (deadlock or infinite loop), the watchdog timer detects the failure. -/// * **Synchronized Start:** Uses a dedicated mutex/condition-variable pair to ensure the -/// thread is fully initialized and running before `CreateThread()` returns. -/// * **Start Gate:** Optional `SetStartGate(StartGate*)`, called before `CreateThread()`, -/// holds the thread ready but processing no messages, at any priority, until -/// `StartGate::Open()` releases every thread sharing the gate at once. - -#include "delegate/IThread.h" -#include "delegate/UnicastDelegate.h" -#include "./extras/util/Timer.h" -#include "port/os/common/ThreadMsg.h" -#include "port/os/common/StartGate.h" -#include -#include -#include -#include -#include - -namespace dmq::os { - -/// @brief Policy applied when the thread message queue is full. See dmq::FullPolicy -/// in DelegateOpt.h for the canonical definition, shared by every dmq::os::Thread port. -using FullPolicy = dmq::FullPolicy; - -/// @brief What ExitThread() does with queued messages. See dmq::ExitPolicy in DelegateOpt.h. -using ExitPolicy = dmq::ExitPolicy; - -/// @brief Raw POSIX (pthreads) thread for Linux and other POSIX systems. -/// @details The PosixThread class creates a worker thread capable of dispatching and -/// invoking asynchronous delegates. -class PosixThread : public dmq::IThread -{ - XALLOCATOR -public: -#if defined(DMQ_DATABUS_TOOLS) - /// @brief Statistics captured for thread monitoring. - struct ThreadStats { - dmq::xstring cpu_name; - dmq::xstring thread_name; - size_t queue_depth; // Current depth - size_t queue_depth_max_window;// Max depth since last snapshot - size_t queue_depth_max_all; // All-time max depth - size_t queue_size_limit; // Max allowed - float latency_avg_ms; // Avg wait in window - float latency_max_window_ms; // Max wait since last snapshot - float latency_max_all_ms; // All-time max wait - float invoke_avg_ms; // Avg execution in window - float invoke_max_window_ms; // Max execution since last snapshot - float invoke_max_all_ms; // All-time max execution - uint64_t dispatch_count; // Total dispatches (all-time) - }; -#endif - - /// Constructor - /// @param threadName The name of the thread for debugging. - /// @param maxQueueSize The maximum number of messages allowed in the queue. - /// 0 falls back to dmq::THREAD_DESKTOP_QUEUE_SIZE -- a high-water-mark - /// safety net, not a throughput limiter, against unbounded growth if - /// the destination thread is dead/stuck. - /// @param fullPolicy When the queue is full: FAULT (default), DROP, or TIMEOUT. - /// @param dispatchTimeout Duration to wait before giving up when policy is TIMEOUT. - /// @param cpuName Optional CPU/Core name grouping for monitoring tools. - PosixThread(const char* threadName, size_t maxQueueSize = 0, FullPolicy fullPolicy = FullPolicy::FAULT, - dmq::Duration dispatchTimeout = dmq::DEFAULT_DISPATCH_TIMEOUT, const char* cpuName = ""); - PosixThread(const std::string& threadName, size_t maxQueueSize = 0, FullPolicy fullPolicy = FullPolicy::FAULT, - dmq::Duration dispatchTimeout = dmq::DEFAULT_DISPATCH_TIMEOUT, const std::string& cpuName = "") - : PosixThread(threadName.c_str(), maxQueueSize, fullPolicy, dispatchTimeout, cpuName.c_str()) {} - - /// Destructor - virtual ~PosixThread(); - - /// Called once to create the worker thread. If watchdogTimeout value - /// provided, the maximum watchdog interval is used. Otherwise no watchdog. - /// @param[in] watchdogTimeout - optional watchdog timeout. - /// @return TRUE if thread is created. FALSE otherwise. - bool CreateThread(std::optional watchdogTimeout = std::nullopt); - - /// Shut down the worker thread. - /// @param[in] policy - DRAIN (default) invokes every message queued before this - /// call first; DISCARD invokes only the message already running and cancels - /// the rest (see dmq::ExitPolicy). Called from the thread's own message - /// handler (a self-exit), queued messages are always discarded. - void ExitThread(ExitPolicy policy = ExitPolicy::DRAIN); - - /// Get the ID of this thread instance - pthread_t GetThreadId(); - - /// Get the ID of the currently executing thread - static pthread_t GetCurrentThreadId(); - - /// Returns true if the calling thread is this thread - virtual bool IsCurrentThread() override; - - /// Get thread name - dmq::xstring GetThreadName() { return THREAD_NAME; } - - /// Get size of thread message queue. - size_t GetQueueSize(); - - /// Sleep for a duration. - /// @param[in] timeout - the duration to sleep. - static void Sleep(dmq::Duration timeout); - - /// Dispatch and invoke a delegate target on the destination thread. - /// @param[in] msg - Delegate message containing target function - /// arguments. - virtual bool DispatchDelegate(std::shared_ptr msg) override; - - /// @brief Register a handler invoked when DispatchDelegate() drops a message: - /// under FullPolicy::DROP (queue full, discarded immediately) or - /// FullPolicy::TIMEOUT (queue stayed full for dispatchTimeout, discarded). - /// Optional; unset by default. Called synchronously on the calling (producer) - /// thread, with the queue depth at the time of the drop. - void SetDroppedHandler(const dmq::UnicastDelegate& handler) { m_droppedHandler = handler; } - void SetDroppedHandler(dmq::UnicastDelegate&& handler) { m_droppedHandler = std::move(handler); } - - /// @brief Register a handler invoked on the worker thread before it processes - /// any message. Use it for per-thread setup (COM, a language runtime attach, - /// thread-local state, affinity). CreateThread() returns only after it completes. - /// @details Must be called while the thread is not running (before CreateThread(), - /// or after ExitThread()); calling it on a running thread faults. It runs again - /// on each CreateThread(). Messages dispatched meanwhile are queued, not lost. - void SetStartHandler(const dmq::UnicastDelegate& handler) { DMQ_ASSERT_TRUE(!m_threadCreated); m_startHandler = handler; } - void SetStartHandler(dmq::UnicastDelegate&& handler) { DMQ_ASSERT_TRUE(!m_threadCreated); m_startHandler = std::move(handler); } - - /// @brief Optional: hold this thread at `gate` once it is created, until - /// `gate->Open()`. Pass nullptr (the default) to start at once. - /// @details CreateThread() still runs the start handler and returns when the - /// thread is ready; the thread then processes nothing, at any priority, until - /// the gate opens. Use one gate for a group of threads so they all start - /// together after setup. See port/os/common/StartGate.h. Must be called while - /// the thread is not running; calling it on a running thread faults. - void SetStartGate(StartGate* gate) { DMQ_ASSERT_TRUE(!m_threadCreated); m_startGate.Set(gate); } - - /// @brief Register a handler invoked on the worker thread after it processes - /// its last message, as the thread exits. Use it to undo SetStartHandler() setup. - /// @details Must be called while the thread is not running; calling it on a - /// running thread faults. The handler is copied when the thread starts. - /// ExitThread() from another thread returns after it completes. If the thread - /// exits itself (ExitThread() from a handler on this thread), it runs after the - /// owning PosixThread may already be destroyed, so it must not touch that object. - void SetExitHandler(const dmq::UnicastDelegate& handler) { DMQ_ASSERT_TRUE(!m_threadCreated); m_exitHandler = handler; } - void SetExitHandler(dmq::UnicastDelegate&& handler) { DMQ_ASSERT_TRUE(!m_threadCreated); m_exitHandler = std::move(handler); } - - /// @brief Register a handler invoked on the worker thread when its queue has - /// been empty for `interval`, then again every `interval` while it stays empty. - /// Any message processed restarts the countdown. Use it for background work that - /// should yield to messages: polling, housekeeping, entering low power. - /// @details Must be called while the thread is not running; calling it on a - /// running thread faults. The handler and interval are copied when the thread - /// starts. Not called once ExitThread() has been requested. - /// @param[in] handler - the idle handler, or an empty delegate to disable. - /// @param[in] interval - quiet time before each call. Must be greater than zero. - /// Defaults to dmq::THREAD_IDLE_INTERVAL (DMQ_THREAD_IDLE_INTERVAL). - void SetIdleHandler(const dmq::UnicastDelegate& handler, dmq::Duration interval = dmq::THREAD_IDLE_INTERVAL) - { - DMQ_ASSERT_TRUE(!m_threadCreated); - DMQ_ASSERT_TRUE(interval > dmq::Duration::zero()); - m_idleHandler = handler; - m_idleInterval = interval; - } - void SetIdleHandler(dmq::UnicastDelegate&& handler, dmq::Duration interval = dmq::THREAD_IDLE_INTERVAL) - { - DMQ_ASSERT_TRUE(!m_threadCreated); - DMQ_ASSERT_TRUE(interval > dmq::Duration::zero()); - m_idleHandler = std::move(handler); - m_idleInterval = interval; - } - - /// @brief Manually update the watchdog alive timestamp. - /// @details The Process() loop refreshes the timestamp automatically on every iteration. - /// Call this from inside long-running message handlers to prevent a false watchdog - /// alarm when a handler legitimately takes longer than watchdogTimeout. - void ThreadCheck(); - - /// @brief Static method to check all registered threads for watchdog expiration. - static void WatchdogCheckAll(); - -#if defined(DMQ_DATABUS_TOOLS) - /// @brief Capture and reset windowed statistics. - ThreadStats SnapshotStats(); -#endif - -private: - PosixThread(const PosixThread&) = delete; - PosixThread& operator=(const PosixThread&) = delete; - - /// pthread entry point trampoline - static void* ThreadEntry(void* arg); - - /// Entry point for the thread - void Process(); - - /// Check watchdog is expired. Called by WatchdogCheckAll(), which the application - /// calls periodically, typically from its highest-priority task. Thread-safe. - void WatchdogCheck(); - - /// Get registry head using the "Immortal" Pattern - static PosixThread*& GetWatchdogHead(); - - /// Get registry lock using the "Immortal" Pattern - static dmq::RecursiveMutex& GetWatchdogLock(); - - /// Compute an absolute CLOCK_MONOTONIC deadline `timeout` from now, for pthread_cond_timedwait(). - static void MakeAbsTimeout(dmq::Duration timeout, struct timespec& ts); - - pthread_t m_thread{}; - bool m_threadCreated = false; - - // Startup synchronization: CreateThread() blocks here until Process() signals it has started. - pthread_mutex_t m_startMutex; - pthread_cond_t m_startCv; - bool m_started = false; - - pthread_mutex_t m_mutex; - - // Condition variable to wake up consumers when a message is enqueued - pthread_cond_t m_cvNotEmpty; - - // Condition variable to wake up blocked producers when space is available - pthread_cond_t m_cvNotFull; - -#ifdef DMQ_ALLOCATOR - std::deque, stl_allocator>> m_highQueue; - std::deque, stl_allocator>> m_normalQueue; -#else - std::deque> m_highQueue; - std::deque> m_normalQueue; -#endif - - const dmq::xstring THREAD_NAME; - const dmq::xstring CPU_NAME; - - // Max queue size for back pressure (0 = unlimited) - const size_t MAX_QUEUE_SIZE; - - // Policy applied when the thread message queue is full. - const FullPolicy FULL_POLICY; - - // Timeout duration for TIMEOUT policy - const dmq::Duration m_dispatchTimeout; - - // Optional handler invoked when a message is dropped (FullPolicy::DROP or TIMEOUT) - dmq::UnicastDelegate m_droppedHandler; - - // Optional handlers invoked on the worker thread at start, exit and when idle - dmq::UnicastDelegate m_startHandler; - dmq::UnicastDelegate m_exitHandler; - dmq::UnicastDelegate m_idleHandler; - dmq::Duration m_idleInterval = dmq::Duration::zero(); - - std::atomic m_exit; - - // Watchdog related members - std::atomic m_lastAliveTime{dmq::TimePoint()}; - std::atomic m_watchdogTimeout{dmq::Duration(0)}; - PosixThread* m_watchdogNext = nullptr; - - // Optional start gate (SetStartGate()): its state, and whether the thread is - // held at it (the watchdog doesn't report a thread waiting by design) - StartGateClient m_startGate; - -#if defined(DMQ_DATABUS_TOOLS) - // Monitoring statistics members - size_t m_queueDepthMaxWindow = 0; - size_t m_queueDepthMaxAll = 0; - - dmq::Duration m_latencyTotalWindow = dmq::Duration(0); - uint32_t m_latencyCountWindow = 0; - dmq::Duration m_latencyMaxWindow = dmq::Duration(0); - dmq::Duration m_latencyMaxAll = dmq::Duration(0); - - dmq::Duration m_invokeTotalWindow = dmq::Duration(0); - uint32_t m_invokeCountWindow = 0; - dmq::Duration m_invokeMaxWindow = dmq::Duration(0); - dmq::Duration m_invokeMaxAll = dmq::Duration(0); - - uint64_t m_dispatchCountAll = 0; -#endif -}; - -/// @brief Backward-compatible name: existing code referencing dmq::os::Thread -/// keeps compiling unchanged against the posix port. -using Thread = PosixThread; - -} // namespace dmq::os - -#endif diff --git a/DelegateMQ/port/os/qt/QtThread.cpp b/DelegateMQ/port/os/qt/QtThread.cpp deleted file mode 100644 index cac25ad..0000000 --- a/DelegateMQ/port/os/qt/QtThread.cpp +++ /dev/null @@ -1,574 +0,0 @@ -// Compiles to nothing unless DMQ_THREAD_QT is selected, so every DelegateMQ source -// file can be added to a build (see src/DelegateMQ.cpp). -#include "delegate/DelegateSelect.h" -#if defined(DMQ_THREAD_QT) - -#include "DelegateMQ.h" -#include "QtThread.h" -#include "extras/util/Fault.h" -#include -#include - -namespace dmq::os { - -using namespace dmq; -using namespace dmq::util; - -// Define DMQ_ASSERT_TRUE if not already defined -#ifndef DMQ_ASSERT_TRUE -#define DMQ_ASSERT_TRUE(x) Q_ASSERT(x) -#endif - -// QTimer takes an int millisecond interval: at least 1, clamped so a very long -// interval (over ~24 days) doesn't overflow -static int ToTimerInterval(long long ms) -{ - if (ms < 1) return 1; - if (ms > std::numeric_limits::max()) return std::numeric_limits::max(); - return static_cast(ms); -} - -// Register the metatype ID once -static int registerId = qRegisterMetaType>(); - -//---------------------------------------------------------------------------- -// Worker::OnDispatch -//---------------------------------------------------------------------------- -void Worker::OnDispatch(std::shared_ptr msg) { - // Watchdog heartbeat: the event loop reached another message - if (m_thread) - m_thread->ThreadCheck(); - - // ExitPolicy::DISCARD: skip messages queued ahead of the event loop's quit - if (m_discard.load()) { - if (msg) - msg->Cancel(); - emit MessageProcessed(); - return; - } - - if (msg) { - auto invoker = msg->GetInvoker(); - if (invoker) { -#if defined(DMQ_DATABUS_TOOLS) - dmq::TimePoint start = Timer::GetNow(); -#endif -#if defined(__cpp_exceptions) && !defined(DMQ_ASSERTS) - try { - bool success = invoker->Invoke(msg); - DMQ_ASSERT_TRUE(success); - } - catch (const std::bad_alloc& e) { - qWarning() << "[Thread:" << m_thread->objectName() << "] Unhandled bad_alloc in delegate callback:" << e.what(); - DMQ_ASSERT(); - } - catch (const std::invalid_argument& e) { - qWarning() << "[Thread:" << m_thread->objectName() << "] Unhandled invalid_argument in delegate callback:" << e.what(); - DMQ_ASSERT(); - } - catch (const std::runtime_error& e) { - qWarning() << "[Thread:" << m_thread->objectName() << "] Unhandled runtime_error in delegate callback:" << e.what(); - DMQ_ASSERT(); - } - catch (const std::exception& e) { - qWarning() << "[Thread:" << m_thread->objectName() << "] Unhandled exception in delegate callback:" << e.what(); - DMQ_ASSERT(); - } - catch (...) { - qWarning() << "[Thread:" << m_thread->objectName() << "] Unhandled unknown exception in delegate callback."; - DMQ_ASSERT(); - } -#else - bool success = invoker->Invoke(msg); - DMQ_ASSERT_TRUE(success); -#endif -#if defined(DMQ_DATABUS_TOOLS) - if (m_thread) { - dmq::Duration invokeTime = Timer::GetNow() - start; - m_thread->UpdateInvokeStats(invokeTime); - } -#endif - } - } - - // Any message restarts the idle countdown - if (m_idleTimer) - m_idleTimer->start(); - - emit MessageProcessed(); -} - -//---------------------------------------------------------------------------- -// Worker::StartIdleTimer -//---------------------------------------------------------------------------- -void Worker::StartIdleTimer(const dmq::UnicastDelegate& handler, dmq::Duration interval) -{ - m_idleHandler = handler; - auto ms = std::chrono::ceil(interval).count(); - - m_idleTimer = new QTimer(this); - m_idleTimer->setSingleShot(true); - m_idleTimer->setInterval(ToTimerInterval(ms)); - connect(m_idleTimer, &QTimer::timeout, this, [this]() { - m_idleHandler(); - m_idleTimer->start(); - }); - m_idleTimer->start(); -} - -//---------------------------------------------------------------------------- -// Worker::StartHeartbeat -//---------------------------------------------------------------------------- -void Worker::StartHeartbeat(dmq::Duration interval) -{ - auto ms = std::chrono::ceil(interval).count(); - - m_heartbeatTimer = new QTimer(this); - m_heartbeatTimer->setInterval(ToTimerInterval(ms)); - // Fires only while the event loop runs, so a stuck handler stops the heartbeat - connect(m_heartbeatTimer, &QTimer::timeout, this, [this]() { - if (m_thread) - m_thread->ThreadCheck(); - }); - m_heartbeatTimer->start(); -} - -//---------------------------------------------------------------------------- -// Thread Constructor -//---------------------------------------------------------------------------- -QtThread::QtThread(const char* threadName, size_t maxQueueSize, FullPolicy fullPolicy, dmq::Duration dispatchTimeout, const char* cpuName) - : m_threadName(threadName) - , m_cpuName(cpuName) - , m_maxQueueSize((maxQueueSize == 0) ? DEFAULT_QUEUE_SIZE : maxQueueSize) - , m_fullPolicy(fullPolicy) - , m_dispatchTimeout(dispatchTimeout) -{ -} - -//---------------------------------------------------------------------------- -// Thread Destructor -//---------------------------------------------------------------------------- -QtThread::~QtThread() -{ - ExitThread(); - - const std::lock_guard lock(GetWatchdogLock()); - QtThread** pp = &GetWatchdogHead(); - while (*pp != nullptr) - { - if (*pp == this) - { - *pp = this->m_watchdogNext; - this->m_watchdogNext = nullptr; - break; - } - pp = &((*pp)->m_watchdogNext); - } -} - -//---------------------------------------------------------------------------- -// CreateThread -//---------------------------------------------------------------------------- -bool QtThread::CreateThread(std::optional watchdogTimeout) -{ - if (!m_thread) - { - m_exiting.store(false); - // Held from creation, so the watchdog never sees a gated thread as hung - // before it reaches the gate (e.g. created before the scheduler runs) - m_startGate.OnCreate(); - // Set before the thread exists: its loop reads the timeout before its - // first queue wait, and an idle thread waits forever with no timeout - m_lastAliveTime.store(Timer::GetNow()); - m_watchdogTimeout.store(watchdogTimeout.value_or(dmq::Duration(0))); - m_thread = new QThread(); - m_thread->setObjectName(QString::fromUtf8(m_threadName.c_str())); - - // Create worker and move it to the new thread - m_worker = new Worker(this); - m_worker->moveToThread(m_thread); - - // Connect the Dispatch signal to the Worker's slot. - // Qt::QueuedConnection is mandatory for cross-thread communication, - // but Qt defaults to AutoConnection which handles this correctly. - connect(this, &QtThread::SignalDispatch, - m_worker, &Worker::OnDispatch, - Qt::QueuedConnection); - - // Track when message is processed to decrement m_queueSize - connect(m_worker, &Worker::MessageProcessed, - this, &QtThread::OnMessageProcessed); - - // Ensure worker is deleted when thread finishes - connect(m_thread, &QThread::finished, m_worker, &QObject::deleteLater); - - // Start handler and idle timer run on the new thread (started is emitted - // there; DirectConnection runs the lambda in place) before its event loop - // processes any dispatched message. - Worker* worker = m_worker; - QSemaphore* startSem = &m_startSem; - dmq::IThread* self = this; - QtThread* qt = this; // start gate state; see the self-exit check below - connect(m_thread, &QThread::started, m_worker, - [worker, self, qt, startSem, startHandler = m_startHandler, - idleHandler = m_idleHandler, idleInterval = m_idleInterval, - watchdog = m_watchdogTimeout.load()]() { - worker->BeginCurrentScope(self); - if (startHandler) - startHandler(); - if (idleHandler) - worker->StartIdleTimer(idleHandler, idleInterval); - if (watchdog.count() > 0) - worker->StartHeartbeat(watchdog / dmq::WATCHDOG_HEARTBEAT_DIVISOR); - - // A start handler that exited this thread (ExitThread() on itself) - // leaves right after the release below: once CreateThread() returns, - // the QtThread may be destroyed, so nothing after it may touch 'qt'. - const bool exitedInStart = qt->m_exiting.load(); - startSem->release(); - if (exitedInStart) - return; - - // Optional start gate: hold here, before the event loop runs any - // dispatched message, until it opens - if (qt->m_startGate.Enabled()) - { - const bool opened = qt->m_startGate.Wait(qt->m_exiting); - qt->m_lastAliveTime.store(Timer::GetNow()); // before Passed() - qt->m_startGate.Passed(); - // ExitThread() while held: the event loop cancels every - // queued message (discard) up to the quit queued behind them - if (!opened) - worker->SetDiscard(true); - } - }, Qt::DirectConnection); - - // Exit handler runs on the worker thread as it finishes (finished is - // emitted there), after GetCurrent() is cleared. Captured by copy so it - // works even if this QtThread was destroyed by a self-exit. - connect(m_thread, &QThread::finished, m_worker, - [worker, exitHandler = m_exitHandler]() { - worker->EndCurrentScope(); - if (exitHandler) - exitHandler(); - }, Qt::DirectConnection); - - // Also delete the QThread object itself when finished (optional, depending on ownership) - // connect(m_thread, &QThread::finished, m_thread, &QObject::deleteLater); - - m_thread->start(); - - // Wait for the start handler to complete - m_startSem.acquire(); - - m_lastAliveTime.store(Timer::GetNow()); - - if (watchdogTimeout.has_value()) - { - - // Add to watchdog registry if not already present - { - dmq::LockGuard lock(GetWatchdogLock()); - bool found = false; - QtThread* p = GetWatchdogHead(); - while (p != nullptr) - { - if (p == this) - { - found = true; - break; - } - p = p->m_watchdogNext; - } - if (!found) - { - m_watchdogNext = GetWatchdogHead(); - GetWatchdogHead() = this; - } - } - } - } - return true; -} - -//---------------------------------------------------------------------------- -// WatchdogCheck -//---------------------------------------------------------------------------- -void QtThread::WatchdogCheck() -{ - if (m_startGate.IsHeld()) - return; // held at its start gate by design, not hung - - auto now = Timer::GetNow(); - auto lastAlive = m_lastAliveTime.load(); - auto watchdogTimeout = m_watchdogTimeout.load(); - - if (watchdogTimeout.count() > 0) - { - auto delta = now - lastAlive; - if (delta > watchdogTimeout) - { - WatchdogHandler(m_threadName.c_str()); - } - } -} - -//---------------------------------------------------------------------------- -// ThreadCheck -//---------------------------------------------------------------------------- -void QtThread::ThreadCheck() -{ - m_lastAliveTime.store(Timer::GetNow()); -} - -//---------------------------------------------------------------------------- -// WatchdogCheckAll -//---------------------------------------------------------------------------- -void QtThread::WatchdogCheckAll() -{ - const std::lock_guard lock(GetWatchdogLock()); - QtThread* p = GetWatchdogHead(); - while (p != nullptr) - { - p->WatchdogCheck(); - p = p->m_watchdogNext; - } -} - -//---------------------------------------------------------------------------- -// GetWatchdogHead -//---------------------------------------------------------------------------- -QtThread*& QtThread::GetWatchdogHead() -{ - static QtThread* head = nullptr; - return head; -} - -//---------------------------------------------------------------------------- -// GetWatchdogLock -//---------------------------------------------------------------------------- -dmq::RecursiveMutex& QtThread::GetWatchdogLock() -{ - static dmq::RecursiveMutex* lock = new dmq::RecursiveMutex(); - return *lock; -} - -//---------------------------------------------------------------------------- -// ExitThread -//---------------------------------------------------------------------------- -void QtThread::ExitThread(ExitPolicy policy) -{ - if (m_thread) - { - m_exiting.store(true); - const bool selfExit = (QThread::currentThread() == m_thread); - if (selfExit) - m_startGate.Leave(); // exited from its start handler: never reaches the gate - - // A self-exit always discards: the event loop keeps running after this - // object may be destroyed. - m_worker->SetDiscard(policy == ExitPolicy::DISCARD || selfExit); - - // A thread held at its start gate isn't waiting on its queue: wake it so it - // sees the exit flag (set above) and leaves. Never touches the gate itself, - // which may be destroyed once the thread is released. - m_startGate.Wake(); - - // Quit queued behind every message already dispatched, so DRAIN invokes - // them first and DISCARD cancels them first. - QThread* thread = m_thread; - QMetaObject::invokeMethod(m_worker, [thread]() { thread->quit(); }, Qt::QueuedConnection); - - // Wake any blocked threads - m_mutex.lock(); - m_cvNotFull.wakeAll(); - m_mutex.unlock(); - - if (!selfExit) { - m_thread->wait(); - delete m_thread; - } else { - m_thread->deleteLater(); - } - - // The thread has finished (or, on a self-exit, is in its last handler): - // stop watchdog checks. Not earlier, so a thread that hangs while - // ExitThread() waits for it is still reported. - m_watchdogTimeout.store(dmq::Duration(0)); - - // Worker thread has fully stopped; null the back-pointer so the Worker - // cannot access this Thread if it is kept alive by deleteLater. - if (m_worker) { - m_worker->ClearThread(); - } - - m_thread = nullptr; - m_worker = nullptr; - } -} - -//---------------------------------------------------------------------------- -// GetThreadId -//---------------------------------------------------------------------------- -QThread* QtThread::GetThreadId() -{ - return m_thread; -} - -//---------------------------------------------------------------------------- -// GetCurrentThreadId -//---------------------------------------------------------------------------- -QThread* QtThread::GetCurrentThreadId() -{ - return QThread::currentThread(); -} - -//---------------------------------------------------------------------------- -// IsCurrentThread -//---------------------------------------------------------------------------- -bool QtThread::IsCurrentThread() -{ - return GetThreadId() == GetCurrentThreadId(); -} - -void QtThread::Sleep(dmq::Duration timeout) { - dmq::ThisThread::sleep_for(timeout); -} - -//---------------------------------------------------------------------------- -// DispatchDelegate -//---------------------------------------------------------------------------- -bool QtThread::DispatchDelegate(std::shared_ptr msg) -{ - // Safety check: Don't emit if thread is tearing down - if (m_thread && m_thread->isRunning() && !m_exiting.load()) - { - m_mutex.lock(); - if (m_queueSize >= m_maxQueueSize) - { - if (m_fullPolicy == FullPolicy::DROP) - { - size_t depth = m_queueSize.load(); - m_mutex.unlock(); - if (m_droppedHandler) - m_droppedHandler(depth); - return false; // silently discard - } - - if (m_fullPolicy == FullPolicy::FAULT) - { - m_mutex.unlock(); - printf("[Thread] CRITICAL: Queue full on thread '%s'! TRIGGERING FAULT.\n", m_threadName.c_str()); - DMQ_ASSERT_TRUE(m_queueSize < m_maxQueueSize); - return false; - } - - if (m_fullPolicy == FullPolicy::TIMEOUT) - { - auto ms = static_cast( - std::chrono::duration_cast(m_dispatchTimeout).count()); - while (m_queueSize >= m_maxQueueSize && m_thread->isRunning()) - { - if (!m_cvNotFull.wait(&m_mutex, ms)) - { - size_t depth = m_queueSize.load(); - m_mutex.unlock(); - printf("[Thread] WARNING: Queue post timed out on '%s' — possible deadlock. Message dropped.\n", m_threadName.c_str()); - if (m_droppedHandler) - m_droppedHandler(depth); - return false; - } - } - } - } - - // Re-check running status after wait - if (m_thread->isRunning()) - { - m_queueSize++; - -#if defined(DMQ_DATABUS_TOOLS) - // Update monitoring stats - size_t currentDepth = m_queueSize.load(); - if (currentDepth > m_queueDepthMaxWindow) m_queueDepthMaxWindow = currentDepth; - if (currentDepth > m_queueDepthMaxAll) m_queueDepthMaxAll = currentDepth; - m_dispatchCountAll++; -#endif - - // Unlike the other thread ports, msg->GetPriority() is ignored here: - // the queued signal goes into Qt's single FIFO event queue, so a - // Priority::HIGH message runs after every message dispatched before - // it. The other ports keep a HIGH and a NORMAL queue and drain HIGH - // first. Supporting priority would need a two-lane queue here, with - // the signal only waking the worker to drain it. - emit SignalDispatch(msg); - m_mutex.unlock(); - return true; - } - m_mutex.unlock(); - } - return false; -} - -#if defined(DMQ_DATABUS_TOOLS) -//---------------------------------------------------------------------------- -// UpdateInvokeStats -//---------------------------------------------------------------------------- -void QtThread::UpdateInvokeStats(dmq::Duration invokeTime) -{ - m_mutex.lock(); - m_invokeTotalWindow += invokeTime; - m_invokeCountWindow++; - if (invokeTime > m_invokeMaxWindow) m_invokeMaxWindow = invokeTime; - if (invokeTime > m_invokeMaxAll) m_invokeMaxAll = invokeTime; - m_mutex.unlock(); -} - -//---------------------------------------------------------------------------- -// SnapshotStats -//---------------------------------------------------------------------------- -QtThread::ThreadStats QtThread::SnapshotStats() -{ - m_mutex.lock(); - ThreadStats stats; - stats.cpu_name = m_cpuName; - stats.thread_name = m_threadName; - stats.queue_depth = m_queueSize.load(); - stats.queue_depth_max_window = m_queueDepthMaxWindow; - stats.queue_depth_max_all = m_queueDepthMaxAll; - stats.queue_size_limit = m_maxQueueSize; - - // Qt port doesn't implement latency yet due to Signal/Slot bridge limitations - stats.latency_avg_ms = 0.0f; - stats.latency_max_window_ms = 0.0f; - stats.latency_max_all_ms = 0.0f; - - if (m_invokeCountWindow > 0) { - stats.invoke_avg_ms = (float)std::chrono::duration_cast(m_invokeTotalWindow).count() / (static_cast(m_invokeCountWindow) * 1000.0f); - } else { - stats.invoke_avg_ms = 0.0f; - } - - stats.invoke_max_window_ms = (float)std::chrono::duration_cast(m_invokeMaxWindow).count() / 1000.0f; - stats.invoke_max_all_ms = (float)std::chrono::duration_cast(m_invokeMaxAll).count() / 1000.0f; - - stats.dispatch_count = m_dispatchCountAll; - - // Reset windowed stats - m_queueDepthMaxWindow = 0; - m_latencyTotalWindow = Duration(0); - m_latencyCountWindow = 0; - m_latencyMaxWindow = Duration(0); - - m_invokeTotalWindow = Duration(0); - m_invokeCountWindow = 0; - m_invokeMaxWindow = Duration(0); - - m_mutex.unlock(); - return stats; -} -#endif - -} // namespace dmq::os - -#endif // DMQ_THREAD_QT diff --git a/DelegateMQ/port/os/qt/QtThread.h b/DelegateMQ/port/os/qt/QtThread.h deleted file mode 100644 index 3f84ae5..0000000 --- a/DelegateMQ/port/os/qt/QtThread.h +++ /dev/null @@ -1,341 +0,0 @@ -#ifndef _QT_THREAD_H -#define _QT_THREAD_H - -/// @file QtThread.h -/// @brief Qt implementation of the DelegateMQ IThread interface. -/// -/// @note No message priority: dmq::Priority is ignored, and messages run in the -/// order they were dispatched (Qt's event queue). The other thread ports process -/// Priority::HIGH messages before NORMAL ones. -/// -/// **Key Features:** -/// * **QThread Integration:** Wraps `QThread` and uses a Worker object to execute -/// delegates in the target thread's event loop. -/// * **FullPolicy Support:** Configurable back-pressure (DROP, FAULT, or TIMEOUT) using -/// `QMutex` and `QWaitCondition`. -/// * **Signal/Slot Dispatch:** Uses Qt's meta-object system to bridge delegate -/// execution across thread boundaries. -/// * **Watchdog Integration:** Optional heartbeat mechanism detects stalled or deadlocked -/// threads. Enable by passing a timeout to CreateThread(). Requires -/// Thread::WatchdogCheckAll() to be called periodically from a context that can preempt -/// watched threads -- the highest-priority thread in the system, not an ISR. -/// * **Start Gate:** Optional `SetStartGate(StartGate*)`, called before `CreateThread()`, -/// holds the thread ready but processing no messages, at any priority, until -/// `StartGate::Open()` releases every thread sharing the gate at once. -/// - -#include "delegate/IThread.h" -#include "delegate/UnicastDelegate.h" -#include "port/os/common/StartGate.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace dmq::os { - -/// @brief Policy applied when the thread message queue is full. See dmq::FullPolicy -/// in DelegateOpt.h for the canonical definition, shared by every dmq::os::Thread port. -using FullPolicy = dmq::FullPolicy; - -/// @brief What ExitThread() does with queued messages. See dmq::ExitPolicy in DelegateOpt.h. -using ExitPolicy = dmq::ExitPolicy; - -// ---------------------------------------------------------------------------- -// Worker Object -// Lives on the target QThread and executes the slots -// ---------------------------------------------------------------------------- -class QtThread; -class Worker : public QObject -{ - Q_OBJECT -public: - Worker(QtThread* thread = nullptr) : m_thread(thread) {} - void ClearThread() { m_thread = nullptr; } - - /// Start the idle countdown. Must be called on the worker's thread. - void StartIdleTimer(const dmq::UnicastDelegate& handler, dmq::Duration interval); - - /// Refresh the watchdog heartbeat every `interval` while the event loop is - /// idle. Must be called on the worker's thread. - void StartHeartbeat(dmq::Duration interval); - - /// Register `thread` for dmq::ThisThread::GetCurrent() until EndCurrentScope(). - /// Both must be called on the worker's thread. - void BeginCurrentScope(dmq::IThread* thread) { m_currentScope.emplace(thread); } - void EndCurrentScope() { m_currentScope.reset(); } - - /// ExitPolicy::DISCARD: cancel messages instead of invoking them. Set by - /// ExitThread() from any thread before it queues the event loop's quit. - void SetDiscard(bool discard) { m_discard.store(discard); } - -public slots: - void OnDispatch(std::shared_ptr msg); - -signals: - void MessageProcessed(); - -private: - QtThread* m_thread; - - // Idle handler copy and its single-shot timer, restarted by every message. - // Created on the worker's thread by StartIdleTimer(); null if no idle handler. - dmq::UnicastDelegate m_idleHandler; - QTimer* m_idleTimer = nullptr; - - // Watchdog heartbeat: refreshes the alive timestamp while the event loop is - // idle. Created by StartHeartbeat(); null if the thread has no watchdog. - QTimer* m_heartbeatTimer = nullptr; - - // Held for the life of the event loop: a Qt worker has no loop stack frame - std::optional m_currentScope; - - std::atomic m_discard{ false }; -}; - -class QtThread : public QObject, public dmq::IThread -{ - Q_OBJECT - -public: -#if defined(DMQ_DATABUS_TOOLS) - /// @brief Statistics captured for thread monitoring. - struct ThreadStats { - dmq::xstring cpu_name; - dmq::xstring thread_name; - size_t queue_depth; // Current depth - size_t queue_depth_max_window;// Max depth since last snapshot - size_t queue_depth_max_all; // All-time max depth - size_t queue_size_limit; // Max allowed - float latency_avg_ms; // Avg wait in window - float latency_max_window_ms; // Max wait since last snapshot - float latency_max_all_ms; // All-time max wait - float invoke_avg_ms; // Avg execution in window - float invoke_max_window_ms; // Max execution since last snapshot - float invoke_max_all_ms; // All-time max execution - uint64_t dispatch_count; // Total dispatches (all-time) - }; -#endif - - /// Default queue size if 0 is passed - static const size_t DEFAULT_QUEUE_SIZE = dmq::DEFAULT_QUEUE_SIZE; - - /// Constructor - /// @param threadName Name for debugging (QObject::objectName) - /// @param maxQueueSize Max number of messages in queue (0 = Default dmq::DEFAULT_QUEUE_SIZE) - /// @param fullPolicy Action when queue is full: FAULT (default), DROP, or TIMEOUT. - /// @param dispatchTimeout Duration to wait before giving up when policy is TIMEOUT. - /// @param cpuName Optional CPU/Core name grouping for monitoring tools. - QtThread(const char* threadName, size_t maxQueueSize = 0, FullPolicy fullPolicy = FullPolicy::FAULT, - dmq::Duration dispatchTimeout = dmq::DEFAULT_DISPATCH_TIMEOUT, const char* cpuName = ""); - - QtThread(const std::string& threadName, size_t maxQueueSize = 0, FullPolicy fullPolicy = FullPolicy::FAULT, - dmq::Duration dispatchTimeout = dmq::DEFAULT_DISPATCH_TIMEOUT, const std::string& cpuName = "") - : QtThread(threadName.c_str(), maxQueueSize, fullPolicy, dispatchTimeout, cpuName.c_str()) {} - - /// Destructor - ~QtThread(); - - /// Create and start the internal QThread. If watchdogTimeout value - /// provided, the maximum watchdog interval is used. Otherwise no watchdog. - /// @param[in] watchdogTimeout - optional watchdog timeout. - /// @return TRUE if thread is created. FALSE otherwise. - bool CreateThread(std::optional watchdogTimeout = std::nullopt); - - /// Shut down the worker thread. - /// @param[in] policy - DRAIN (default) invokes every message queued before this - /// call first; DISCARD invokes only the message already running and cancels - /// the rest (see dmq::ExitPolicy). Called from the thread's own message - /// handler (a self-exit), queued messages are always discarded. - void ExitThread(ExitPolicy policy = ExitPolicy::DRAIN); - - /// Get the QThread pointer (used as the ID) - QThread* GetThreadId(); - - /// Get the current executing QThread pointer - static QThread* GetCurrentThreadId(); - - /// Returns true if the calling thread is this thread - virtual bool IsCurrentThread() override; - - dmq::xstring GetThreadName() const { return m_threadName; } - - /// Get current queue size - size_t GetQueueSize() const { return m_queueSize.load(); } - - /// Sleep for a duration. - /// @param[in] timeout - the duration to sleep. - static void Sleep(dmq::Duration timeout); - - // IThread Interface Implementation - virtual bool DispatchDelegate(std::shared_ptr msg) override; - - /// @brief Register a handler invoked when DispatchDelegate() drops a message: - /// under FullPolicy::DROP (queue full, discarded immediately) or - /// FullPolicy::TIMEOUT (queue stayed full for dispatchTimeout, discarded). - /// Optional; unset by default. Called synchronously on the calling (producer) - /// thread, with the queue depth at the time of the drop. - void SetDroppedHandler(const dmq::UnicastDelegate& handler) { m_droppedHandler = handler; } - void SetDroppedHandler(dmq::UnicastDelegate&& handler) { m_droppedHandler = std::move(handler); } - - /// @brief Register a handler invoked on the worker thread before it processes - /// any message. Use it for per-thread setup (COM, a language runtime attach, - /// thread-local state, affinity). CreateThread() returns only after it completes. - /// @details Must be called while the thread is not running (before CreateThread(), - /// or after ExitThread()); calling it on a running thread faults. It runs again - /// on each CreateThread(). Messages dispatched meanwhile are queued, not lost. - void SetStartHandler(const dmq::UnicastDelegate& handler) { DMQ_ASSERT_TRUE(!m_thread); m_startHandler = handler; } - void SetStartHandler(dmq::UnicastDelegate&& handler) { DMQ_ASSERT_TRUE(!m_thread); m_startHandler = std::move(handler); } - - /// @brief Optional: hold this thread at `gate` once it is created, until - /// `gate->Open()`. Pass nullptr (the default) to start at once. - /// @details CreateThread() still runs the start handler and returns when the - /// thread is ready; the thread then processes nothing, at any priority, until - /// the gate opens. Use one gate for a group of threads so they all start - /// together after setup. See port/os/common/StartGate.h. Must be called while - /// the thread is not running; calling it on a running thread faults. - void SetStartGate(StartGate* gate) { DMQ_ASSERT_TRUE(!m_thread); m_startGate.Set(gate); } - - /// @brief Register a handler invoked on the worker thread after it processes - /// its last message, as the thread exits. Use it to undo SetStartHandler() setup. - /// @details Must be called while the thread is not running; calling it on a - /// running thread faults. The handler is copied when the thread starts. - /// ExitThread() from another thread returns after it completes. If the thread - /// exits itself (ExitThread() from a handler on this thread), it runs after the - /// owning QtThread may already be destroyed, so it must not touch that object. - void SetExitHandler(const dmq::UnicastDelegate& handler) { DMQ_ASSERT_TRUE(!m_thread); m_exitHandler = handler; } - void SetExitHandler(dmq::UnicastDelegate&& handler) { DMQ_ASSERT_TRUE(!m_thread); m_exitHandler = std::move(handler); } - - /// @brief Register a handler invoked on the worker thread when its queue has - /// been empty for `interval`, then again every `interval` while it stays empty. - /// Any message processed restarts the countdown. Use it for background work that - /// should yield to messages: polling, housekeeping, entering low power. - /// @details Must be called while the thread is not running; calling it on a - /// running thread faults. The handler and interval are copied when the thread - /// starts. Not called once ExitThread() has been requested. - /// @param[in] handler - the idle handler, or an empty delegate to disable. - /// @param[in] interval - quiet time before each call. Must be greater than zero. - /// Defaults to dmq::THREAD_IDLE_INTERVAL (DMQ_THREAD_IDLE_INTERVAL). - void SetIdleHandler(const dmq::UnicastDelegate& handler, dmq::Duration interval = dmq::THREAD_IDLE_INTERVAL) - { - DMQ_ASSERT_TRUE(!m_thread); - DMQ_ASSERT_TRUE(interval > dmq::Duration::zero()); - m_idleHandler = handler; - m_idleInterval = interval; - } - void SetIdleHandler(dmq::UnicastDelegate&& handler, dmq::Duration interval = dmq::THREAD_IDLE_INTERVAL) - { - DMQ_ASSERT_TRUE(!m_thread); - DMQ_ASSERT_TRUE(interval > dmq::Duration::zero()); - m_idleHandler = std::move(handler); - m_idleInterval = interval; - } - - /// @brief Manually update the watchdog alive timestamp. - /// @details The Run() loop refreshes the timestamp automatically on every iteration. - /// Call this from inside long-running message handlers to prevent a false watchdog - /// alarm when a handler legitimately takes longer than watchdogTimeout. - void ThreadCheck(); - - /// @brief Static method to check all registered threads for watchdog expiration. - static void WatchdogCheckAll(); - -#if defined(DMQ_DATABUS_TOOLS) - /// @brief Capture and reset windowed statistics. - ThreadStats SnapshotStats(); - - /// @brief Internal method for Worker to update invoke stats. - void UpdateInvokeStats(dmq::Duration invokeTime); -#endif - -signals: - // Internal signal to bridge threads - void SignalDispatch(std::shared_ptr msg); - -private slots: - void OnMessageProcessed() { - m_queueSize--; - m_cvNotFull.wakeAll(); - } - -private: - QtThread(const QtThread&) = delete; - QtThread& operator=(const QtThread&) = delete; - - /// Check watchdog is expired. Called by WatchdogCheckAll(). - void WatchdogCheck(); - - /// Get registry head using the "Immortal" Pattern - static QtThread*& GetWatchdogHead(); - - /// Get registry lock using the "Immortal" Pattern - static dmq::RecursiveMutex& GetWatchdogLock(); - - const dmq::xstring m_threadName; - const dmq::xstring m_cpuName; - const size_t m_maxQueueSize; - const FullPolicy m_fullPolicy; - const dmq::Duration m_dispatchTimeout; - QThread* m_thread = nullptr; - Worker* m_worker = nullptr; - std::atomic m_queueSize{0}; - QMutex m_mutex; - QWaitCondition m_cvNotFull; - - // Released on the worker thread once the start handler has run - QSemaphore m_startSem; - - // Set by ExitThread(): DispatchDelegate() rejects new messages, which would - // otherwise queue behind the event loop's quit and never run - std::atomic m_exiting{ false }; - - // Optional handler invoked when a message is dropped (FullPolicy::DROP or TIMEOUT) - dmq::UnicastDelegate m_droppedHandler; - - // Optional handlers invoked on the worker thread at start, exit and when idle - dmq::UnicastDelegate m_startHandler; - dmq::UnicastDelegate m_exitHandler; - dmq::UnicastDelegate m_idleHandler; - dmq::Duration m_idleInterval = dmq::Duration::zero(); - - // Watchdog related members - std::atomic m_lastAliveTime{dmq::TimePoint()}; - std::atomic m_watchdogTimeout{dmq::Duration(0)}; - QtThread* m_watchdogNext = nullptr; - - // Optional start gate (SetStartGate()): its state, and whether the thread is - // held at it (the watchdog doesn't report a thread waiting by design) - StartGateClient m_startGate; - -#if defined(DMQ_DATABUS_TOOLS) - // Monitoring statistics members - size_t m_queueDepthMaxWindow = 0; - size_t m_queueDepthMaxAll = 0; - - dmq::Duration m_latencyTotalWindow = dmq::Duration(0); - uint32_t m_latencyCountWindow = 0; - dmq::Duration m_latencyMaxWindow = dmq::Duration(0); - dmq::Duration m_latencyMaxAll = dmq::Duration(0); - - dmq::Duration m_invokeTotalWindow = dmq::Duration(0); - uint32_t m_invokeCountWindow = 0; - dmq::Duration m_invokeMaxWindow = dmq::Duration(0); - dmq::Duration m_invokeMaxAll = dmq::Duration(0); - - uint64_t m_dispatchCountAll = 0; -#endif -}; - -/// @brief Backward-compatible name: existing code referencing dmq::os::Thread -/// keeps compiling unchanged against the Qt port. -using Thread = QtThread; - -} // namespace dmq::os - -#endif // _QT_THREAD_H diff --git a/DelegateMQ/port/os/stdlib/StdlibThisThread.h b/DelegateMQ/port/os/stdlib/StdlibThisThread.h deleted file mode 100644 index 1a57fb1..0000000 --- a/DelegateMQ/port/os/stdlib/StdlibThisThread.h +++ /dev/null @@ -1,29 +0,0 @@ -#ifndef STDLIB_THIS_THREAD_H -#define STDLIB_THIS_THREAD_H - -/// @file StdlibThisThread.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief dmq::ThisThread for the desktop ports (stdlib, Win32, Qt, POSIX). -/// -/// @details -/// std::this_thread is already portable on these platforms, so sleep_for() and -/// yield() forward to it. GetCurrent() uses thread_local storage. - -#include "port/os/common/CurrentThreadStorage.h" -#include -#include - -namespace dmq::os { - - struct StdlibThisThread : ThreadLocalCurrentThread { - template - static void sleep_for(std::chrono::duration d) { std::this_thread::sleep_for(d); } - - static void yield() noexcept { std::this_thread::yield(); } - }; - -} // namespace dmq::os - -#endif // STDLIB_THIS_THREAD_H diff --git a/DelegateMQ/port/os/stdlib/StdlibThread.cpp b/DelegateMQ/port/os/stdlib/StdlibThread.cpp deleted file mode 100644 index d4a5e7d..0000000 --- a/DelegateMQ/port/os/stdlib/StdlibThread.cpp +++ /dev/null @@ -1,685 +0,0 @@ -// Compiles to nothing unless DMQ_THREAD_STDLIB is selected, so every DelegateMQ source -// file can be added to a build (see src/DelegateMQ.cpp). -#include "delegate/DelegateSelect.h" -#if defined(DMQ_THREAD_STDLIB) - -#include "DelegateMQ.h" -#include "StdlibThread.h" -#include "port/os/common/ThreadHooks.h" -#include "extras/util/Fault.h" - -#ifdef _WIN32 -#include -#endif -#ifdef __linux__ -#include -#endif - -// Thread-local pointer into Process()'s stack frame. Set non-null only while -// Process() is running on a given thread. ExitThread() writes true through it -// when the thread destroys its own owning object so Process() can exit without -// touching freed members. -static thread_local bool* t_self_exit = nullptr; - -namespace dmq::os { - -using namespace dmq::util; - -//---------------------------------------------------------------------------- -// Thread -//---------------------------------------------------------------------------- -StdlibThread::StdlibThread(const char* threadName, size_t maxQueueSize, FullPolicy fullPolicy, dmq::Duration dispatchTimeout, const char* cpuName) - : m_thread(std::nullopt) - , m_exit(false) - , THREAD_NAME(threadName) - , CPU_NAME(cpuName) - , MAX_QUEUE_SIZE(maxQueueSize == 0 ? dmq::THREAD_DESKTOP_QUEUE_SIZE : maxQueueSize) - , FULL_POLICY(fullPolicy) - , m_dispatchTimeout(dispatchTimeout) -{ -} - -//---------------------------------------------------------------------------- -// ~Thread -//---------------------------------------------------------------------------- -StdlibThread::~StdlibThread() -{ - ExitThread(); - - const std::lock_guard lock(GetWatchdogLock()); - StdlibThread** pp = &GetWatchdogHead(); - while (*pp != nullptr) - { - if (*pp == this) - { - *pp = this->m_watchdogNext; - this->m_watchdogNext = nullptr; - break; - } - pp = &((*pp)->m_watchdogNext); - } -} - -//---------------------------------------------------------------------------- -// CreateThread -//---------------------------------------------------------------------------- -bool StdlibThread::CreateThread(std::optional watchdogTimeout) -{ - if (!m_thread) - { - m_threadStartPromise.emplace(); - m_threadStartFuture.emplace(m_threadStartPromise->get_future()); - m_exit = false; - // Held from creation, so the watchdog never sees a gated thread as hung - // before it reaches the gate (e.g. created before the scheduler runs) - m_startGate.OnCreate(); - // Set before the thread exists: its loop reads the timeout before its - // first queue wait, and an idle thread waits forever with no timeout - m_lastAliveTime.store(Timer::GetNow()); - m_watchdogTimeout.store(watchdogTimeout.value_or(dmq::Duration(0))); - - { - // Held until m_thread is fully constructed and named. Process() takes - // this lock before running the start handler, which may call - // IsCurrentThread() or dispatch to this thread (both read m_thread). - std::lock_guard lock(m_mutex); - m_thread.emplace(&StdlibThread::Process, this); - - auto handle = m_thread->native_handle(); - SetThreadName(handle, THREAD_NAME); - } - - // Wait for the thread to run the start handler and enter its loop - m_threadStartFuture->get(); - - m_lastAliveTime.store(Timer::GetNow()); - - // Caller wants a watchdog timer? - if (watchdogTimeout.has_value()) - { - - // Add to watchdog registry if not already present - { - dmq::LockGuard lock(GetWatchdogLock()); - bool found = false; - StdlibThread* p = GetWatchdogHead(); - while (p != nullptr) - { - if (p == this) - { - found = true; - break; - } - p = p->m_watchdogNext; - } - if (!found) - { - m_watchdogNext = GetWatchdogHead(); - GetWatchdogHead() = this; - } - } - } - } - return true; -} - -//---------------------------------------------------------------------------- -// GetThreadId -//---------------------------------------------------------------------------- -std::thread::id StdlibThread::GetThreadId() -{ - if (!m_thread.has_value()) - throw std::invalid_argument("Thread pointer is null"); - - return m_thread->get_id(); -} - -//---------------------------------------------------------------------------- -// GetCurrentThreadId -//---------------------------------------------------------------------------- -std::thread::id StdlibThread::GetCurrentThreadId() -{ - return std::this_thread::get_id(); -} - -//---------------------------------------------------------------------------- -// IsCurrentThread -//---------------------------------------------------------------------------- -bool StdlibThread::IsCurrentThread() -{ - if (!m_thread.has_value()) - return false; - - return GetThreadId() == GetCurrentThreadId(); -} - -//---------------------------------------------------------------------------- -// GetQueueSize -//---------------------------------------------------------------------------- -size_t StdlibThread::GetQueueSize() -{ - std::lock_guard lock(m_mutex); - return (m_highQueue.size() + m_normalQueue.size()); -} - -void StdlibThread::Sleep(dmq::Duration timeout) { - dmq::ThisThread::sleep_for(timeout); -} - -//---------------------------------------------------------------------------- -// SetThreadName -//---------------------------------------------------------------------------- -void StdlibThread::SetThreadName(std::thread::native_handle_type handle, const dmq::xstring& name) -{ - (void)handle; - (void)name; -#ifdef _WIN32 - // Set the thread name so it shows in the Visual Studio Debug Location toolbar - std::wstring wstr(name.begin(), name.end()); - HRESULT hr = SetThreadDescription(handle, wstr.c_str()); - if (FAILED(hr)) - { - // Handle error if needed - } -#elif defined(__linux__) - // Shown by top -H, ps -L, gdb and perf. Linux limits names to 15 characters. - pthread_setname_np(handle, name.substr(0, 15).c_str()); -#endif -} - -//---------------------------------------------------------------------------- -// ExitThread -//---------------------------------------------------------------------------- -void StdlibThread::ExitThread(ExitPolicy policy) -{ - if (!m_thread) - return; - - // Create a new ThreadMsg - auto threadMsg = xmake_shared(MSG_EXIT_THREAD, nullptr); - - // Messages taken off the queues without being invoked; canceled outside the lock - decltype(m_highQueue) discardedHigh; - decltype(m_normalQueue) discardedNormal; - - { - std::lock_guard lock(m_mutex); - - // Set exit flag INSIDE lock before notifying. - // This ensures that when a blocked producer wakes up, it sees m_exit == true immediately. - m_exit.store(true); - - // DISCARD: empty the queues so the exit message is the next one processed - if (policy == ExitPolicy::DISCARD) - { - discardedHigh.swap(m_highQueue); - discardedNormal.swap(m_normalQueue); - } - - // Explicitly allow Exit message to bypass the MAX_QUEUE_SIZE limit. - // We do not wait on m_cvNotFull here to prevent deadlock during shutdown. - if (threadMsg->GetPriority() == dmq::Priority::HIGH) - m_highQueue.push_back(threadMsg); - else - m_normalQueue.push_back(threadMsg); - - // Wake up consumers - m_cv.notify_one(); - // Wake up blocked producers (DispatchDelegate) - m_cvNotFull.notify_all(); - } - - CancelAll(discardedHigh); - CancelAll(discardedNormal); - - // A thread held at its start gate isn't waiting on its queue: wake it so it - // sees the exit flag (set above) and leaves. Never touches the gate itself, - // which may be destroyed once the thread is released. - m_startGate.Wake(); - - // Prevent deadlock if ExitThread is called from within the thread itself - if (m_thread->joinable()) - { - if (std::this_thread::get_id() != m_thread->get_id()) - { - m_thread->join(); - } - else - { - // We are killing ourselves. Detach so the thread object cleans up naturally. - m_thread->detach(); - // Signal Process() (running on this thread) to exit without touching - // 'this' again — the owning object is about to be freed. - if (t_self_exit) *t_self_exit = true; - m_startGate.Leave(); // exited from its start handler: never reaches the gate - } - } - - // The thread has finished (or, on a self-exit, is in its last handler): - // stop watchdog checks. Not earlier, so a thread that hangs while - // ExitThread() waits for it is still reported. - m_watchdogTimeout.store(dmq::Duration(0)); - - { - std::lock_guard lock(m_mutex); - m_thread.reset(); - - // Normally empty. After a self-exit the loop returns without draining, - // so anything still queued is discarded here. - discardedHigh.swap(m_highQueue); - discardedNormal.swap(m_normalQueue); - - // Final cleanup notification - m_cvNotFull.notify_all(); - } - - CancelAll(discardedHigh); - CancelAll(discardedNormal); -} - -//---------------------------------------------------------------------------- -// DispatchDelegate -//---------------------------------------------------------------------------- -bool StdlibThread::DispatchDelegate(std::shared_ptr msg) -{ - // Early check, though we re-check inside lock for safety - if (m_exit.load()) - return false; - - if (!m_thread.has_value()) - throw std::invalid_argument("Thread pointer is null"); - - std::unique_lock lk(m_mutex); - - // [BACK PRESSURE / DROP / FAULT / TIMEOUT LOGIC] - if (MAX_QUEUE_SIZE > 0 && (m_highQueue.size() + m_normalQueue.size()) >= MAX_QUEUE_SIZE) - { - if (FULL_POLICY == FullPolicy::DROP) - { - size_t depth = m_highQueue.size() + m_normalQueue.size(); - lk.unlock(); - if (m_droppedHandler) - m_droppedHandler(depth); - return false; // silently discard — caller is not stalled, no allocation wasted - } - - if (FULL_POLICY == FullPolicy::FAULT) - { - printf("[Thread] CRITICAL: Queue full on thread '%s'! TRIGGERING FAULT.\n", THREAD_NAME.c_str()); - DMQ_ASSERT_TRUE(false); - return false; - } - - if (FULL_POLICY == FullPolicy::TIMEOUT) - { - bool hasSpace = m_cvNotFull.wait_for(lk, m_dispatchTimeout, [this]() { - return (m_highQueue.size() + m_normalQueue.size()) < MAX_QUEUE_SIZE || m_exit.load(); - }); - if (!hasSpace) { - printf("[Thread] WARNING: Queue post timed out on '%s' — possible deadlock. Message dropped.\n", THREAD_NAME.c_str()); - size_t depth = m_highQueue.size() + m_normalQueue.size(); - lk.unlock(); - if (m_droppedHandler) - m_droppedHandler(depth); - return false; - } - // space found — fall through to push - } - - } - - // If using XALLOCATOR explicit operator new required. See xallocator.h. - auto threadMsg = xmake_shared(MSG_DISPATCH_DELEGATE, msg); -#if defined(DMQ_DATABUS_TOOLS) - threadMsg->SetEnqueueTime(Timer::GetNow()); -#endif - - // If we woke up because of exit (or exit happened while waiting), abort - if (m_exit.load()) - return false; - - if (threadMsg->GetPriority() == dmq::Priority::HIGH) - m_highQueue.push_back(threadMsg); - else - m_normalQueue.push_back(threadMsg); - -#if defined(DMQ_DATABUS_TOOLS) - // Snapshot size while holding m_mutex - size_t currentDepth = (m_highQueue.size() + m_normalQueue.size()); -#endif - - m_cv.notify_one(); - lk.unlock(); // Release producer-blocking lock early - -#if defined(DMQ_DATABUS_TOOLS) - // Update monitoring stats under the separate stats mutex - { - std::lock_guard lock(m_statsMutex); - if (currentDepth > m_queueDepthMaxWindow) m_queueDepthMaxWindow = currentDepth; - if (currentDepth > m_queueDepthMaxAll) m_queueDepthMaxAll = currentDepth; - } -#endif - - return true; -} - -//---------------------------------------------------------------------------- -// WatchdogCheckAll -//---------------------------------------------------------------------------- -void StdlibThread::WatchdogCheckAll() -{ - const std::lock_guard lock(GetWatchdogLock()); - StdlibThread* p = GetWatchdogHead(); - while (p != nullptr) - { - p->WatchdogCheck(); - p = p->m_watchdogNext; - } -} - -//---------------------------------------------------------------------------- -// WatchdogCheck -//---------------------------------------------------------------------------- -void StdlibThread::WatchdogCheck() -{ - if (m_startGate.IsHeld()) - return; // held at its start gate by design, not hung - - auto now = Timer::GetNow(); - auto lastAlive = m_lastAliveTime.load(); - auto watchdogTimeout = m_watchdogTimeout.load(); - - if (watchdogTimeout.count() > 0) - { - auto delta = now - lastAlive; - if (delta > watchdogTimeout) - { - WatchdogHandler(THREAD_NAME.c_str()); - } - } -} - -//---------------------------------------------------------------------------- -// ThreadCheck -//---------------------------------------------------------------------------- -void StdlibThread::ThreadCheck() -{ - m_lastAliveTime.store(Timer::GetNow()); -} - -//---------------------------------------------------------------------------- -// GetWatchdogHead -//---------------------------------------------------------------------------- -StdlibThread*& StdlibThread::GetWatchdogHead() -{ - static StdlibThread* head = nullptr; - return head; -} - -//---------------------------------------------------------------------------- -// GetWatchdogLock -//---------------------------------------------------------------------------- -dmq::RecursiveMutex& StdlibThread::GetWatchdogLock() -{ - static dmq::RecursiveMutex* lock = new dmq::RecursiveMutex(); - return *lock; -} - -//---------------------------------------------------------------------------- -// Process -//---------------------------------------------------------------------------- -void StdlibThread::Process() -{ - // selfExit is set by ExitThread() when the thread destroys its own owner. - // It lives on this stack frame so it remains valid even after 'this' is freed. - bool selfExit = false; - t_self_exit = &selfExit; - - // Exit and idle handlers are copied onto this stack frame so they work on - // every return path, including a self-exit where 'this' may already be freed. - ThreadExitGuard exitGuard(m_exitHandler); - ThreadIdleTimer idle(m_idleHandler, m_idleInterval); - - // Wait for CreateThread() to finish constructing m_thread - { std::lock_guard lock(m_mutex); } - - // dmq::ThisThread::GetCurrent() returns this thread from here on. Declared - // after exitGuard, so it is cleared again before the exit handler runs. - dmq::CurrentThreadScope currentScope(this); - - if (m_startHandler) - m_startHandler(); - - // A start handler that exited this thread (ExitThread() on itself) leaves - // right after the signal below: once CreateThread() returns, the Thread may - // be destroyed, so nothing after the signal may touch 'this'. - const bool exitedInStart = selfExit; - - // Signal that the thread has started processing to notify CreateThread. - // From a local: the caller may destroy this object once it is signaled. - std::promise startPromise = std::move(*m_threadStartPromise); - startPromise.set_value(); - if (exitedInStart) { t_self_exit = nullptr; return; } - - // Optional start gate: wait here, ready but processing nothing, until it opens - if (m_startGate.Enabled()) - { - const bool opened = m_startGate.Wait(m_exit); - m_lastAliveTime.store(Timer::GetNow()); // before Passed(): no stale watchdog read - m_startGate.Passed(); - if (!opened) - { - // ExitThread() while held: leave without running any message. - // ExitThread() cancels what is still queued once this thread ends. - t_self_exit = nullptr; - return; - } - } - - while (!selfExit) - { - dmq::Duration watchdogTimeout; - { - m_lastAliveTime.store(Timer::GetNow()); - watchdogTimeout = m_watchdogTimeout.load(); - } - - std::shared_ptr msg; - { - std::unique_lock lk(m_mutex); - - // Wait for message to be added to the queue. - // If watchdog active, use a finite timeout so we can periodically update - // m_lastAliveTime while idle. If an idle handler is set, wake no later - // than when it is due. Otherwise, block forever. - auto predicate = [this]() { return !(m_highQueue.empty() && m_normalQueue.empty()) || m_exit.load(); }; - // Wake up frequently to ensure heartbeat is updated while idle (negative = forever) - dmq::Duration waitTime = idle.WaitTime(watchdogTimeout.count() > 0 ? watchdogTimeout / dmq::WATCHDOG_HEARTBEAT_DIVISOR : dmq::Duration(-1)); - if (waitTime >= dmq::Duration::zero()) - m_cv.wait_for(lk, waitTime, predicate); - else - m_cv.wait(lk, predicate); - - // Always update alive time immediately after waking up - m_lastAliveTime.store(Timer::GetNow()); - - // If empty and exit is true, we should exit. - if ((m_highQueue.empty() && m_normalQueue.empty())) - { - if (m_exit.load()) { t_self_exit = nullptr; return; } - if (!idle.IsDue()) - continue; - // Idle handler is due: fall through with no message - } - else - { - // Get highest priority message within queue - if (!m_highQueue.empty()) { - msg = m_highQueue.front(); - m_highQueue.pop_front(); - } else { - msg = m_normalQueue.front(); - m_normalQueue.pop_front(); - } - - // Unblock producers now that space is available - if (MAX_QUEUE_SIZE > 0) - { - m_cvNotFull.notify_one(); - } - } - } - - if (!msg) - { - idle.Run(); - continue; - } - - switch (msg->GetId()) - { - case MSG_DISPATCH_DELEGATE: - { -#if defined(DMQ_DATABUS_TOOLS) - // Update latency stats before invoking - dmq::Duration latency = Timer::GetNow() - msg->GetEnqueueTime(); - { - std::lock_guard lock(m_statsMutex); - m_latencyTotalWindow += latency; - m_latencyCountWindow++; - if (latency > m_latencyMaxWindow) m_latencyMaxWindow = latency; - if (latency > m_latencyMaxAll) m_latencyMaxAll = latency; - m_dispatchCountAll++; - } -#endif - - auto delegateMsg = msg->GetData(); - if (delegateMsg) { - auto invoker = delegateMsg->GetInvoker(); - if (invoker) { -#if defined(DMQ_DATABUS_TOOLS) - dmq::TimePoint start = Timer::GetNow(); -#endif -#if defined(__cpp_exceptions) && !defined(DMQ_ASSERTS) - try { - bool success = invoker->Invoke(delegateMsg); - if (!selfExit) DMQ_ASSERT_TRUE(success); - } - catch (const std::bad_alloc& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled bad_alloc in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::invalid_argument& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled invalid_argument in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::runtime_error& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled runtime_error in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::exception& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled exception in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (...) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled unknown exception in delegate callback." << std::endl; - DMQ_ASSERT(); - } -#else - bool success = invoker->Invoke(delegateMsg); - if (!selfExit) DMQ_ASSERT_TRUE(success); -#endif - if (selfExit) { - t_self_exit = nullptr; - return; - } -#if defined(DMQ_DATABUS_TOOLS) - dmq::Duration invokeTime = Timer::GetNow() - start; - if (!selfExit) { - std::lock_guard lock(m_statsMutex); - m_invokeTotalWindow += invokeTime; - m_invokeCountWindow++; - if (invokeTime > m_invokeMaxWindow) m_invokeMaxWindow = invokeTime; - if (invokeTime > m_invokeMaxAll) m_invokeMaxAll = invokeTime; - } -#endif - } - } - break; - } - - case MSG_EXIT_THREAD: - { - t_self_exit = nullptr; - return; - } - - default: - DMQ_ASSERT(); - break; - } - - // Any message restarts the idle countdown - idle.Restart(); - - // msg goes out of scope here — may trigger self-destruction of 'this'. - // After this point do not access any member; check selfExit in while(). - } - t_self_exit = nullptr; -} - -#if defined(DMQ_DATABUS_TOOLS) -//---------------------------------------------------------------------------- -// SnapshotStats -//---------------------------------------------------------------------------- -StdlibThread::ThreadStats StdlibThread::SnapshotStats() -{ - // Need m_mutex only for (m_highQueue.size() + m_normalQueue.size()) - size_t currentDepth = GetQueueSize(); - - std::lock_guard lock(m_statsMutex); - ThreadStats stats; - stats.cpu_name = CPU_NAME; - stats.thread_name = THREAD_NAME; - stats.queue_depth = currentDepth; - stats.queue_depth_max_window = m_queueDepthMaxWindow; - stats.queue_depth_max_all = m_queueDepthMaxAll; - stats.queue_size_limit = MAX_QUEUE_SIZE; - - if (m_latencyCountWindow > 0) { - stats.latency_avg_ms = (float)std::chrono::duration_cast(m_latencyTotalWindow).count() / (static_cast(m_latencyCountWindow) * 1000.0f); - } else { - stats.latency_avg_ms = 0.0f; - } - - stats.latency_max_window_ms = (float)std::chrono::duration_cast(m_latencyMaxWindow).count() / 1000.0f; - stats.latency_max_all_ms = (float)std::chrono::duration_cast(m_latencyMaxAll).count() / 1000.0f; - - if (m_invokeCountWindow > 0) { - stats.invoke_avg_ms = (float)std::chrono::duration_cast(m_invokeTotalWindow).count() / (static_cast(m_invokeCountWindow) * 1000.0f); - } else { - stats.invoke_avg_ms = 0.0f; - } - - stats.invoke_max_window_ms = (float)std::chrono::duration_cast(m_invokeMaxWindow).count() / 1000.0f; - stats.invoke_max_all_ms = (float)std::chrono::duration_cast(m_invokeMaxAll).count() / 1000.0f; - - stats.dispatch_count = m_dispatchCountAll; - - // Reset windowed stats - m_queueDepthMaxWindow = 0; - m_latencyTotalWindow = dmq::Duration(0); - m_latencyCountWindow = 0; - m_latencyMaxWindow = dmq::Duration(0); - - m_invokeTotalWindow = dmq::Duration(0); - m_invokeCountWindow = 0; - m_invokeMaxWindow = dmq::Duration(0); - - return stats; -} -#endif - -} // namespace dmq::os - -#endif // DMQ_THREAD_STDLIB diff --git a/DelegateMQ/port/os/stdlib/StdlibThread.h b/DelegateMQ/port/os/stdlib/StdlibThread.h deleted file mode 100644 index e8cb21f..0000000 --- a/DelegateMQ/port/os/stdlib/StdlibThread.h +++ /dev/null @@ -1,311 +0,0 @@ -#ifndef _THREAD_STD_H -#define _THREAD_STD_H - -/// @file StdlibThread.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// @brief Standard C++ implementation of the DelegateMQ IThread interface. -/// -/// @details -/// This class provides a cross-platform implementation of the `IThread` interface using -/// standard C++11 primitives (`std::thread`, `std::mutex`, `std::condition_variable`). -/// It creates a dedicated worker thread with an event loop capable of processing -/// asynchronous delegates and system messages. -/// -/// **Key Features:** -/// * **Priority Queue:** One FIFO `std::deque` per priority level, so high-priority -/// delegate messages (e.g., system signals) are processed before normal ones, and -/// messages of the same priority are processed in the order they were dispatched. -/// * **Queue Full Policy:** Configurable `FullPolicy` (DROP or TIMEOUT), always enforced -- -/// `maxQueueSize == 0` falls back to `dmq::THREAD_DESKTOP_QUEUE_SIZE` rather than disabling -/// the cap, since this port backs its queue with a plain `std::deque` and would otherwise -/// grow without bound if the destination thread is dead/stuck. TIMEOUT waits up to -/// `dispatchTimeout` for the consumer before logging and dropping; DROP silently discards -/// immediately. FAULT (the default) triggers a system fault. -/// * **Watchdog Integration:** Includes a built-in heartbeat mechanism. If the thread loop -/// stalls (deadlock or infinite loop), the watchdog timer detects the failure. -/// * **Synchronized Start:** Uses `std::promise` and `std::future` to ensure the thread -/// is fully initialized and running before `CreateThread()` returns. -/// * **Debug Support:** Sets the native thread name on Windows and Linux to aid -/// debugging in IDEs and tools (Linux truncates names to 15 characters). -/// * **Start Gate:** Optional `SetStartGate(StartGate*)`, called before `CreateThread()`, -/// holds the thread ready but processing no messages, at any priority, until -/// `StartGate::Open()` releases every thread sharing the gate at once. - -#include "delegate/IThread.h" -#include "delegate/UnicastDelegate.h" -#include "./extras/util/Timer.h" -#include "port/os/common/ThreadMsg.h" -#include "port/os/common/StartGate.h" -#include -#include -#include -#include -#include -#include - -namespace dmq::os { - -/// @brief Policy applied when the thread message queue is full. See dmq::FullPolicy -/// in DelegateOpt.h for the canonical definition, shared by every dmq::os::Thread port. -using FullPolicy = dmq::FullPolicy; - -/// @brief What ExitThread() does with queued messages. See dmq::ExitPolicy in DelegateOpt.h. -using ExitPolicy = dmq::ExitPolicy; - -/// @brief Cross-platform thread for any system supporting C++11 std::thread (e.g. Windows, Linux). -/// @details The StdlibThread class creates a worker thread capable of dispatching and -/// invoking asynchronous delegates. -class StdlibThread : public dmq::IThread -{ - XALLOCATOR -public: -#if defined(DMQ_DATABUS_TOOLS) - /// @brief Statistics captured for thread monitoring. - struct ThreadStats { - dmq::xstring cpu_name; - dmq::xstring thread_name; - size_t queue_depth; // Current depth - size_t queue_depth_max_window;// Max depth since last snapshot - size_t queue_depth_max_all; // All-time max depth - size_t queue_size_limit; // Max allowed - float latency_avg_ms; // Avg wait in window - float latency_max_window_ms; // Max wait since last snapshot - float latency_max_all_ms; // All-time max wait - float invoke_avg_ms; // Avg execution in window - float invoke_max_window_ms; // Max execution since last snapshot - float invoke_max_all_ms; // All-time max execution - uint64_t dispatch_count; // Total dispatches (all-time) - }; -#endif - - /// Constructor - /// @param threadName The name of the thread for debugging. - /// @param maxQueueSize The maximum number of messages allowed in the queue. - /// 0 falls back to dmq::THREAD_DESKTOP_QUEUE_SIZE -- a high-water-mark - /// safety net, not a throughput limiter, against unbounded growth if - /// the destination thread is dead/stuck. - /// @param fullPolicy When the queue is full: FAULT (default), DROP, or TIMEOUT. - /// @param dispatchTimeout Duration to wait before giving up when policy is TIMEOUT. - /// @param cpuName Optional CPU/Core name grouping for monitoring tools. - StdlibThread(const char* threadName, size_t maxQueueSize = 0, FullPolicy fullPolicy = FullPolicy::FAULT, - dmq::Duration dispatchTimeout = dmq::DEFAULT_DISPATCH_TIMEOUT, const char* cpuName = ""); - StdlibThread(const std::string& threadName, size_t maxQueueSize = 0, FullPolicy fullPolicy = FullPolicy::FAULT, - dmq::Duration dispatchTimeout = dmq::DEFAULT_DISPATCH_TIMEOUT, const std::string& cpuName = "") - : StdlibThread(threadName.c_str(), maxQueueSize, fullPolicy, dispatchTimeout, cpuName.c_str()) {} - - /// Destructor - ~StdlibThread(); - - /// Called once to create the worker thread. If watchdogTimeout value - /// provided, the maximum watchdog interval is used. Otherwise no watchdog. - /// @param[in] watchdogTimeout - optional watchdog timeout. - /// @return TRUE if thread is created. FALSE otherwise. - bool CreateThread(std::optional watchdogTimeout = std::nullopt); - - /// Called once at program exit to shut down the worker thread. - /// @param[in] policy - DRAIN (default) invokes every message queued before this - /// call first; DISCARD invokes only the message already running and cancels - /// the rest (see dmq::ExitPolicy). Called from the thread's own message - /// handler (a self-exit), queued messages are always discarded. - void ExitThread(ExitPolicy policy = ExitPolicy::DRAIN); - - /// Get the ID of this thread instance - std::thread::id GetThreadId(); - - /// Get the ID of the currently executing thread - static std::thread::id GetCurrentThreadId(); - - /// Returns true if the calling thread is this thread - virtual bool IsCurrentThread() override; - - /// Get thread name - dmq::xstring GetThreadName() { return THREAD_NAME; } - - /// Get size of thread message queue. - size_t GetQueueSize(); - - /// Sleep for a duration. - /// @param[in] timeout - the duration to sleep. - static void Sleep(dmq::Duration timeout); - - /// Dispatch and invoke a delegate target on the destination thread. - /// @param[in] msg - Delegate message containing target function - /// arguments. - virtual bool DispatchDelegate(std::shared_ptr msg) override; - - /// @brief Register a handler invoked when DispatchDelegate() drops a message: - /// under FullPolicy::DROP (queue full, discarded immediately) or - /// FullPolicy::TIMEOUT (queue stayed full for dispatchTimeout, discarded). - /// Optional; unset by default. Called synchronously on the calling (producer) - /// thread, with the queue depth at the time of the drop. - void SetDroppedHandler(const dmq::UnicastDelegate& handler) { m_droppedHandler = handler; } - void SetDroppedHandler(dmq::UnicastDelegate&& handler) { m_droppedHandler = std::move(handler); } - - /// @brief Register a handler invoked on the worker thread before it processes - /// any message. Use it for per-thread setup (COM, a language runtime attach, - /// thread-local state, affinity). CreateThread() returns only after it completes. - /// @details Must be called while the thread is not running (before CreateThread(), - /// or after ExitThread()); calling it on a running thread faults. It runs again - /// on each CreateThread(). Messages dispatched meanwhile are queued, not lost. - void SetStartHandler(const dmq::UnicastDelegate& handler) { DMQ_ASSERT_TRUE(!m_thread); m_startHandler = handler; } - void SetStartHandler(dmq::UnicastDelegate&& handler) { DMQ_ASSERT_TRUE(!m_thread); m_startHandler = std::move(handler); } - - /// @brief Optional: hold this thread at `gate` once it is created, until - /// `gate->Open()`. Pass nullptr (the default) to start at once. - /// @details CreateThread() still runs the start handler and returns when the - /// thread is ready; the thread then processes nothing, at any priority, until - /// the gate opens. Use one gate for a group of threads so they all start - /// together after setup. See port/os/common/StartGate.h. Must be called while - /// the thread is not running; calling it on a running thread faults. - void SetStartGate(StartGate* gate) { DMQ_ASSERT_TRUE(!m_thread); m_startGate.Set(gate); } - - /// @brief Register a handler invoked on the worker thread after it processes - /// its last message, as the thread exits. Use it to undo SetStartHandler() setup. - /// @details Must be called while the thread is not running; calling it on a - /// running thread faults. The handler is copied when the thread starts. - /// ExitThread() from another thread returns after it completes. If the thread - /// exits itself (ExitThread() from a handler on this thread), it runs after the - /// owning StdlibThread may already be destroyed, so it must not touch that object. - void SetExitHandler(const dmq::UnicastDelegate& handler) { DMQ_ASSERT_TRUE(!m_thread); m_exitHandler = handler; } - void SetExitHandler(dmq::UnicastDelegate&& handler) { DMQ_ASSERT_TRUE(!m_thread); m_exitHandler = std::move(handler); } - - /// @brief Register a handler invoked on the worker thread when its queue has - /// been empty for `interval`, then again every `interval` while it stays empty. - /// Any message processed restarts the countdown. Use it for background work that - /// should yield to messages: polling, housekeeping, entering low power. - /// @details Must be called while the thread is not running; calling it on a - /// running thread faults. The handler and interval are copied when the thread - /// starts. Not called once ExitThread() has been requested. - /// @param[in] handler - the idle handler, or an empty delegate to disable. - /// @param[in] interval - quiet time before each call. Must be greater than zero. - /// Defaults to dmq::THREAD_IDLE_INTERVAL (DMQ_THREAD_IDLE_INTERVAL). - void SetIdleHandler(const dmq::UnicastDelegate& handler, dmq::Duration interval = dmq::THREAD_IDLE_INTERVAL) - { - DMQ_ASSERT_TRUE(!m_thread); - DMQ_ASSERT_TRUE(interval > dmq::Duration::zero()); - m_idleHandler = handler; - m_idleInterval = interval; - } - void SetIdleHandler(dmq::UnicastDelegate&& handler, dmq::Duration interval = dmq::THREAD_IDLE_INTERVAL) - { - DMQ_ASSERT_TRUE(!m_thread); - DMQ_ASSERT_TRUE(interval > dmq::Duration::zero()); - m_idleHandler = std::move(handler); - m_idleInterval = interval; - } - - /// @brief Manually update the watchdog alive timestamp. - /// @details The Process() loop refreshes the timestamp automatically on every iteration. - /// Call this from inside long-running message handlers to prevent a false watchdog - /// alarm when a handler legitimately takes longer than watchdogTimeout. - void ThreadCheck(); - - /// @brief Static method to check all registered threads for watchdog expiration. - static void WatchdogCheckAll(); - -#if defined(DMQ_DATABUS_TOOLS) - /// @brief Capture and reset windowed statistics. - ThreadStats SnapshotStats(); -#endif - -private: - StdlibThread(const StdlibThread&) = delete; - StdlibThread& operator=(const StdlibThread&) = delete; - - /// Entry point for the thread - void Process(); - - void SetThreadName(std::thread::native_handle_type handle, const dmq::xstring& name); - - /// Check watchdog is expired. Called by WatchdogCheckAll(), which the application - /// calls periodically, typically from its highest-priority task. Thread-safe. - void WatchdogCheck(); - - /// @brief Returns the head of the watchdog linked list. - static StdlibThread*& GetWatchdogHead(); - - /// @brief Returns the recursive mutex for protecting the watchdog list. - static dmq::RecursiveMutex& GetWatchdogLock(); - - std::optional m_thread; - std::atomic m_exit; - -#ifdef DMQ_ALLOCATOR - std::deque, stl_allocator>> m_highQueue; - std::deque, stl_allocator>> m_normalQueue; -#else - std::deque> m_highQueue; - std::deque> m_normalQueue; -#endif - std::mutex m_mutex; - std::condition_variable m_cv; - - // Condition variable to wake up blocked producers when space is available - std::condition_variable m_cvNotFull; - - const dmq::xstring THREAD_NAME; - const dmq::xstring CPU_NAME; - - // Max queue size (0 = unlimited) - const size_t MAX_QUEUE_SIZE; - - // Policy when queue is full - const FullPolicy FULL_POLICY; - - // Timeout duration for TIMEOUT policy - const dmq::Duration m_dispatchTimeout; - - // Optional handler invoked when a message is dropped (FullPolicy::DROP or TIMEOUT) - dmq::UnicastDelegate m_droppedHandler; - - // Optional handlers invoked on the worker thread at start, exit and when idle - dmq::UnicastDelegate m_startHandler; - dmq::UnicastDelegate m_exitHandler; - dmq::UnicastDelegate m_idleHandler; - dmq::Duration m_idleInterval = dmq::Duration::zero(); - - // Promise and future to synchronize thread start (constructed lazily in CreateThread) - std::optional> m_threadStartPromise; - std::optional> m_threadStartFuture; - - // Watchdog related members - std::atomic m_lastAliveTime{dmq::TimePoint()}; - std::atomic m_watchdogTimeout{dmq::Duration(0)}; - StdlibThread* m_watchdogNext = nullptr; - - // Optional start gate (SetStartGate()): its state, and whether the thread is - // held at it (the watchdog doesn't report a thread waiting by design) - StartGateClient m_startGate; - -#if defined(DMQ_DATABUS_TOOLS) - // Separate mutex for statistics to reduce contention on m_mutex - std::mutex m_statsMutex; - - // Monitoring statistics members - size_t m_queueDepthMaxWindow = 0; - size_t m_queueDepthMaxAll = 0; - - dmq::Duration m_latencyTotalWindow = dmq::Duration(0); - uint32_t m_latencyCountWindow = 0; - dmq::Duration m_latencyMaxWindow = dmq::Duration(0); - dmq::Duration m_latencyMaxAll = dmq::Duration(0); - - dmq::Duration m_invokeTotalWindow = dmq::Duration(0); - uint32_t m_invokeCountWindow = 0; - dmq::Duration m_invokeMaxWindow = dmq::Duration(0); - dmq::Duration m_invokeMaxAll = dmq::Duration(0); - - uint64_t m_dispatchCountAll = 0; -#endif -}; - -/// @brief Backward-compatible name: existing code referencing dmq::os::Thread -/// keeps compiling unchanged against the stdlib port. -using Thread = StdlibThread; - -} // namespace dmq::os - - -#endif diff --git a/DelegateMQ/port/os/threadx/ThreadXClock.h b/DelegateMQ/port/os/threadx/ThreadXClock.h deleted file mode 100644 index 7cce0ad..0000000 --- a/DelegateMQ/port/os/threadx/ThreadXClock.h +++ /dev/null @@ -1,56 +0,0 @@ -#ifndef THREADX_CLOCK_H -#define THREADX_CLOCK_H - -#include "tx_api.h" -#include -#include - -namespace dmq::os { - struct ThreadXClock { - // 1. Define duration traits - using rep = int64_t; - using period = std::milli; - using duration = std::chrono::duration; - using time_point = std::chrono::time_point; - static const bool is_steady = true; - - // 2. The critical "now()" function - static time_point now() noexcept { - static ULONG last = 0; - static uint64_t high = 0; - - // Enter Critical Section - // This prevents other threads (and ISRs) from interrupting - // the read-modify-write of 'last' and 'high'. - TX_INTERRUPT_SAVE_AREA - TX_DISABLE - - ULONG cur = tx_time_get(); - - constexpr uint64_t TICK_MODULO = static_cast(1ULL) << (sizeof(ULONG) * 8); - - if (cur < last) { - high += TICK_MODULO; - } - - last = cur; - - // Capture value before re-enabling interrupts - uint64_t ticks = high + cur; - - // Exit Critical Section - TX_RESTORE - - // tx_time_get() counts ThreadX ticks (TX_TIMER_TICKS_PER_SECOND - // per second), not milliseconds -- scale before returning, or - // every duration/deadline computed against this clock (e.g. - // dmq::util::Timer expirations) would run TX_TIMER_TICKS_PER_SECOND/1000x - // slower than requested. - uint64_t ms = (ticks * 1000ULL) / TX_TIMER_TICKS_PER_SECOND; - - return time_point(duration(static_cast(ms))); - } - }; -} // namespace dmq::os - -#endif // THREADX_CLOCK_H \ No newline at end of file diff --git a/DelegateMQ/port/os/threadx/ThreadXConditionVariable.h b/DelegateMQ/port/os/threadx/ThreadXConditionVariable.h deleted file mode 100644 index 5a2f699..0000000 --- a/DelegateMQ/port/os/threadx/ThreadXConditionVariable.h +++ /dev/null @@ -1,113 +0,0 @@ -#ifndef THREADX_CONDITION_VARIABLE_H -#define THREADX_CONDITION_VARIABLE_H - -#include "tx_api.h" -#include - -namespace dmq::os { - /// @brief Production-grade wrapper around ThreadX Semaphore to mimic std::condition_variable - /// @details - /// - Uses a Counting Semaphore (initialized to 0). - /// - ISR-safe notification logic (tx_semaphore_put). - /// - Robust tick overflow handling using elapsed time subtraction. - /// - /// @note Limitation: Unlike std::cv, a semaphore retains its signal state. - /// If notify() occurs before wait(), the wait will effectively "fall through". - class ThreadXConditionVariable - { - public: - ThreadXConditionVariable() - { - // Create a semaphore with initial count 0. - // Cast string literal to (CHAR*) to satisfy strict C++ compilers interfacing with C API. - UINT status = tx_semaphore_create(&m_sem, (CHAR*)"DMQ_CondVar", 0); - DMQ_ASSERT_TRUE(status == TX_SUCCESS); - } - - ~ThreadXConditionVariable() - { - tx_semaphore_delete(&m_sem); - } - - ThreadXConditionVariable(const ThreadXConditionVariable&) = delete; - ThreadXConditionVariable& operator=(const ThreadXConditionVariable&) = delete; - - /// @brief Wake up one waiting thread (ISR Safe) - void notify_one() noexcept - { - // ThreadX tx_semaphore_put is ISR-safe. - // It increments the semaphore count. - tx_semaphore_put(&m_sem); - } - - /// @brief Wait indefinitely until predicate is true - template - void wait(Lock& lock, Predicate pred) - { - while (!pred()) - { - lock.unlock(); - // Wait indefinitely - tx_semaphore_get(&m_sem, TX_WAIT_FOREVER); - lock.lock(); - } - } - - /// @brief Wait until predicate is true or timeout expires - template - bool wait_for(Lock& lock, std::chrono::milliseconds timeout, Predicate pred) - { - // 1. Convert timeout to ticks safely - // Use unsigned long long to prevent overflow during multiplication (ms * ticks_per_sec) - const ULONG ticksPerSec = TX_TIMER_TICKS_PER_SECOND; - unsigned long long totalTicks = (static_cast(timeout.count()) * ticksPerSec) / 1000ULL; - - // Ensure at least 1 tick if timeout > 0 to avoid immediate timeout - if (totalTicks == 0 && timeout.count() > 0) totalTicks = 1; - - // Cap at ThreadX max wait if necessary, though unlikely for ms ranges - const ULONG timeoutTicks = (totalTicks > 0xFFFFFFFF) ? 0xFFFFFFFF : (ULONG)totalTicks; - - const ULONG startTick = tx_time_get(); - - while (!pred()) - { - ULONG now = tx_time_get(); - - // Overflow-safe subtraction (works because ULONG is unsigned) - ULONG elapsed = now - startTick; - - if (elapsed >= timeoutTicks) - return pred(); // Timeout expired - - ULONG remaining = timeoutTicks - elapsed; - - lock.unlock(); - - // Wait for the semaphore or timeout - UINT res = tx_semaphore_get(&m_sem, remaining); - - lock.lock(); - - if (res != TX_SUCCESS) - { - // TX_NO_INSTANCE (0x0D) or TX_WAIT_ABORTED means we didn't get the token. - // Timeout occurred or wait aborted. - return pred(); - } - - // If res == TX_SUCCESS, we consumed a token. - // Loop around and check pred() again. - // If pred() is false, we consumed a signal intended for state that isn't ready, - // effectively acting as a "spurious wakeup" handler. - } - - return true; - } - - private: - TX_SEMAPHORE m_sem; - }; -} // namespace dmq::os - -#endif // THREADX_CONDITION_VARIABLE_H \ No newline at end of file diff --git a/DelegateMQ/port/os/threadx/ThreadXCriticalSection.h b/DelegateMQ/port/os/threadx/ThreadXCriticalSection.h deleted file mode 100644 index 35f7ea7..0000000 --- a/DelegateMQ/port/os/threadx/ThreadXCriticalSection.h +++ /dev/null @@ -1,89 +0,0 @@ -#ifndef THREADX_CRITICAL_SECTION_H -#define THREADX_CRITICAL_SECTION_H - -/// @file ThreadXCriticalSection.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief ISR-safe critical section for ThreadX. -/// -/// @details -/// ThreadX's TX_MUTEX cannot be used from a genuine hardware ISR: both -/// tx_mutex_create() and tx_mutex_get() check TX_THREAD_GET_SYSTEM_STATE() -/// and return TX_CALLER_ERROR when called from interrupt context (verified -/// directly against common/src/txe_mutex_create.c and txe_mutex_get.c). -/// This type exists for the narrow set of call sites that must work from -/// BOTH thread and ISR context -- currently dmq::util::Timer's internal -/// list lock, since dmq::util::Timer::ProcessTimers() is documented as -/// callable from the highest-priority context available, including a -/// hardware ISR. -/// -/// It works by disabling/restoring interrupts directly, the same underlying -/// mechanism ThreadXClock.h uses via TX_INTERRUPT_SAVE_AREA / TX_DISABLE / -/// TX_RESTORE. This class can't use those macros themselves, though: they -/// declare a local save-area variable whose NAME is port-specific (e.g. -/// "interrupt_save" on most ARM ports, "tx_saved_posture" on Linux/GNU) and -/// only valid within the function that declared it -- fine for ThreadXClock.h, -/// where disable and restore happen in the same function, but lock() and -/// unlock() here are separate calls, so the saved posture must survive in a -/// member variable across the gap. Instead this uses tx_interrupt_control(), -/// the portable, publicly documented ThreadX service for exactly this: it -/// takes the new posture (TX_INT_DISABLE) and returns the previous one to -/// restore later, with no port-specific local variable involved. It's the -/// same interrupt-lockout primitive TX_DISABLE/TX_RESTORE use internally, so -/// it carries the same ISR-safety guarantee. -/// -/// *** NARROW PURPOSE -- DO NOT USE THIS AS A GENERAL-PURPOSE LOCK *** -/// Holding this masks ALL maskable interrupts on the CPU for as long as it -/// is held. Only use it to protect something genuinely tiny and bounded -/// that may be touched from ISR context. Do NOT use it in place of -/// dmq::Mutex / dmq::RecursiveMutex for ordinary thread-to-thread -/// synchronization (e.g. DataBus internals, a Thread's message queue) -- -/// anything that can block, take a while, or run for an unbounded time -/// must not run with interrupts globally masked; that is a real-time -/// correctness bug on hardware, not just a style issue. -/// -/// *** NOT RE-LOCKABLE ON THE SAME INSTANCE *** -/// Unlike dmq::RecursiveMutex, calling lock() twice on the SAME instance -/// without an intervening unlock() is incorrect: the second lock() call -/// overwrites the single saved-interrupt-state member with the (already -/// disabled) inner posture, so the outer unlock() restores the wrong -/// state and interrupts are left disabled permanently. There is no -/// "recursive" variant of this type -- it has no ownership concept to -/// make recursion meaningful, and Timer's own usage never nests. Locking -/// two DIFFERENT instances in proper LIFO lock/unlock order is fine: each -/// instance saves and restores its own interrupt state independently. - -#include "tx_api.h" - -namespace dmq::os { - - // ========================================================================= - // ThreadXCriticalSection - // See the file-level comment above before using this type anywhere new. - // ========================================================================= - class ThreadXCriticalSection { - public: - ThreadXCriticalSection() = default; - - void lock() { - m_savedPosture = tx_interrupt_control(TX_INT_DISABLE); - } - - void unlock() { - tx_interrupt_control(m_savedPosture); - } - - // No try_lock(): interrupt masking cannot fail to "acquire", so a - // try_lock() here would always trivially succeed and isn't meaningful. - - ThreadXCriticalSection(const ThreadXCriticalSection&) = delete; - ThreadXCriticalSection& operator=(const ThreadXCriticalSection&) = delete; - - private: - UINT m_savedPosture = 0; - }; - -} // namespace dmq::os - -#endif // THREADX_CRITICAL_SECTION_H diff --git a/DelegateMQ/port/os/threadx/ThreadXDelegateQueue.h b/DelegateMQ/port/os/threadx/ThreadXDelegateQueue.h deleted file mode 100644 index 1efd46f..0000000 --- a/DelegateMQ/port/os/threadx/ThreadXDelegateQueue.h +++ /dev/null @@ -1,253 +0,0 @@ -#ifndef THREADX_DELEGATE_QUEUE_H -#define THREADX_DELEGATE_QUEUE_H - -/// @file ThreadXDelegateQueue.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief Thin RAII wrapper around a pair of ThreadX TX_QUEUE primitives used -/// by dmq::os::Thread to carry pending ThreadMsg pointers, with priority -/// support. See the Priority enum in delegate/DelegateMsg.h for the -/// cross-port ordering contract this class must uphold. -/// -/// @details -/// *** DO NOT "SIMPLIFY" THIS BACK TO ONE QUEUE + tx_queue_front_send() *** -/// An earlier version of this class used a single TX_QUEUE and called -/// tx_queue_front_send() for HIGH priority messages. That is WRONG: sending -/// to the front of a single queue makes HIGH messages a LIFO stack relative -/// to each other, not a FIFO lane. Concretely, starting from [Normal1]: -/// 1. HIGH-A sent to front -> [HIGH-A, Normal1] -/// 2. HIGH-B sent to front -> [HIGH-B, HIGH-A, Normal1] -/// The consumer then dequeues HIGH-B before HIGH-A, even though A arrived -/// first -- exactly backwards. See DelegateMsg.h's Priority comment for the -/// required contract (HIGH jumps ahead of NORMAL, but FIFO is preserved -/// within each priority). -/// -/// The fix: two independent TX_QUEUE instances, one per priority lane, each -/// always pushed to the BACK (tx_queue_send, never tx_queue_front_send). -/// ThreadX gives no way to block on "either of two queues has data" the way -/// a std::condition_variable can wait on an arbitrary predicate, so a -/// TX_SEMAPHORE counting semaphore is used as a shared "doorbell": every -/// successful Send() (to either lane) puts the semaphore once; Receive() -/// gets the semaphore (the single blocking wait) and then does a -/// non-blocking pop, checking the HIGH lane first so it still drains ahead -/// of NORMAL. This mirrors StdlibThread's two-std::deque + one- -/// condition_variable design and ZephyrDelegateQueue's two-k_msgq + k_poll -/// design -- same shape, RTOS-native primitives. -/// -/// Each lane is sized to the full requested 'capacity' (like -/// ZephyrDelegateQueue), so worst-case combined depth is 2x capacity rather -/// than exactly capacity -- this doubles queue memory relative to the old -/// single-queue design. Unlike FreeRTOS's counting semaphore, ThreadX's -/// tx_semaphore_create() has no "max count" ceiling to size -- a put() only -/// fails on ULONG overflow, which combined lane capacity never approaches. -/// -/// Isolates the native tx_queue_create/tx_queue_send/tx_queue_receive/ -/// tx_queue_delete/tx_semaphore_create/tx_semaphore_put/tx_semaphore_get -/// calls (and the ULONG-word buffer sizing they require) behind a small type -/// so Thread.cpp's DispatchDelegate()/Run() read as policy and dispatch -/// logic, not ThreadX API plumbing. This class owns no policy decisions of -/// its own (FullPolicy, timeout computation, and stats stay in Thread.cpp) -/// -- it only knows how to move ThreadMsg* pointers through two -/// fixed-capacity ThreadX queues in priority order. - -#include -#include "port/os/common/ThreadMsg.h" -#include -#include -#include - -namespace dmq::os { - -class ThreadXDelegateQueue -{ -public: - ThreadXDelegateQueue() - { - memset(&m_highQueue, 0, sizeof(m_highQueue)); - memset(&m_normalQueue, 0, sizeof(m_normalQueue)); - memset(&m_countSem, 0, sizeof(m_countSem)); - } - ~ThreadXDelegateQueue() { Destroy(); } - - ThreadXDelegateQueue(const ThreadXDelegateQueue&) = delete; - ThreadXDelegateQueue& operator=(const ThreadXDelegateQueue&) = delete; - - /// Create the underlying HIGH and NORMAL queues, each with room for - /// 'capacity' pointers, plus the counting semaphore doorbell (initial - /// count 0). - /// @param name Queue/semaphore name; ThreadX stores this pointer, not a - /// copy, so it must outlive the queue (callers pass THREAD_NAME.c_str(), - /// which lives as long as the owning Thread). The same name is shared - /// across both queues and the semaphore -- ThreadX names are purely - /// informational for kernel-aware debuggers and need not be unique. - /// @return true on success, false if any buffer allocation or ThreadX - /// create call failed. - bool Create(size_t capacity, const char* name) - { - if (m_highQueue.tx_queue_id != 0 && m_normalQueue.tx_queue_id != 0 && m_countSem.tx_semaphore_id != 0) - return true; - - // ThreadX queues store "words" (ULONGs). We're passing a pointer - // (ThreadMsg*), so round up to enough words to hold one. - UINT msgSizeWords = (sizeof(ThreadMsg*) + sizeof(ULONG) - 1) / sizeof(ULONG); - ULONG queueMemSizeWords = static_cast(capacity) * msgSizeWords; - - // Queue buffers use new (std::nothrow) for the same reason as the thread - // stack (see ThreadXThread::CreateThread()): ThreadX needs caller-supplied - // memory, and multi-KB buffers don't belong in the fixed-block allocator. - // - // On any failure below, Destroy() deletes whatever was already created - // and frees the buffers, so a later Create() never re-creates a live - // queue or frees memory a live queue still uses. - m_highQueueMemory.reset(new (std::nothrow) ULONG[queueMemSizeWords]); - m_normalQueueMemory.reset(new (std::nothrow) ULONG[queueMemSizeWords]); - if (!m_highQueueMemory || !m_normalQueueMemory) { - Destroy(); - return false; - } - - UINT ret = tx_queue_create(&m_highQueue, - const_cast(name), - msgSizeWords, - m_highQueueMemory.get(), - queueMemSizeWords * sizeof(ULONG)); - if (ret != TX_SUCCESS) { - Destroy(); - return false; - } - - ret = tx_queue_create(&m_normalQueue, - const_cast(name), - msgSizeWords, - m_normalQueueMemory.get(), - queueMemSizeWords * sizeof(ULONG)); - if (ret != TX_SUCCESS) { - Destroy(); - return false; - } - - ret = tx_semaphore_create(&m_countSem, const_cast(name), 0); - if (ret != TX_SUCCESS) { - Destroy(); - return false; - } - return true; - } - - bool IsCreated() const - { - return m_highQueue.tx_queue_id != 0 && m_normalQueue.tx_queue_id != 0 && m_countSem.tx_semaphore_id != 0; - } - - /// Send a message pointer. 'highPriority' routes to the HIGH lane, which - /// Receive() always drains first; otherwise the NORMAL lane. Both lanes - /// are always pushed to the BACK -- see the file-level comment for why - /// "send to front" must never be reintroduced here. 'waitOption' is - /// TX_NO_WAIT for non-blocking, TX_WAIT_FOREVER to block forever, or a - /// finite tick count for a bounded wait; it applies only to the queue - /// push (each lane has its own independent capacity -- there is no - /// combined-depth wait across both). Putting the doorbell semaphore never - /// blocks and cannot realistically fail (only on ULONG overflow, far - /// beyond any real combined lane capacity). - /// @return true if the message was enqueued. - bool Send(ThreadMsg* msg, bool highPriority, ULONG waitOption) - { - TX_QUEUE* q = highPriority ? &m_highQueue : &m_normalQueue; - if (tx_queue_send(q, &msg, waitOption) != TX_SUCCESS) - return false; - tx_semaphore_put(&m_countSem); - return true; - } - - /// Receive a message pointer, blocking up to 'waitOption'. The HIGH lane - /// is always checked -- and drained -- first, so a pending HIGH message - /// is returned even if NORMAL messages arrived earlier. Blocks on the - /// doorbell semaphore (the single native wait), then does a - /// non-blocking pop from whichever lane has data; the semaphore count - /// guarantees at least one lane is non-empty once the get succeeds. - /// @return the message, or nullptr on timeout. - ThreadMsg* Receive(ULONG waitOption) - { - if (tx_semaphore_get(&m_countSem, waitOption) != TX_SUCCESS) - return nullptr; // timed out waiting for either lane - - ThreadMsg* msg = nullptr; - if (tx_queue_receive(&m_highQueue, &msg, TX_NO_WAIT) == TX_SUCCESS) - return msg; - if (tx_queue_receive(&m_normalQueue, &msg, TX_NO_WAIT) == TX_SUCCESS) - return msg; - return nullptr; - } - - /// Combined number of messages waiting across both lanes. - size_t Size() - { - if (m_highQueue.tx_queue_id == 0 || m_normalQueue.tx_queue_id == 0) - return 0; - - ULONG enqueued = 0; - ULONG available = 0; - TX_THREAD* suspension_list = nullptr; - ULONG suspension_count = 0; - TX_QUEUE* next_queue = nullptr; - size_t total = 0; - - if (tx_queue_info_get(&m_highQueue, nullptr, &enqueued, &available, - &suspension_list, &suspension_count, &next_queue) == TX_SUCCESS) { - total += static_cast(enqueued); - } - if (tx_queue_info_get(&m_normalQueue, nullptr, &enqueued, &available, - &suspension_list, &suspension_count, &next_queue) == TX_SUCCESS) { - total += static_cast(enqueued); - } - return total; - } - - /// Remove and delete every pending message in both lanes without - /// blocking. Used during shutdown once the owning thread has stopped - /// consuming the queues. - /// Each message is canceled first (CancelThreadMsg()), releasing a sender - /// blocked waiting on it. - void DrainAndDelete() - { - ThreadMsg* msg = nullptr; - while (tx_queue_receive(&m_highQueue, &msg, TX_NO_WAIT) == TX_SUCCESS) { - CancelThreadMsg(*msg); // Release a sender blocked on it - delete msg; - } - while (tx_queue_receive(&m_normalQueue, &msg, TX_NO_WAIT) == TX_SUCCESS) { - CancelThreadMsg(*msg); // Release a sender blocked on it - delete msg; - } - } - - void Destroy() - { - if (m_highQueue.tx_queue_id != 0) { - tx_queue_delete(&m_highQueue); - memset(&m_highQueue, 0, sizeof(m_highQueue)); - } - if (m_normalQueue.tx_queue_id != 0) { - tx_queue_delete(&m_normalQueue); - memset(&m_normalQueue, 0, sizeof(m_normalQueue)); - } - if (m_countSem.tx_semaphore_id != 0) { - tx_semaphore_delete(&m_countSem); - memset(&m_countSem, 0, sizeof(m_countSem)); - } - m_highQueueMemory.reset(); - m_normalQueueMemory.reset(); - } - -private: - TX_QUEUE m_highQueue; - TX_QUEUE m_normalQueue; - TX_SEMAPHORE m_countSem; - std::unique_ptr m_highQueueMemory; - std::unique_ptr m_normalQueueMemory; -}; - -} // namespace dmq::os - -#endif // THREADX_DELEGATE_QUEUE_H diff --git a/DelegateMQ/port/os/threadx/ThreadXMutex.h b/DelegateMQ/port/os/threadx/ThreadXMutex.h deleted file mode 100644 index 40cb20c..0000000 --- a/DelegateMQ/port/os/threadx/ThreadXMutex.h +++ /dev/null @@ -1,48 +0,0 @@ -#ifndef THREADX_MUTEX_H -#define THREADX_MUTEX_H - -#include "tx_api.h" - -namespace dmq::os { - - // ========================================================================= - // ThreadXMutex - // Wraps TX_MUTEX. - // ========================================================================= - class ThreadXMutex { - public: - ThreadXMutex() { - // Cast string literal to (CHAR*) for strict compliance - UINT status = tx_mutex_create(&m_mutex, (CHAR*)"DMQ_Mutex", TX_INHERIT); - DMQ_ASSERT_TRUE(status == TX_SUCCESS); - } - - ~ThreadXMutex() { - tx_mutex_delete(&m_mutex); - } - - void lock() { - tx_mutex_get(&m_mutex, TX_WAIT_FOREVER); - } - - // REQUIRED for std::unique_lock compatibility - bool try_lock() { - return tx_mutex_get(&m_mutex, TX_NO_WAIT) == TX_SUCCESS; - } - - void unlock() { - tx_mutex_put(&m_mutex); - } - - ThreadXMutex(const ThreadXMutex&) = delete; - ThreadXMutex& operator=(const ThreadXMutex&) = delete; - - private: - TX_MUTEX m_mutex; - }; - - // ThreadX Mutexes are recursive by default, so this alias is valid. - using ThreadXRecursiveMutex = ThreadXMutex; -} // namespace dmq::os - -#endif // THREADX_MUTEX_H \ No newline at end of file diff --git a/DelegateMQ/port/os/threadx/ThreadXThisThread.h b/DelegateMQ/port/os/threadx/ThreadXThisThread.h deleted file mode 100644 index 6656685..0000000 --- a/DelegateMQ/port/os/threadx/ThreadXThisThread.h +++ /dev/null @@ -1,57 +0,0 @@ -#ifndef THREADX_THIS_THREAD_H -#define THREADX_THIS_THREAD_H - -/// @file ThreadXThisThread.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief Portable sleep_for()/yield() for the calling thread, ThreadX backend. -/// -/// @details -/// This is dmq::ThisThread for this port (see DelegateOpt.h). GetCurrent() -/// uses RegistryCurrentThread, keyed by the calling thread's control block. Exists so -/// library internals that need to delay or yield (e.g. RetryMonitor backoff) -/// aren't forced to pull in the full dmq::os::Thread class -- which also -/// drags in the message queue, watchdog, and stats machinery -- just to -/// sleep. dmq::os::Thread::Sleep() forwards here too, so the ThreadX delay -/// call is implemented exactly once. - -#include -#include "ThreadXMutex.h" -#include "port/os/common/CurrentThreadStorage.h" -#include - -namespace dmq::os { - - /// @brief Key for RegistryCurrentThread: the calling thread's control block. - /// @TODO: Return 0 inside an ISR if your target can detect it (e.g. read IPSR on - /// ARM Cortex-M). tx_thread_identify() returns the interrupted thread there, so - /// dmq::ThisThread::GetCurrent() from an ISR returns that thread's IThread - /// instead of nullptr. See docs/PORTING.md, "Current Thread". - inline uintptr_t ThreadXCurrentThreadKey() { - return reinterpret_cast(tx_thread_identify()); - } - - struct ThreadXThisThread : RegistryCurrentThread { - template - static void sleep_for(std::chrono::duration d) { - const auto ms = std::chrono::duration_cast(d); - auto count = ms.count(); - // Round up so a sub-tick sleep still yields the CPU for at least - // one tick rather than returning immediately. - ULONG ticks = static_cast((count * TX_TIMER_TICKS_PER_SECOND) / 1000); - if (ticks == 0 && count > 0) ticks = 1; - tx_thread_sleep(ticks); - } - - static void yield() noexcept { - // ThreadX has no separate "yield" API -- relinquish is the - // documented way to hand the CPU to other ready threads of the - // same priority. - tx_thread_relinquish(); - } - }; - -} // namespace dmq::os - -#endif // THREADX_THIS_THREAD_H diff --git a/DelegateMQ/port/os/threadx/ThreadXThread.cpp b/DelegateMQ/port/os/threadx/ThreadXThread.cpp deleted file mode 100644 index 932445c..0000000 --- a/DelegateMQ/port/os/threadx/ThreadXThread.cpp +++ /dev/null @@ -1,761 +0,0 @@ -// Compiles to nothing unless DMQ_THREAD_THREADX is selected, so every DelegateMQ source -// file can be added to a build (see src/DelegateMQ.cpp). -#include "delegate/DelegateSelect.h" -#if defined(DMQ_THREAD_THREADX) - -#include "DelegateMQ.h" -#include "ThreadXThread.h" -#include "port/os/common/ThreadMsg.h" -#include "port/os/common/ThreadHooks.h" -#include "extras/util/Fault.h" -#include -#include // for memset -#include // for std::nothrow - -// Define DMQ_ASSERT_TRUE if not already defined -#ifndef DMQ_ASSERT_TRUE -#define DMQ_ASSERT_TRUE(x) if(!(x)) { while(1); } // Replace with your fault handler -#endif - -namespace dmq::os { - -using namespace dmq; -using namespace dmq::util; - -//---------------------------------------------------------------------------- -// Thread Constructor -//---------------------------------------------------------------------------- -ThreadXThread::ThreadXThread(const char* threadName, size_t maxQueueSize, FullPolicy fullPolicy, dmq::Duration dispatchTimeout, const char* cpuName) - : THREAD_NAME(threadName) - , CPU_NAME(cpuName) - , m_queueSize((maxQueueSize == 0) ? DEFAULT_QUEUE_SIZE : maxQueueSize) - , FULL_POLICY(fullPolicy) - , m_dispatchTimeout(dispatchTimeout) - , m_exit(false) -{ - // Zero out control blocks for safety (m_queue zeroes its own control - // block in ThreadXDelegateQueue's constructor) - memset(&m_thread, 0, sizeof(m_thread)); - memset(&m_exitSem, 0, sizeof(m_exitSem)); - memset(&m_startSem, 0, sizeof(m_startSem)); - -#if defined(DMQ_DATABUS_TOOLS) - tx_mutex_create(&m_statMutex, (CHAR*)"StatMutex", TX_NO_INHERIT); -#endif - - // Default Priority - m_priority = static_cast(dmq::THREADX_THREAD_PRIORITY); // DMQ_THREADX_THREAD_PRIORITY -} - -//---------------------------------------------------------------------------- -// Thread Destructor -//---------------------------------------------------------------------------- -ThreadXThread::~ThreadXThread() -{ - // Deleting a ThreadXThread from one of its own callbacks is not supported: the - // destructor would free the stack and control block the thread is still - // running on, and ThreadX/Zephyr (unlike FreeRTOS, whose idle task frees a - // self-deleted task's stack) have no way to free them afterwards. Fault - // immediately instead of corrupting memory. To stop a thread from inside - // its own callback, call ExitThread() and delete the object from another - // thread. - if (m_thread.tx_thread_id != 0 && tx_thread_identify() == &m_thread) - DMQ_ASSERT(); - - ExitThread(); - - const dmq::LockGuard lock(GetWatchdogLock()); - ThreadXThread** pp = &GetWatchdogHead(); - while (*pp != nullptr) - { - if (*pp == this) - { - *pp = this->m_watchdogNext; - this->m_watchdogNext = nullptr; - break; - } - pp = &((*pp)->m_watchdogNext); - } - -#if defined(DMQ_DATABUS_TOOLS) - tx_mutex_delete(&m_statMutex); -#endif - - // Guard against deleting invalid semaphore - if (m_exitSem.tx_semaphore_id != 0) { - tx_semaphore_delete(&m_exitSem); - } - if (m_startSem.tx_semaphore_id != 0) { - tx_semaphore_delete(&m_startSem); - } -} - -//---------------------------------------------------------------------------- -// CreateThread -//---------------------------------------------------------------------------- -bool ThreadXThread::CreateThread(std::optional watchdogTimeout) -{ - // Check if thread is already created (tx_thread_id is non-zero if created) - if (m_thread.tx_thread_id == 0) - { - // Reset from a previous ExitThread(), so the thread can be created again - m_exit.store(false); - // Held from creation, so the watchdog never sees a gated thread as hung - // before it reaches the gate (e.g. created before the scheduler runs) - m_startGate.OnCreate(); - // Set before the thread exists: its loop reads the timeout before its - // first queue wait, and an idle thread waits forever with no timeout - m_lastAliveTime.store(Timer::GetNow()); - m_watchdogTimeout.store(watchdogTimeout.value_or(dmq::Duration(0))); - m_discard.store(false); - - // 0. Create Synchronization Semaphore (Critical for cleanup) - if (m_exitSem.tx_semaphore_id == 0) { - tx_semaphore_create(&m_exitSem, (CHAR*)"ExitSem", 0); - } - if (m_startSem.tx_semaphore_id == 0) { - tx_semaphore_create(&m_startSem, (CHAR*)"StartSem", 0); - } - - // Called from a thread, CreateThread() waits for the start handler. From - // tx_application_define() (no current thread) it cannot block; the start - // handler then runs when the kernel starts, still before any message. - m_startSync = (tx_thread_identify() != TX_NULL); - - // --- 1. Create Queue --- - DMQ_ASSERT_TRUE(m_queue.Create(m_queueSize, THREAD_NAME.c_str())); - - // --- 2. Create Thread --- - // Stack must be ULONG aligned. - - // Stack Size Rounding - ULONG stackSizeWords = (STACK_SIZE + sizeof(ULONG) - 1) / sizeof(ULONG); - - // ThreadX requires the caller to supply this memory. It's allocated with - // new (std::nothrow) on purpose (the CLAUDE.md "no new" rule allows a - // justified exception): the fixed-block allocator is sized for small - // objects and has a limited number of size classes - // (DMQ_XALLOCATOR_MAX_ALLOCATORS), so multi-KB buffers would exhaust it, - // and a ThreadX byte pool would require the application to create one. - // Allocated once per CreateThread(), freed by ExitThread()/the destructor. - m_stackMemory.reset(new (std::nothrow) ULONG[stackSizeWords]); - if (!m_stackMemory) - BAD_ALLOC(); - - UINT ret = tx_thread_create(&m_thread, - (CHAR*)THREAD_NAME.c_str(), - &ThreadXThread::Process, - 0, // Unused: see GetInstanceRegistry() - m_stackMemory.get(), - stackSizeWords * sizeof(ULONG), - m_priority, - m_priority, - TX_NO_TIME_SLICE, - TX_DONT_START); - - if (ret == TX_SUCCESS) { - // Register before resuming: the thread must never be able to run - // (and call Process()) before its registry entry exists. - { - const dmq::LockGuard lock(GetInstanceRegistryLock()); - GetInstanceRegistry()[&m_thread] = this; - } - tx_thread_resume(&m_thread); - - // Wait for the start handler to complete - if (m_startSync) - tx_semaphore_get(&m_startSem, TX_WAIT_FOREVER); - } - - DMQ_ASSERT_TRUE(ret == TX_SUCCESS); - - m_lastAliveTime.store(Timer::GetNow()); - - if (watchdogTimeout.has_value()) - { - - const dmq::LockGuard lock(GetWatchdogLock()); - - // Add to watchdog registry if not already present - bool found = false; - ThreadXThread* p = GetWatchdogHead(); - while (p != nullptr) - { - if (p == this) - { - found = true; - break; - } - p = p->m_watchdogNext; - } - - if (!found) - { - m_watchdogNext = GetWatchdogHead(); - GetWatchdogHead() = this; - } - } - } - return true; -} - -//---------------------------------------------------------------------------- -// SetThreadPriority -//---------------------------------------------------------------------------- -void ThreadXThread::SetThreadPriority(UINT priority) -{ - m_priority = priority; - - // If the thread is already running, update it live - if (m_thread.tx_thread_id != 0) { - UINT oldPriority; - tx_thread_priority_change(&m_thread, m_priority, &oldPriority); - } -} - -//---------------------------------------------------------------------------- -// GetThreadPriority -//---------------------------------------------------------------------------- -UINT ThreadXThread::GetThreadPriority() -{ - return m_priority; -} - -//---------------------------------------------------------------------------- -// ExitThread -//---------------------------------------------------------------------------- -void ThreadXThread::ExitThread(ExitPolicy policy) -{ - if (m_queue.IsCreated()) - { - // Set before m_exit: Run() reads it for every message ahead of the exit message - m_discard.store(policy == ExitPolicy::DISCARD); - m_exit.store(true); - - // A thread held at its start gate isn't waiting on its queue: wake it so it - // sees the exit flag (set above) and leaves. Never touches the gate itself, - // which may be destroyed once the thread is released. - m_startGate.Wake(); - - // Determine self-exit BEFORE attempting to enqueue the exit message. - // If this thread is destroying itself from within its own dispatched - // callback, it is not consuming its own queue right now -- it is - // blocked here, inside ExitThread(). A blocking tx_queue_send() would - // deadlock forever if the queue happened to be full. No message needs - // to be queued in that case: Run()'s dispatch loop already checks - // m_selfExitPtr immediately after the current callback invoke - // returns, and unwinds without touching 'this' again. - // - // A self-exiting thread must also NOT do the cleanup below: it is still - // running on m_stackMemory with m_thread linked in the kernel, so - // deleting the queue, wiping m_thread or freeing the stack here would - // corrupt ThreadX state. Set the flags and return; the cleanup runs in a - // later ExitThread() from another thread (typically ~ThreadXThread()), - // which sees m_selfExited and waits for the thread to finish instead of - // doing the exit-message handshake. Same approach as ZephyrThread. - TX_THREAD* currentThread = tx_thread_identify(); - bool isSelfExit = (currentThread == &m_thread); - - if (isSelfExit) { - m_selfExited.store(true); - if (m_selfExitPtr) { *m_selfExitPtr = true; m_selfExitPtr = nullptr; } - m_startGate.Leave(); // exited from its start handler: never reaches the gate - // Self-exit: this thread runs no more messages, and the object may be - // destroyed once this handler returns. Stop watchdog checks now. - m_watchdogTimeout.store(dmq::Duration(0)); - return; - } - - if (m_selfExited.load()) { - // The thread self-exited earlier and is returning (or has returned) - // from Run() on its own, possibly still running its exit handler. - // Wait until ThreadX marks it finished before terminating/deleting - // it below. Not from an ISR: there it can't block, as above. - if (currentThread != nullptr) { - UINT state = TX_READY; - while (tx_thread_info_get(&m_thread, nullptr, &state, nullptr, nullptr, nullptr, - nullptr, nullptr, nullptr) == TX_SUCCESS - && state != TX_COMPLETED && state != TX_TERMINATED) { - tx_thread_sleep(1); - } - } - } else { - // Send exit message - ThreadMsg* msg = new (std::nothrow) ThreadMsg(MSG_EXIT_THREAD); - if (msg) - { - // Wait forever to ensure message is sent - if (!m_queue.Send(msg, /*highPriority=*/false, TX_WAIT_FOREVER)) - { - delete msg; // Failed to send, prevent leak - } - } - - // If tx_thread_identify() returns NULL (ISR context), we shouldn't block. - if (currentThread != nullptr) { - // Wait for Run() to signal completion - tx_semaphore_get(&m_exitSem, TX_WAIT_FOREVER); - } - } - - // Force terminate if still running (safety net) - // tx_thread_terminate returns TX_SUCCESS if terminated or TX_THREAD_ERROR if already terminated - // The thread has finished (or, on a self-exit, is in its last handler): - // stop watchdog checks. Not earlier, so a thread that hangs while - // ExitThread() waits for it is still reported. - m_watchdogTimeout.store(dmq::Duration(0)); - - tx_thread_terminate(&m_thread); - tx_thread_delete(&m_thread); - - m_queue.DrainAndDelete(); - m_queue.Destroy(); - - // Remove the registry entry before clearing/reusing the control block - // (see GetInstanceRegistry() for why this exists). - { - const dmq::LockGuard lock(GetInstanceRegistryLock()); - GetInstanceRegistry().erase(&m_thread); - } - - // Clear control block so CreateThread could potentially be called again - memset(&m_thread, 0, sizeof(m_thread)); - m_selfExited.store(false); - } -} - -//---------------------------------------------------------------------------- -// GetThreadId -//---------------------------------------------------------------------------- -TX_THREAD* ThreadXThread::GetThreadId() -{ - return &m_thread; -} - -//---------------------------------------------------------------------------- -// GetCurrentThreadId -//---------------------------------------------------------------------------- -TX_THREAD* ThreadXThread::GetCurrentThreadId() -{ - return tx_thread_identify(); -} - -//---------------------------------------------------------------------------- -// IsCurrentThread -//---------------------------------------------------------------------------- -bool ThreadXThread::IsCurrentThread() -{ - return GetThreadId() == GetCurrentThreadId(); -} - -//---------------------------------------------------------------------------- -// GetQueueSize -//---------------------------------------------------------------------------- -size_t ThreadXThread::GetQueueSize() -{ - return m_queue.Size(); -} - -void ThreadXThread::Sleep(dmq::Duration timeout) { - dmq::ThisThread::sleep_for(timeout); -} - -//---------------------------------------------------------------------------- -// DispatchDelegate -//---------------------------------------------------------------------------- -bool ThreadXThread::DispatchDelegate(std::shared_ptr msg) -{ - // Safety check if queue is valid - if (!m_queue.IsCreated()) return false; - - // Allocate message container - ThreadMsg* threadMsg = new (std::nothrow) ThreadMsg(MSG_DISPATCH_DELEGATE, msg); - if (!threadMsg) - { - // OOM: drop the message - return false; - } -#if defined(DMQ_DATABUS_TOOLS) - threadMsg->SetEnqueueTime(Timer::GetNow()); -#endif - - // Compute wait option based on policy. - ULONG wait_option; - if (FULL_POLICY == FullPolicy::TIMEOUT) - wait_option = (static_cast(std::chrono::duration_cast(m_dispatchTimeout).count()) * TX_TIMER_TICKS_PER_SECOND) / 1000; - else - wait_option = TX_NO_WAIT; // DROP and FAULT: non-blocking - - // High priority routes to the HIGH lane (drained before NORMAL), preserving - // FIFO order within each lane -- see ThreadXDelegateQueue.h for why this is - // NOT tx_queue_front_send (that would make HIGH messages LIFO, not FIFO). - bool sent = m_queue.Send(threadMsg, msg->GetPriority() == Priority::HIGH, wait_option); - - if (!sent) - { - if (FULL_POLICY == FullPolicy::FAULT) { - printf("[Thread] CRITICAL: Queue full on thread '%s'! TRIGGERING FAULT.\n", THREAD_NAME.c_str()); - DMQ_ASSERT_TRUE(sent); - } else if (FULL_POLICY == FullPolicy::TIMEOUT) { - printf("[Thread] WARNING: Queue post timed out on '%s' — possible deadlock. Message dropped.\n", THREAD_NAME.c_str()); - if (m_droppedHandler) - m_droppedHandler(GetQueueSize()); - } else { // DROP - if (m_droppedHandler) - m_droppedHandler(GetQueueSize()); - } - delete threadMsg; // Failed to enqueue, prevent leak - return false; - } - -#if defined(DMQ_DATABUS_TOOLS) - // Update monitoring stats - tx_mutex_get(&m_statMutex, TX_WAIT_FOREVER); - size_t currentDepth = GetQueueSize(); - if (currentDepth > m_queueDepthMaxWindow) m_queueDepthMaxWindow = currentDepth; - if (currentDepth > m_queueDepthMaxAll) m_queueDepthMaxAll = currentDepth; - tx_mutex_put(&m_statMutex); -#endif - - return true; -} - -//---------------------------------------------------------------------------- -// Process (Static Entry Point) -//---------------------------------------------------------------------------- -void ThreadXThread::Process(ULONG /*instance*/) -{ - ThreadXThread* thread = nullptr; - { - const dmq::LockGuard lock(GetInstanceRegistryLock()); - auto it = GetInstanceRegistry().find(tx_thread_identify()); - if (it != GetInstanceRegistry().end()) - thread = it->second; - } - - DMQ_ASSERT_TRUE(thread != nullptr); - thread->Run(); -} - -//---------------------------------------------------------------------------- -// WatchdogCheck -//---------------------------------------------------------------------------- -void ThreadXThread::WatchdogCheck() -{ - if (m_startGate.IsHeld()) - return; // held at its start gate by design, not hung - - auto now = Timer::GetNow(); - auto lastAlive = m_lastAliveTime.load(); - auto watchdogTimeout = m_watchdogTimeout.load(); - - if (watchdogTimeout.count() > 0) - { - auto delta = now - lastAlive; - if (delta > watchdogTimeout) - { - WatchdogHandler(THREAD_NAME.c_str()); - } - } -} - -//---------------------------------------------------------------------------- -// ThreadCheck -//---------------------------------------------------------------------------- -void ThreadXThread::ThreadCheck() -{ - m_lastAliveTime.store(Timer::GetNow()); -} - -//---------------------------------------------------------------------------- -// WatchdogCheckAll -//---------------------------------------------------------------------------- -void ThreadXThread::WatchdogCheckAll() -{ - const dmq::LockGuard lock(GetWatchdogLock()); - ThreadXThread* p = GetWatchdogHead(); - while (p != nullptr) - { - p->WatchdogCheck(); - p = p->m_watchdogNext; - } -} - -//---------------------------------------------------------------------------- -// GetInstanceRegistry -//---------------------------------------------------------------------------- -dmq::xmap& ThreadXThread::GetInstanceRegistry() -{ - static dmq::xmap registry; - return registry; -} - -//---------------------------------------------------------------------------- -// GetInstanceRegistryLock -//---------------------------------------------------------------------------- -dmq::RecursiveMutex& ThreadXThread::GetInstanceRegistryLock() -{ - static dmq::RecursiveMutex* lock = new dmq::RecursiveMutex(); - return *lock; -} - -//---------------------------------------------------------------------------- -// GetWatchdogHead -//---------------------------------------------------------------------------- -ThreadXThread*& ThreadXThread::GetWatchdogHead() -{ - static ThreadXThread* head = nullptr; - return head; -} - -//---------------------------------------------------------------------------- -// GetWatchdogLock -//---------------------------------------------------------------------------- -dmq::RecursiveMutex& ThreadXThread::GetWatchdogLock() -{ - static dmq::RecursiveMutex* lock = new dmq::RecursiveMutex(); - return *lock; -} - -//---------------------------------------------------------------------------- -// Run (Member Function Loop) -//---------------------------------------------------------------------------- -void ThreadXThread::Run() -{ - bool selfExit = false; - m_selfExitPtr = &selfExit; - - // Exit and idle handlers are copied onto this stack frame so they work on - // every return path, including a self-exit where 'this' may already be freed. - ThreadExitGuard exitGuard(m_exitHandler); - ThreadIdleTimer idle(m_idleHandler, m_idleInterval); - - // dmq::ThisThread::GetCurrent() returns this thread from here on. Reset - // before the exit handler runs (and destroyed before exitGuard on a - // self-exit), so the exit handler sees nullptr. - std::optional currentScope; - currentScope.emplace(this); - - if (m_startHandler) - m_startHandler(); - - // A start handler that exited this thread (ExitThread() on itself) leaves - // right after the signal below: once CreateThread() returns, the Thread may - // be destroyed, so nothing after the signal may touch 'this'. - const bool exitedInStart = selfExit; - - if (m_startSync) - tx_semaphore_put(&m_startSem); - if (exitedInStart) - return; - - // Optional start gate: wait here, ready but processing nothing, until it opens - if (m_startGate.Enabled()) - { - const bool opened = m_startGate.Wait(m_exit); - m_lastAliveTime.store(Timer::GetNow()); // before Passed(): no stale watchdog read - m_startGate.Passed(); - // ExitThread() while held: run nothing. Cancel each queued message - // (DISCARD) until the exit message. Consuming them also keeps - // ExitThread()'s blocking send of the exit message from waiting on a - // full queue. - if (!opened) - m_discard.store(true); - } - - ThreadMsg* msg = nullptr; - while (!selfExit) - { - dmq::Duration timeout; - { - m_lastAliveTime.store(Timer::GetNow()); - timeout = m_watchdogTimeout.load(); - } - - // If watchdog active, use a finite timeout so we can periodically update - // m_lastAliveTime while idle. If an idle handler is set, wake no later - // than when it is due. Otherwise, block forever to save power. - ULONG waitOption = TX_WAIT_FOREVER; - if (timeout.count() > 0) - { - auto ms = std::chrono::duration_cast(timeout).count(); - waitOption = (static_cast(ms / dmq::WATCHDOG_HEARTBEAT_DIVISOR) * TX_TIMER_TICKS_PER_SECOND) / 1000; - if (waitOption == 0) waitOption = 1; - } - if (idle.Enabled()) - { - auto ms = std::chrono::ceil(idle.WaitTime(dmq::Duration(-1))).count(); - ULONG idleTicks = (static_cast(ms) * TX_TIMER_TICKS_PER_SECOND + 999) / 1000; - if (idleTicks < waitOption) waitOption = idleTicks; - } - - msg = m_queue.Receive(waitOption); - if (!msg) - { - // Exit requested but no exit message arrived (e.g. it could not be allocated) - if (m_exit.load()) - break; - - // Timeout or other failure: run the idle handler if it is due - if (idle.IsDue()) - { - idle.Run(); - // The idle handler exited this thread (and may have deleted it): leave - // without touching 'this', as the message path does - if (selfExit) - return; - } - continue; - } - - int msgId = msg->GetId(); - if (msgId == MSG_DISPATCH_DELEGATE && m_discard.load()) - { - // ExitPolicy::DISCARD: skip messages queued ahead of the exit message - CancelThreadMsg(*msg); - } - else if (msgId == MSG_DISPATCH_DELEGATE) - { -#if defined(DMQ_DATABUS_TOOLS) - // Update latency stats before invoking - dmq::Duration latency = Timer::GetNow() - msg->GetEnqueueTime(); - { - tx_mutex_get(&m_statMutex, TX_WAIT_FOREVER); - m_latencyTotalWindow += latency; - m_latencyCountWindow++; - if (latency > m_latencyMaxWindow) m_latencyMaxWindow = latency; - if (latency > m_latencyMaxAll) m_latencyMaxAll = latency; - m_dispatchCountAll++; - tx_mutex_put(&m_statMutex); - } -#endif - - auto delegateMsg = msg->GetData(); - DMQ_ASSERT_TRUE(delegateMsg); - auto invoker = delegateMsg->GetInvoker(); - DMQ_ASSERT_TRUE(invoker); - -#if defined(DMQ_DATABUS_TOOLS) - dmq::TimePoint start = Timer::GetNow(); -#endif -#if defined(__cpp_exceptions) && !defined(DMQ_ASSERTS) - bool success = false; - try { - success = invoker->Invoke(delegateMsg); - if (!selfExit) DMQ_ASSERT_TRUE(success); - } - catch (const std::bad_alloc& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled bad_alloc in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::invalid_argument& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled invalid_argument in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::runtime_error& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled runtime_error in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::exception& e) { - printf("[Thread:%s] Unhandled exception in delegate callback: %s\n", THREAD_NAME.c_str(), e.what()); - DMQ_ASSERT(); - } - catch (...) { - printf("[Thread:%s] Unhandled unknown exception in delegate callback.\n", THREAD_NAME.c_str()); - DMQ_ASSERT(); - } -#else - bool success = invoker->Invoke(delegateMsg); - if (!selfExit) DMQ_ASSERT_TRUE(success); -#endif - if (selfExit) { - delete msg; - return; - } - -#if defined(DMQ_DATABUS_TOOLS) - dmq::Duration invokeTime = Timer::GetNow() - start; - { - tx_mutex_get(&m_statMutex, TX_WAIT_FOREVER); - m_invokeTotalWindow += invokeTime; - m_invokeCountWindow++; - if (invokeTime > m_invokeMaxWindow) m_invokeMaxWindow = invokeTime; - if (invokeTime > m_invokeMaxAll) m_invokeMaxAll = invokeTime; - tx_mutex_put(&m_statMutex); - } -#endif - } - - delete msg; - - if (msgId == MSG_EXIT_THREAD) { - break; - } - - // Any message restarts the idle countdown - idle.Restart(); - } - - // Run the exit handler before signalling ExitThread(), so it returns only after it - currentScope.reset(); - exitGuard.Fire(); - - // Clear before signalling: once ExitThread() returns, 'this' may be destroyed - m_selfExitPtr = nullptr; - // Signal ExitThread() that the loop has exited - tx_semaphore_put(&m_exitSem); -} - -#if defined(DMQ_DATABUS_TOOLS) -//---------------------------------------------------------------------------- -// SnapshotStats -//---------------------------------------------------------------------------- -ThreadXThread::ThreadStats ThreadXThread::SnapshotStats() -{ - tx_mutex_get(&m_statMutex, TX_WAIT_FOREVER); - ThreadStats stats; - stats.cpu_name = CPU_NAME; - stats.thread_name = THREAD_NAME; - stats.queue_depth = GetQueueSize(); - stats.queue_depth_max_window = m_queueDepthMaxWindow; - stats.queue_depth_max_all = m_queueDepthMaxAll; - stats.queue_size_limit = m_queueSize; - - if (m_latencyCountWindow > 0) { - stats.latency_avg_ms = (float)std::chrono::duration_cast(m_latencyTotalWindow).count() / (static_cast(m_latencyCountWindow) * 1000.0f); - } else { - stats.latency_avg_ms = 0.0f; - } - - stats.latency_max_window_ms = (float)std::chrono::duration_cast(m_latencyMaxWindow).count() / 1000.0f; - stats.latency_max_all_ms = (float)std::chrono::duration_cast(m_latencyMaxAll).count() / 1000.0f; - - if (m_invokeCountWindow > 0) { - stats.invoke_avg_ms = (float)std::chrono::duration_cast(m_invokeTotalWindow).count() / (static_cast(m_invokeCountWindow) * 1000.0f); - } else { - stats.invoke_avg_ms = 0.0f; - } - - stats.invoke_max_window_ms = (float)std::chrono::duration_cast(m_invokeMaxWindow).count() / 1000.0f; - stats.invoke_max_all_ms = (float)std::chrono::duration_cast(m_invokeMaxAll).count() / 1000.0f; - - stats.dispatch_count = m_dispatchCountAll; - - // Reset windowed stats - m_queueDepthMaxWindow = 0; - m_latencyTotalWindow = Duration(0); - m_latencyCountWindow = 0; - m_latencyMaxWindow = Duration(0); - - m_invokeTotalWindow = Duration(0); - m_invokeCountWindow = 0; - m_invokeMaxWindow = Duration(0); - - tx_mutex_put(&m_statMutex); - return stats; -} -#endif - -} // namespace dmq::os - -#endif // DMQ_THREAD_THREADX diff --git a/DelegateMQ/port/os/threadx/ThreadXThread.h b/DelegateMQ/port/os/threadx/ThreadXThread.h deleted file mode 100644 index a1a0910..0000000 --- a/DelegateMQ/port/os/threadx/ThreadXThread.h +++ /dev/null @@ -1,328 +0,0 @@ -#ifndef _THREAD_THREADX_H -#define _THREAD_THREADX_H - -/// @file ThreadXThread.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief ThreadX implementation of the DelegateMQ IThread interface. -/// -/// @details -/// This class provides a concrete implementation of the `IThread` interface using -/// Azure RTOS ThreadX primitives. It enables DelegateMQ to dispatch asynchronous -/// delegates to a dedicated ThreadX thread. -/// -/// @note This implementation is a basic port. For reference, the stdlib and win32 -/// implementations provide additional features: -/// 1. Synchronized Startup: CreateThread() blocks until the worker thread is ready. -/// -/// **Key Features:** -/// * **Task Integration:** Wraps `tx_thread_create` to establish a dedicated worker loop. -/// * **FullPolicy Support:** Configurable back-pressure (DROP or TIMEOUT) when the -/// message queue is full. -/// * **Priority Support:** Normal and High priorities, as two FIFO queue lanes drained -/// HIGH first, so same-priority messages keep dispatch order (see -/// `ThreadXDelegateQueue` for why one queue + `tx_queue_front_send()` is wrong). -/// * **Queue-Based Dispatch:** Uses `ThreadXDelegateQueue` (a thin RAII wrapper -/// around a ThreadX `TX_QUEUE`) to receive and process incoming delegate -/// messages in a thread-safe manner. -/// * **Priority Control:** Supports runtime priority configuration via `SetThreadPriority`. -/// * **Dynamic Configuration:** Allows configuring stack size and queue depth at construction. -/// * **Graceful Shutdown:** Implements robust termination logic using semaphores to ensure -/// the thread exits cleanly before destruction. -/// * **Watchdog Integration:** Optional heartbeat mechanism detects stalled or deadlocked -/// threads. Enable by passing a timeout to CreateThread(). Requires -/// Thread::WatchdogCheckAll() to be called periodically from a context that can preempt -/// watched threads -- the highest-priority task in the system, not an ISR. -/// * **Start Gate:** Optional `SetStartGate(StartGate*)`, called before `CreateThread()`, -/// holds the thread ready but processing no messages, at any priority, until -/// `StartGate::Open()` releases every thread sharing the gate at once. - -#include "delegate/IThread.h" -#include "delegate/UnicastDelegate.h" -#include "port/os/common/ThreadMsg.h" -#include "port/os/common/StartGate.h" -#include "ThreadXDelegateQueue.h" -#include "extras/util/Timer.h" -#include -#include -#include -#include -#include - -namespace dmq::os { - -using namespace dmq::util; - -/// @brief Policy applied when the thread message queue is full. See dmq::FullPolicy -/// in DelegateOpt.h for the canonical definition, shared by every dmq::os::Thread port. -using FullPolicy = dmq::FullPolicy; - -/// @brief What ExitThread() does with queued messages. See dmq::ExitPolicy in DelegateOpt.h. -using ExitPolicy = dmq::ExitPolicy; - -// Comparator for priority (ThreadX priority is 0 to N-1, where 0 is highest) -// This is used for the priority queue if we had one, but ThreadX uses tx_queue_send/tx_queue_front_send. - -class ThreadXThread : public dmq::IThread -{ -public: -#if defined(DMQ_DATABUS_TOOLS) - /// @brief Statistics captured for thread monitoring. - struct ThreadStats { - dmq::xstring cpu_name; - dmq::xstring thread_name; - size_t queue_depth; // Current depth - size_t queue_depth_max_window;// Max depth since last snapshot - size_t queue_depth_max_all; // All-time max depth - size_t queue_size_limit; // Max allowed - float latency_avg_ms; // Avg wait in window - float latency_max_window_ms; // Max wait since last snapshot - float latency_max_all_ms; // All-time max wait - float invoke_avg_ms; // Avg execution in window - float invoke_max_window_ms; // Max execution since last snapshot - float invoke_max_all_ms; // All-time max execution - uint64_t dispatch_count; // Total dispatches (all-time) - }; -#endif - - /// Default queue size if 0 is passed - static const ULONG DEFAULT_QUEUE_SIZE = dmq::DEFAULT_QUEUE_SIZE; - - /// Constructor - /// @param threadName Name for the ThreadX thread - /// @param maxQueueSize Max number of messages in queue (0 = Default dmq::DEFAULT_QUEUE_SIZE) - /// @param fullPolicy Action when queue is full: FAULT (default), DROP, or TIMEOUT. - /// @param dispatchTimeout Duration to wait before giving up when policy is TIMEOUT. - /// @param cpuName Optional CPU/Core name grouping for monitoring tools. - ThreadXThread(const char* threadName, size_t maxQueueSize = 0, FullPolicy fullPolicy = FullPolicy::FAULT, - dmq::Duration dispatchTimeout = dmq::DEFAULT_DISPATCH_TIMEOUT, const char* cpuName = ""); - - ThreadXThread(const std::string& threadName, size_t maxQueueSize = 0, FullPolicy fullPolicy = FullPolicy::FAULT, - dmq::Duration dispatchTimeout = dmq::DEFAULT_DISPATCH_TIMEOUT, const std::string& cpuName = "") - : ThreadXThread(threadName.c_str(), maxQueueSize, fullPolicy, dispatchTimeout, cpuName.c_str()) {} - - /// Destructor - ~ThreadXThread(); - - /// Called once to create the worker thread. If watchdogTimeout value - /// provided, the maximum watchdog interval is used. Otherwise no watchdog. - /// @param[in] watchdogTimeout - optional watchdog timeout. - /// @return TRUE if thread is created. FALSE otherwise. - bool CreateThread(std::optional watchdogTimeout = std::nullopt); - - /// Shut down the worker thread. - /// @param[in] policy - DRAIN (default) invokes every message queued before this - /// call first; DISCARD invokes only the message already running and cancels - /// the rest (see dmq::ExitPolicy). Called from the thread's own message - /// handler (a self-exit), queued messages are always discarded. - void ExitThread(ExitPolicy policy = ExitPolicy::DRAIN); - - /// Get the ID of this thread instance - TX_THREAD* GetThreadId(); - - /// Get the ID of the currently executing thread - static TX_THREAD* GetCurrentThreadId(); - - /// Returns true if the calling thread is this thread - virtual bool IsCurrentThread() override; - - /// Set the ThreadX Priority (0 = Highest). - /// Can be called before or after CreateThread(). - void SetThreadPriority(UINT priority); - - /// Get current priority - UINT GetThreadPriority(); - - /// Get thread name - dmq::xstring GetThreadName() { return THREAD_NAME; } - - /// Get current queue size - size_t GetQueueSize(); - - /// Sleep for a duration. - /// @param[in] timeout - the duration to sleep. - static void Sleep(dmq::Duration timeout); - - // IThread Interface Implementation - virtual bool DispatchDelegate(std::shared_ptr msg) override; - - /// @brief Register a handler invoked when DispatchDelegate() drops a message: - /// under FullPolicy::DROP (queue full, discarded immediately) or - /// FullPolicy::TIMEOUT (queue stayed full for dispatchTimeout, discarded). - /// Optional; unset by default. Called synchronously on the calling (producer) - /// thread, with the queue depth at the time of the drop. - void SetDroppedHandler(const dmq::UnicastDelegate& handler) { m_droppedHandler = handler; } - void SetDroppedHandler(dmq::UnicastDelegate&& handler) { m_droppedHandler = std::move(handler); } - - /// @brief Register a handler invoked on the worker thread before it processes - /// any message. Use it for per-thread setup (COM, a language runtime attach, - /// thread-local state, affinity). CreateThread() returns only after it completes. - /// @details Must be called while the thread is not running (before CreateThread(), - /// or after ExitThread()); calling it on a running thread faults. It runs again - /// on each CreateThread(). Messages dispatched meanwhile are queued, not lost. - void SetStartHandler(const dmq::UnicastDelegate& handler) { DMQ_ASSERT_TRUE(m_thread.tx_thread_id == 0); m_startHandler = handler; } - void SetStartHandler(dmq::UnicastDelegate&& handler) { DMQ_ASSERT_TRUE(m_thread.tx_thread_id == 0); m_startHandler = std::move(handler); } - - /// @brief Optional: hold this thread at `gate` once it is created, until - /// `gate->Open()`. Pass nullptr (the default) to start at once. - /// @details CreateThread() still runs the start handler and returns when the - /// thread is ready; the thread then processes nothing, at any priority, until - /// the gate opens. Use one gate for a group of threads so they all start - /// together after setup. See port/os/common/StartGate.h. Must be called while - /// the thread is not running; calling it on a running thread faults. - void SetStartGate(StartGate* gate) { DMQ_ASSERT_TRUE(m_thread.tx_thread_id == 0); m_startGate.Set(gate); } - - /// @brief Register a handler invoked on the worker thread after it processes - /// its last message, as the thread exits. Use it to undo SetStartHandler() setup. - /// @details Must be called while the thread is not running; calling it on a - /// running thread faults. The handler is copied when the thread starts. - /// ExitThread() from another thread returns after it completes. If the thread - /// exits itself (ExitThread() from a handler on this thread), it runs after the - /// owning ThreadXThread may already be destroyed, so it must not touch that object. - void SetExitHandler(const dmq::UnicastDelegate& handler) { DMQ_ASSERT_TRUE(m_thread.tx_thread_id == 0); m_exitHandler = handler; } - void SetExitHandler(dmq::UnicastDelegate&& handler) { DMQ_ASSERT_TRUE(m_thread.tx_thread_id == 0); m_exitHandler = std::move(handler); } - - /// @brief Register a handler invoked on the worker thread when its queue has - /// been empty for `interval`, then again every `interval` while it stays empty. - /// Any message processed restarts the countdown. Use it for background work that - /// should yield to messages: polling, housekeeping, entering low power. - /// @details Must be called while the thread is not running; calling it on a - /// running thread faults. The handler and interval are copied when the thread - /// starts. Not called once ExitThread() has been requested. - /// @param[in] handler - the idle handler, or an empty delegate to disable. - /// @param[in] interval - quiet time before each call. Must be greater than zero. - /// Defaults to dmq::THREAD_IDLE_INTERVAL (DMQ_THREAD_IDLE_INTERVAL). - void SetIdleHandler(const dmq::UnicastDelegate& handler, dmq::Duration interval = dmq::THREAD_IDLE_INTERVAL) - { - DMQ_ASSERT_TRUE(m_thread.tx_thread_id == 0); - DMQ_ASSERT_TRUE(interval > dmq::Duration::zero()); - m_idleHandler = handler; - m_idleInterval = interval; - } - void SetIdleHandler(dmq::UnicastDelegate&& handler, dmq::Duration interval = dmq::THREAD_IDLE_INTERVAL) - { - DMQ_ASSERT_TRUE(m_thread.tx_thread_id == 0); - DMQ_ASSERT_TRUE(interval > dmq::Duration::zero()); - m_idleHandler = std::move(handler); - m_idleInterval = interval; - } - - /// @brief Manually update the watchdog alive timestamp. - /// @details The Run() loop refreshes the timestamp automatically on every iteration. - /// Call this from inside long-running message handlers to prevent a false watchdog - /// alarm when a handler legitimately takes longer than watchdogTimeout. - void ThreadCheck(); - - /// @brief Static method to check all registered threads for watchdog expiration. - static void WatchdogCheckAll(); - -#if defined(DMQ_DATABUS_TOOLS) - /// @brief Capture and reset windowed statistics. - ThreadStats SnapshotStats(); -#endif - -private: - ThreadXThread(const ThreadXThread&) = delete; - ThreadXThread& operator=(const ThreadXThread&) = delete; - - /// Entry point for the thread - static void Process(ULONG instance); - - // Run loop called by Process - void Run(); - - /// @brief Registry mapping a ThreadX TX_THREAD control block back to its - /// owning ThreadXThread instance. - /// @details ThreadX's tx_thread_create() entry_input parameter is a - /// ULONG, which cannot safely carry a 64-bit 'this' pointer on hosts - /// where ULONG is 32 bits (e.g. this Linux/GNU simulation port) -- - /// reinterpret_cast(this) would truncate it. Process() instead - /// looks up 'this' via tx_thread_identify() against this registry. - /// Entries are added before tx_thread_resume() is called, so Process() - /// can never observe a not-yet-registered thread. - static dmq::xmap& GetInstanceRegistry(); - static dmq::RecursiveMutex& GetInstanceRegistryLock(); - - /// Check watchdog is expired. Called by WatchdogCheckAll(). - void WatchdogCheck(); - - /// Get registry head using the "Immortal" Pattern - static ThreadXThread*& GetWatchdogHead(); - - /// Get registry lock using the "Immortal" Pattern - static dmq::RecursiveMutex& GetWatchdogLock(); - - const dmq::xstring THREAD_NAME; - const dmq::xstring CPU_NAME; - const size_t m_queueSize; // Stored queue size - const FullPolicy FULL_POLICY; - const dmq::Duration m_dispatchTimeout; - UINT m_priority; // Stored priority - - // ThreadX Control Blocks - TX_THREAD m_thread; - ThreadXDelegateQueue m_queue; - - // Optional handler invoked when a message is dropped (FullPolicy::DROP or TIMEOUT) - dmq::UnicastDelegate m_droppedHandler; - - // Optional handlers invoked on the worker thread at start, exit and when idle - dmq::UnicastDelegate m_startHandler; - dmq::UnicastDelegate m_exitHandler; - dmq::UnicastDelegate m_idleHandler; - dmq::Duration m_idleInterval = dmq::Duration::zero(); - TX_SEMAPHORE m_exitSem; // Semaphore to signal thread completion - TX_SEMAPHORE m_startSem; // Put by Run() once the start handler has run - bool m_startSync = false; // CreateThread() waits for the start handler (called from a thread) - std::atomic m_exit = false; - - // Optional start gate (SetStartGate()): its state, and whether the thread is - // held at it (the watchdog doesn't report a thread waiting by design) - StartGateClient m_startGate; - std::atomic m_discard = false; // ExitPolicy::DISCARD: cancel queued messages instead of invoking - bool* m_selfExitPtr = nullptr; - - // Set when ExitThread() is called from this thread itself (see ExitThread()): - // the cleanup is then deferred to a later ExitThread() from another thread. - std::atomic m_selfExited{false}; - - // Stack memory required by ThreadX (Managed by RAII) - // Using ULONG[] ensures correct alignment for the ThreadX stack - std::unique_ptr m_stackMemory; - - // Configurable stack size (bytes) - static const ULONG STACK_SIZE = static_cast(dmq::THREADX_STACK_BYTES); // DMQ_THREADX_STACK_BYTES - - // Watchdog related members - std::atomic m_lastAliveTime{dmq::TimePoint()}; - std::atomic m_watchdogTimeout{dmq::Duration(0)}; - ThreadXThread* m_watchdogNext = nullptr; - -#if defined(DMQ_DATABUS_TOOLS) - TX_MUTEX m_statMutex; // Mutex to protect statistics - // Monitoring statistics members - size_t m_queueDepthMaxWindow = 0; - size_t m_queueDepthMaxAll = 0; - - dmq::Duration m_latencyTotalWindow = dmq::Duration(0); - uint32_t m_latencyCountWindow = 0; - dmq::Duration m_latencyMaxWindow = dmq::Duration(0); - dmq::Duration m_latencyMaxAll = dmq::Duration(0); - - dmq::Duration m_invokeTotalWindow = dmq::Duration(0); - uint32_t m_invokeCountWindow = 0; - dmq::Duration m_invokeMaxWindow = dmq::Duration(0); - dmq::Duration m_invokeMaxAll = dmq::Duration(0); - - uint64_t m_dispatchCountAll = 0; -#endif -}; - -/// @brief Backward-compatible name: existing code referencing dmq::os::Thread -/// keeps compiling unchanged against the ThreadX port. -using Thread = ThreadXThread; - -} // namespace dmq::os - -#endif // _THREAD_THREADX_H diff --git a/DelegateMQ/port/os/win32/Win32Thread.cpp b/DelegateMQ/port/os/win32/Win32Thread.cpp deleted file mode 100644 index 9aaab2d..0000000 --- a/DelegateMQ/port/os/win32/Win32Thread.cpp +++ /dev/null @@ -1,652 +0,0 @@ -// Compiles to nothing unless DMQ_THREAD_WIN32 is selected, so every DelegateMQ source -// file can be added to a build (see src/DelegateMQ.cpp). -#include "delegate/DelegateSelect.h" -#if defined(DMQ_THREAD_WIN32) && !defined(_WIN32) -#error "DMQ_THREAD_WIN32 is Windows-only. Select another DMQ_THREAD_* port for this target." -#endif -#if defined(DMQ_THREAD_WIN32) - -#include "DelegateMQ.h" -#include "Win32Thread.h" -#include "port/os/common/ThreadHooks.h" -#include "extras/util/Fault.h" -#include - -namespace dmq::os { - -using namespace dmq::util; - -// Thread-local pointer into Process()'s stack frame. Set non-null only while -// Process() is running on a given thread. ExitThread() writes true through it -// when the thread destroys its own owning object so Process() can exit without -// touching freed members. -static thread_local bool* t_self_exit = nullptr; - -//---------------------------------------------------------------------------- -// Thread -//---------------------------------------------------------------------------- -Win32Thread::Win32Thread(const char* threadName, size_t maxQueueSize, FullPolicy fullPolicy, dmq::Duration dispatchTimeout, const char* cpuName) - : THREAD_NAME(threadName) - , CPU_NAME(cpuName) - , MAX_QUEUE_SIZE(maxQueueSize == 0 ? dmq::THREAD_DESKTOP_QUEUE_SIZE : maxQueueSize) - , FULL_POLICY(fullPolicy) - , m_dispatchTimeout(dispatchTimeout) - , m_exit(false) -{ - InitializeCriticalSection(&m_cs); - InitializeConditionVariable(&m_cvNotEmpty); - InitializeConditionVariable(&m_cvNotFull); -} - -//---------------------------------------------------------------------------- -// ~Thread -//---------------------------------------------------------------------------- -Win32Thread::~Win32Thread() -{ - ExitThread(); - - const std::lock_guard lock(GetWatchdogLock()); - Win32Thread** pp = &GetWatchdogHead(); - while (*pp != nullptr) - { - if (*pp == this) - { - *pp = this->m_watchdogNext; - this->m_watchdogNext = nullptr; - break; - } - pp = &((*pp)->m_watchdogNext); - } - - DeleteCriticalSection(&m_cs); -} - -//---------------------------------------------------------------------------- -// CreateThread -//---------------------------------------------------------------------------- -bool Win32Thread::CreateThread(std::optional watchdogTimeout) -{ - if (m_hThread == NULL) - { - m_exit = false; - // Held from creation, so the watchdog never sees a gated thread as hung - // before it reaches the gate (e.g. created before the scheduler runs) - m_startGate.OnCreate(); - // Set before the thread exists: its loop reads the timeout before its - // first queue wait, and an idle thread waits forever with no timeout - m_lastAliveTime.store(Timer::GetNow()); - m_watchdogTimeout.store(watchdogTimeout.value_or(dmq::Duration(0))); - - // Manual-reset event for startup synchronization - m_hStartEvent = CreateEvent(NULL, TRUE, FALSE, NULL); - - // Created suspended so m_hThread/m_threadId are stored before the thread - // runs: the start handler may call IsCurrentThread() or dispatch to it. - m_hThread = ::CreateThread(NULL, 0, ThreadProc, this, CREATE_SUSPENDED, &m_threadId); - if (m_hThread == NULL) { - m_watchdogTimeout.store(dmq::Duration(0)); // no thread to refresh the heartbeat - m_startGate.OnCreateFailed(); - CloseHandle(m_hStartEvent); - m_hStartEvent = NULL; - return false; - } - - // Set the thread name so it shows in the Visual Studio Debug Location toolbar - std::wstring wname(THREAD_NAME.begin(), THREAD_NAME.end()); - SetThreadDescription(m_hThread, wname.c_str()); - - ResumeThread(m_hThread); - - // Wait for the thread to enter the Process method - WaitForSingleObject(m_hStartEvent, INFINITE); - CloseHandle(m_hStartEvent); - m_hStartEvent = NULL; - - m_lastAliveTime.store(Timer::GetNow()); - - // Caller wants a watchdog timer? - if (watchdogTimeout.has_value()) - { - - // Add to watchdog registry if not already present - { - dmq::LockGuard lock(GetWatchdogLock()); - bool found = false; - Win32Thread* p = GetWatchdogHead(); - while (p != nullptr) - { - if (p == this) - { - found = true; - break; - } - p = p->m_watchdogNext; - } - if (!found) - { - m_watchdogNext = GetWatchdogHead(); - GetWatchdogHead() = this; - } - } - } - } - return true; -} - -//---------------------------------------------------------------------------- -// ThreadProc -//---------------------------------------------------------------------------- -DWORD WINAPI Win32Thread::ThreadProc(LPVOID lpParam) -{ - static_cast(lpParam)->Process(); - return 0; -} - -//---------------------------------------------------------------------------- -// DispatchDelegate -//---------------------------------------------------------------------------- -bool Win32Thread::DispatchDelegate(std::shared_ptr msg) -{ - if (m_exit.load() || m_hThread == NULL) return false; - - EnterCriticalSection(&m_cs); - - // [BACK PRESSURE / DROP / FAULT / TIMEOUT LOGIC] - if (MAX_QUEUE_SIZE > 0 && (m_highQueue.size() + m_normalQueue.size()) >= MAX_QUEUE_SIZE) - { - if (FULL_POLICY == FullPolicy::DROP) - { - size_t depth = m_highQueue.size() + m_normalQueue.size(); - LeaveCriticalSection(&m_cs); - if (m_droppedHandler) - m_droppedHandler(depth); - return false; // silently discard - } - - if (FULL_POLICY == FullPolicy::FAULT) - { - LeaveCriticalSection(&m_cs); - printf("[Thread] CRITICAL: Queue full on thread '%s'! TRIGGERING FAULT.\n", THREAD_NAME.c_str()); - DMQ_ASSERT_TRUE(false); - return false; - } - - if (FULL_POLICY == FullPolicy::TIMEOUT) - { - DWORD dwTimeout = static_cast( - std::chrono::duration_cast(m_dispatchTimeout).count()); - while ((m_highQueue.size() + m_normalQueue.size()) >= MAX_QUEUE_SIZE && !m_exit.load()) - { - if (!SleepConditionVariableCS(&m_cvNotFull, &m_cs, dwTimeout)) - { - size_t depth = m_highQueue.size() + m_normalQueue.size(); - LeaveCriticalSection(&m_cs); - printf("[Thread] WARNING: Queue post timed out on '%s' — possible deadlock. Message dropped.\n", THREAD_NAME.c_str()); - if (m_droppedHandler) - m_droppedHandler(depth); - return false; - } - } - } - } - - // If using XALLOCATOR explicit operator new required. See xallocator.h. - auto threadMsg = xmake_shared(MSG_DISPATCH_DELEGATE, msg); - #if defined(DMQ_DATABUS_TOOLS) - threadMsg->SetEnqueueTime(Timer::GetNow()); - #endif - - // If we woke up because of exit (or exit happened while waiting), abort - if (!m_exit.load()) - { - if (threadMsg->GetPriority() == dmq::Priority::HIGH) - m_highQueue.push_back(threadMsg); - else - m_normalQueue.push_back(threadMsg); - - #if defined(DMQ_DATABUS_TOOLS) - // Update monitoring stats - size_t currentDepth = (m_highQueue.size() + m_normalQueue.size()); - if (currentDepth > m_queueDepthMaxWindow) m_queueDepthMaxWindow = currentDepth; - if (currentDepth > m_queueDepthMaxAll) m_queueDepthMaxAll = currentDepth; - #endif - - WakeConditionVariable(&m_cvNotEmpty); - } - else - { - LeaveCriticalSection(&m_cs); - return false; - } - - LeaveCriticalSection(&m_cs); - return true; -} - -//---------------------------------------------------------------------------- -// Process -//---------------------------------------------------------------------------- -void Win32Thread::Process() -{ - // selfExit is set by ExitThread() when the thread destroys its own owner. - // It lives on this stack frame so it remains valid even after 'this' is freed. - bool selfExit = false; - t_self_exit = &selfExit; - - // Exit and idle handlers are copied onto this stack frame so they work on - // every return path, including a self-exit where 'this' may already be freed. - ThreadExitGuard exitGuard(m_exitHandler); - ThreadIdleTimer idle(m_idleHandler, m_idleInterval); - - // dmq::ThisThread::GetCurrent() returns this thread from here on. Declared - // after exitGuard, so it is cleared again before the exit handler runs. - dmq::CurrentThreadScope currentScope(this); - - if (m_startHandler) - m_startHandler(); - - // A start handler that exited this thread (ExitThread() on itself) leaves - // right after the signal below: once CreateThread() returns, the Thread may - // be destroyed, so nothing after the signal may touch 'this'. - const bool exitedInStart = selfExit; - - // Signal that the thread has started processing to notify CreateThread - SetEvent(m_hStartEvent); - if (exitedInStart) { t_self_exit = nullptr; return; } - - // Optional start gate: wait here, ready but processing nothing, until it opens - if (m_startGate.Enabled()) - { - const bool opened = m_startGate.Wait(m_exit); - m_lastAliveTime.store(Timer::GetNow()); // before Passed(): no stale watchdog read - m_startGate.Passed(); - if (!opened) - { - // ExitThread() while held: leave without running any message. - // ExitThread() cancels what is still queued once this thread ends. - t_self_exit = nullptr; - return; - } - } - - while (!selfExit) - { - dmq::Duration watchdogTimeout; - { - m_lastAliveTime.store(Timer::GetNow()); - watchdogTimeout = m_watchdogTimeout.load(); - } - - std::shared_ptr msg; - - EnterCriticalSection(&m_cs); - - // Wait for message to be added to the queue. - // If watchdog active, use a finite timeout so we can periodically update - // m_lastAliveTime while idle. If an idle handler is set, wake no later - // than when it is due. Otherwise, block forever. - DWORD dwTimeout = INFINITE; - if (watchdogTimeout.count() > 0) - { - auto ms = std::chrono::duration_cast(watchdogTimeout).count(); - dwTimeout = static_cast(ms / dmq::WATCHDOG_HEARTBEAT_DIVISOR); - if (dwTimeout == 0) dwTimeout = 1; - } - if (idle.Enabled()) - { - auto untilIdle = std::chrono::ceil(idle.WaitTime(dmq::Duration(-1))).count(); - if (static_cast(untilIdle) < dwTimeout) - dwTimeout = static_cast(untilIdle); - } - - while ((m_highQueue.empty() && m_normalQueue.empty()) && !m_exit.load()) - { - if (!SleepConditionVariableCS(&m_cvNotEmpty, &m_cs, dwTimeout)) - { - if (GetLastError() == ERROR_TIMEOUT) - break; // Timeout reached, break inner while to update m_lastAliveTime - } - } - - // If empty and exit is true, we should exit. - if ((m_highQueue.empty() && m_normalQueue.empty()) && m_exit.load()) - { - LeaveCriticalSection(&m_cs); - break; - } - - // If queue still empty, it means we timed out. Run the idle handler if it is - // due, then loop again to update m_lastAliveTime. - if ((m_highQueue.empty() && m_normalQueue.empty())) - { - LeaveCriticalSection(&m_cs); - if (idle.IsDue()) - idle.Run(); - continue; - } - - // Get highest priority message within queue - if (!m_highQueue.empty()) { - msg = m_highQueue.front(); - m_highQueue.pop_front(); - } else { - msg = m_normalQueue.front(); - m_normalQueue.pop_front(); - } - - // Unblock producers now that space is available - if (MAX_QUEUE_SIZE > 0) - WakeConditionVariable(&m_cvNotFull); - - LeaveCriticalSection(&m_cs); - - switch (msg->GetId()) - { - case MSG_DISPATCH_DELEGATE: - { -#if defined(DMQ_DATABUS_TOOLS) - // Update latency stats before invoking - dmq::Duration latency = Timer::GetNow() - msg->GetEnqueueTime(); - { - EnterCriticalSection(&m_cs); - m_latencyTotalWindow += latency; - m_latencyCountWindow++; - if (latency > m_latencyMaxWindow) m_latencyMaxWindow = latency; - if (latency > m_latencyMaxAll) m_latencyMaxAll = latency; - m_dispatchCountAll++; - LeaveCriticalSection(&m_cs); - } -#endif - - auto delegateMsg = msg->GetData(); - DMQ_ASSERT_TRUE(delegateMsg); - auto invoker = delegateMsg->GetInvoker(); - DMQ_ASSERT_TRUE(invoker); - -#if defined(DMQ_DATABUS_TOOLS) - dmq::TimePoint start = Timer::GetNow(); -#endif -#if defined(__cpp_exceptions) && !defined(DMQ_ASSERTS) - try { - bool success = invoker->Invoke(delegateMsg); - if (!selfExit) DMQ_ASSERT_TRUE(success); - } - catch (const std::bad_alloc& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled bad_alloc in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::invalid_argument& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled invalid_argument in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::runtime_error& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled runtime_error in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::exception& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled exception in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (...) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled unknown exception in delegate callback." << std::endl; - DMQ_ASSERT(); - } -#else - bool success = invoker->Invoke(delegateMsg); - if (!selfExit) DMQ_ASSERT_TRUE(success); -#endif - if (selfExit) { - t_self_exit = nullptr; - return; - } -#if defined(DMQ_DATABUS_TOOLS) - dmq::Duration invokeTime = Timer::GetNow() - start; - if (!selfExit) { - EnterCriticalSection(&m_cs); - m_invokeTotalWindow += invokeTime; - m_invokeCountWindow++; - if (invokeTime > m_invokeMaxWindow) m_invokeMaxWindow = invokeTime; - if (invokeTime > m_invokeMaxAll) m_invokeMaxAll = invokeTime; - LeaveCriticalSection(&m_cs); - } -#endif - break; - } - - case MSG_EXIT_THREAD: - { - t_self_exit = nullptr; - return; - } - - default: - { - break; - } - } - - // Any message restarts the idle countdown - idle.Restart(); - } - t_self_exit = nullptr; -} - -//---------------------------------------------------------------------------- -// ExitThread -//---------------------------------------------------------------------------- -void Win32Thread::ExitThread(ExitPolicy policy) -{ - if (m_hThread == NULL) return; - - // Messages taken off the queues without being invoked; canceled outside the lock - decltype(m_highQueue) discardedHigh; - decltype(m_normalQueue) discardedNormal; - - EnterCriticalSection(&m_cs); - - // Set exit flag INSIDE lock before notifying. - // This ensures that when a blocked producer wakes up, it sees m_exit == true immediately. - m_exit.store(true); - - // DISCARD: empty the queues so the exit message is the next one processed - if (policy == ExitPolicy::DISCARD) - { - discardedHigh.swap(m_highQueue); - discardedNormal.swap(m_normalQueue); - } - - // Explicitly allow Exit message to bypass the MAX_QUEUE_SIZE limit. - // We do not wait on m_cvNotFull here to prevent deadlock during shutdown. - // Queued last, so DRAIN invokes every message already queued first. - m_normalQueue.push_back(xmake_shared(MSG_EXIT_THREAD, nullptr)); - - // Wake up consumers - WakeConditionVariable(&m_cvNotEmpty); - - // Wake up blocked producers (DispatchDelegate) - WakeAllConditionVariable(&m_cvNotFull); - - LeaveCriticalSection(&m_cs); - - CancelAll(discardedHigh); - CancelAll(discardedNormal); - - // A thread held at its start gate isn't waiting on its queue: wake it so it - // sees the exit flag (set above) and leaves. Never touches the gate itself, - // which may be destroyed once the thread is released. - m_startGate.Wake(); - - // Prevent deadlock if ExitThread is called from within the thread itself - if (::GetCurrentThreadId() != m_threadId) - { - WaitForSingleObject(m_hThread, INFINITE); - } - else - { - if (t_self_exit) *t_self_exit = true; - m_startGate.Leave(); // exited from its start handler: never reaches the gate - } - - // Normally empty. After a self-exit the loop returns without draining, - // so anything still queued is discarded here. - EnterCriticalSection(&m_cs); - discardedHigh.swap(m_highQueue); - discardedNormal.swap(m_normalQueue); - LeaveCriticalSection(&m_cs); - CancelAll(discardedHigh); - CancelAll(discardedNormal); - - // The thread has finished (or, on a self-exit, is in its last handler): - // stop watchdog checks. Not earlier, so a thread that hangs while - // ExitThread() waits for it is still reported. - m_watchdogTimeout.store(dmq::Duration(0)); - - CloseHandle(m_hThread); - m_hThread = NULL; -} - -//---------------------------------------------------------------------------- -// GetThreadId -//---------------------------------------------------------------------------- -DWORD Win32Thread::GetThreadId() { return m_threadId; } - -//---------------------------------------------------------------------------- -// GetCurrentThreadId -//---------------------------------------------------------------------------- -DWORD Win32Thread::GetCurrentThreadId() { return ::GetCurrentThreadId(); } - -//---------------------------------------------------------------------------- -// IsCurrentThread -//---------------------------------------------------------------------------- -bool Win32Thread::IsCurrentThread() { return GetThreadId() == GetCurrentThreadId(); } - -//---------------------------------------------------------------------------- -// GetQueueSize -//---------------------------------------------------------------------------- -size_t Win32Thread::GetQueueSize() -{ - EnterCriticalSection(&m_cs); - size_t size = (m_highQueue.size() + m_normalQueue.size()); - LeaveCriticalSection(&m_cs); - return size; -} - -void Win32Thread::Sleep(dmq::Duration timeout) { - dmq::ThisThread::sleep_for(timeout); -} - -//---------------------------------------------------------------------------- -// WatchdogCheckAll -//---------------------------------------------------------------------------- -void Win32Thread::WatchdogCheckAll() -{ - const std::lock_guard lock(GetWatchdogLock()); - Win32Thread* p = GetWatchdogHead(); - while (p != nullptr) - { - p->WatchdogCheck(); - p = p->m_watchdogNext; - } -} - -//---------------------------------------------------------------------------- -// WatchdogCheck -//---------------------------------------------------------------------------- -void Win32Thread::WatchdogCheck() -{ - if (m_startGate.IsHeld()) - return; // held at its start gate by design, not hung - - auto now = Timer::GetNow(); - auto lastAlive = m_lastAliveTime.load(); - auto watchdogTimeout = m_watchdogTimeout.load(); - - if (watchdogTimeout.count() > 0) - { - auto delta = now - lastAlive; - if (delta > watchdogTimeout) - { - WatchdogHandler(THREAD_NAME.c_str()); - } - } -} - -//---------------------------------------------------------------------------- -// ThreadCheck -//---------------------------------------------------------------------------- -void Win32Thread::ThreadCheck() -{ - m_lastAliveTime.store(Timer::GetNow()); -} - -//---------------------------------------------------------------------------- -// GetWatchdogHead -//---------------------------------------------------------------------------- -Win32Thread*& Win32Thread::GetWatchdogHead() -{ - static Win32Thread* head = nullptr; - return head; -} - -//---------------------------------------------------------------------------- -// GetWatchdogLock -//---------------------------------------------------------------------------- -dmq::RecursiveMutex& Win32Thread::GetWatchdogLock() -{ - static dmq::RecursiveMutex* lock = new dmq::RecursiveMutex(); - return *lock; -} - -#if defined(DMQ_DATABUS_TOOLS) -//---------------------------------------------------------------------------- -// SnapshotStats -//---------------------------------------------------------------------------- -Win32Thread::ThreadStats Win32Thread::SnapshotStats() -{ - EnterCriticalSection(&m_cs); - ThreadStats stats; - stats.cpu_name = CPU_NAME; - stats.thread_name = THREAD_NAME; - stats.queue_depth = (m_highQueue.size() + m_normalQueue.size()); - stats.queue_depth_max_window = m_queueDepthMaxWindow; - stats.queue_depth_max_all = m_queueDepthMaxAll; - stats.queue_size_limit = MAX_QUEUE_SIZE; - - if (m_latencyCountWindow > 0) { - stats.latency_avg_ms = (float)std::chrono::duration_cast(m_latencyTotalWindow).count() / (static_cast(m_latencyCountWindow) * 1000.0f); - } else { - stats.latency_avg_ms = 0.0f; - } - - stats.latency_max_window_ms = (float)std::chrono::duration_cast(m_latencyMaxWindow).count() / 1000.0f; - stats.latency_max_all_ms = (float)std::chrono::duration_cast(m_latencyMaxAll).count() / 1000.0f; - - if (m_invokeCountWindow > 0) { - stats.invoke_avg_ms = (float)std::chrono::duration_cast(m_invokeTotalWindow).count() / (static_cast(m_invokeCountWindow) * 1000.0f); - } else { - stats.invoke_avg_ms = 0.0f; - } - - stats.invoke_max_window_ms = (float)std::chrono::duration_cast(m_invokeMaxWindow).count() / 1000.0f; - stats.invoke_max_all_ms = (float)std::chrono::duration_cast(m_invokeMaxAll).count() / 1000.0f; - - stats.dispatch_count = m_dispatchCountAll; - - // Reset windowed stats - m_queueDepthMaxWindow = 0; - m_latencyTotalWindow = dmq::Duration(0); - m_latencyCountWindow = 0; - m_latencyMaxWindow = dmq::Duration(0); - - m_invokeTotalWindow = dmq::Duration(0); - m_invokeCountWindow = 0; - m_invokeMaxWindow = dmq::Duration(0); - - LeaveCriticalSection(&m_cs); - return stats; -} -#endif - -} // namespace dmq::os - -#endif // DMQ_THREAD_WIN32 diff --git a/DelegateMQ/port/os/win32/Win32Thread.h b/DelegateMQ/port/os/win32/Win32Thread.h deleted file mode 100644 index 2c9ceb5..0000000 --- a/DelegateMQ/port/os/win32/Win32Thread.h +++ /dev/null @@ -1,314 +0,0 @@ -#ifndef _THREAD_WIN32_H -#define _THREAD_WIN32_H - -/// @file Win32Thread.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// @brief Win32 API implementation of the DelegateMQ IThread interface. -/// -/// @details -/// This class provides a Windows-native implementation of the `IThread` interface using -/// Win32 synchronization primitives (`CRITICAL_SECTION`, `CONDITION_VARIABLE`, `HANDLE`). -/// It creates a dedicated worker thread with an event loop capable of processing -/// asynchronous delegates and system messages. -/// -/// **Key Features:** -/// * **Priority Queue:** One FIFO `std::deque` per priority level, so high-priority -/// delegate messages (e.g., system signals) are processed before normal ones, and -/// messages of the same priority are processed in the order they were dispatched. -/// * **Queue Full Policy:** Configurable `FullPolicy` (DROP, FAULT, or TIMEOUT), always enforced -- -/// `maxQueueSize == 0` falls back to `dmq::THREAD_DESKTOP_QUEUE_SIZE` rather than disabling -/// the cap, since this port backs its queue with a plain `std::deque` and would otherwise -/// grow without bound if the destination thread is dead/stuck. TIMEOUT waits up to -/// `dispatchTimeout` for the consumer before logging and dropping; DROP silently discards -/// immediately. FAULT (the default) triggers a system fault. -/// * **Watchdog Integration:** Includes a built-in heartbeat mechanism. If the thread loop -/// stalls (deadlock or infinite loop), the watchdog timer detects the failure. -/// * **Synchronized Start:** Uses a Win32 manual-reset event to ensure the thread -/// is fully initialized and running before `CreateThread()` returns. -/// * **Debug Support:** Sets the native thread name via `SetThreadDescription()` to -/// aid debugging in Visual Studio. -/// * **Start Gate:** Optional `SetStartGate(StartGate*)`, called before `CreateThread()`, -/// holds the thread ready but processing no messages, at any priority, until -/// `StartGate::Open()` releases every thread sharing the gate at once. - -#include "delegate/IThread.h" -#include "delegate/UnicastDelegate.h" -#include "./extras/util/Timer.h" -#include "port/os/common/ThreadMsg.h" -#include "port/os/common/StartGate.h" -#include -#include -#include -#include - -#ifdef _WIN32 -#ifndef NOMINMAX -#define NOMINMAX -#endif -#include -#endif - -namespace dmq::os { - -/// @brief Policy applied when the thread message queue is full. See dmq::FullPolicy -/// in DelegateOpt.h for the canonical definition, shared by every dmq::os::Thread port. -using FullPolicy = dmq::FullPolicy; - -/// @brief What ExitThread() does with queued messages. See dmq::ExitPolicy in DelegateOpt.h. -using ExitPolicy = dmq::ExitPolicy; - -/// @brief Windows-native thread for systems using the Win32 API. -/// @details The Win32Thread class creates a worker thread capable of dispatching and -/// invoking asynchronous delegates. -class Win32Thread : public dmq::IThread -{ - XALLOCATOR -public: -#if defined(DMQ_DATABUS_TOOLS) - /// @brief Statistics captured for thread monitoring. - struct ThreadStats { - dmq::xstring cpu_name; - dmq::xstring thread_name; - size_t queue_depth; // Current depth - size_t queue_depth_max_window;// Max depth since last snapshot - size_t queue_depth_max_all; // All-time max depth - size_t queue_size_limit; // Max allowed - float latency_avg_ms; // Avg wait in window - float latency_max_window_ms; // Max wait since last snapshot - float latency_max_all_ms; // All-time max wait - float invoke_avg_ms; // Avg execution in window - float invoke_max_window_ms; // Max execution since last snapshot - float invoke_max_all_ms; // All-time max execution - uint64_t dispatch_count; // Total dispatches (all-time) - }; -#endif - - /// Constructor - /// @param threadName The name of the thread for debugging. - /// @param maxQueueSize The maximum number of messages allowed in the queue. - /// 0 falls back to dmq::THREAD_DESKTOP_QUEUE_SIZE -- a high-water-mark - /// safety net, not a throughput limiter, against unbounded growth if - /// the destination thread is dead/stuck. - /// @param fullPolicy When the queue is full: FAULT (default), DROP, or TIMEOUT. - /// @param dispatchTimeout Duration to wait before giving up when policy is TIMEOUT. - /// @param cpuName Optional CPU/Core name grouping for monitoring tools. - Win32Thread(const char* threadName, size_t maxQueueSize = 0, FullPolicy fullPolicy = FullPolicy::FAULT, - dmq::Duration dispatchTimeout = dmq::DEFAULT_DISPATCH_TIMEOUT, const char* cpuName = ""); - - Win32Thread(const std::string& threadName, size_t maxQueueSize = 0, FullPolicy fullPolicy = FullPolicy::FAULT, - dmq::Duration dispatchTimeout = dmq::DEFAULT_DISPATCH_TIMEOUT, const std::string& cpuName = "") - : Win32Thread(threadName.c_str(), maxQueueSize, fullPolicy, dispatchTimeout, cpuName.c_str()) {} - - /// Destructor - virtual ~Win32Thread(); - - /// Called once to create the worker thread. If watchdogTimeout value - /// provided, the maximum watchdog interval is used. Otherwise no watchdog. - /// @param[in] watchdogTimeout - optional watchdog timeout. - /// @return TRUE if thread is created. FALSE otherwise. - bool CreateThread(std::optional watchdogTimeout = std::nullopt); - - /// Shut down the worker thread. - /// @param[in] policy - DRAIN (default) invokes every message queued before this - /// call first; DISCARD invokes only the message already running and cancels - /// the rest (see dmq::ExitPolicy). Called from the thread's own message - /// handler (a self-exit), queued messages are always discarded. - void ExitThread(ExitPolicy policy = ExitPolicy::DRAIN); - - /// Get the ID of this thread instance - DWORD GetThreadId(); - - /// Get the ID of the currently executing thread - static DWORD GetCurrentThreadId(); - - /// Returns true if the calling thread is this thread - virtual bool IsCurrentThread() override; - - /// Get thread name - dmq::xstring GetThreadName() { return THREAD_NAME; } - - /// Get size of thread message queue. - size_t GetQueueSize(); - - /// Sleep for a duration. - /// @param[in] timeout - the duration to sleep. - static void Sleep(dmq::Duration timeout); - - /// Dispatch and invoke a delegate target on the destination thread. - /// @param[in] msg - Delegate message containing target function - /// arguments. - virtual bool DispatchDelegate(std::shared_ptr msg) override; - - /// @brief Register a handler invoked when DispatchDelegate() drops a message: - /// under FullPolicy::DROP (queue full, discarded immediately) or - /// FullPolicy::TIMEOUT (queue stayed full for dispatchTimeout, discarded). - /// Optional; unset by default. Called synchronously on the calling (producer) - /// thread, with the queue depth at the time of the drop. - void SetDroppedHandler(const dmq::UnicastDelegate& handler) { m_droppedHandler = handler; } - void SetDroppedHandler(dmq::UnicastDelegate&& handler) { m_droppedHandler = std::move(handler); } - - /// @brief Register a handler invoked on the worker thread before it processes - /// any message. Use it for per-thread setup (COM, a language runtime attach, - /// thread-local state, affinity). CreateThread() returns only after it completes. - /// @details Must be called while the thread is not running (before CreateThread(), - /// or after ExitThread()); calling it on a running thread faults. It runs again - /// on each CreateThread(). Messages dispatched meanwhile are queued, not lost. - void SetStartHandler(const dmq::UnicastDelegate& handler) { DMQ_ASSERT_TRUE(m_hThread == NULL); m_startHandler = handler; } - void SetStartHandler(dmq::UnicastDelegate&& handler) { DMQ_ASSERT_TRUE(m_hThread == NULL); m_startHandler = std::move(handler); } - - /// @brief Optional: hold this thread at `gate` once it is created, until - /// `gate->Open()`. Pass nullptr (the default) to start at once. - /// @details CreateThread() still runs the start handler and returns when the - /// thread is ready; the thread then processes nothing, at any priority, until - /// the gate opens. Use one gate for a group of threads so they all start - /// together after setup. See port/os/common/StartGate.h. Must be called while - /// the thread is not running; calling it on a running thread faults. - void SetStartGate(StartGate* gate) { DMQ_ASSERT_TRUE(m_hThread == NULL); m_startGate.Set(gate); } - - /// @brief Register a handler invoked on the worker thread after it processes - /// its last message, as the thread exits. Use it to undo SetStartHandler() setup. - /// @details Must be called while the thread is not running; calling it on a - /// running thread faults. The handler is copied when the thread starts. - /// ExitThread() from another thread returns after it completes. If the thread - /// exits itself (ExitThread() from a handler on this thread), it runs after the - /// owning Win32Thread may already be destroyed, so it must not touch that object. - void SetExitHandler(const dmq::UnicastDelegate& handler) { DMQ_ASSERT_TRUE(m_hThread == NULL); m_exitHandler = handler; } - void SetExitHandler(dmq::UnicastDelegate&& handler) { DMQ_ASSERT_TRUE(m_hThread == NULL); m_exitHandler = std::move(handler); } - - /// @brief Register a handler invoked on the worker thread when its queue has - /// been empty for `interval`, then again every `interval` while it stays empty. - /// Any message processed restarts the countdown. Use it for background work that - /// should yield to messages: polling, housekeeping, entering low power. - /// @details Must be called while the thread is not running; calling it on a - /// running thread faults. The handler and interval are copied when the thread - /// starts. Not called once ExitThread() has been requested. - /// @param[in] handler - the idle handler, or an empty delegate to disable. - /// @param[in] interval - quiet time before each call. Must be greater than zero. - /// Defaults to dmq::THREAD_IDLE_INTERVAL (DMQ_THREAD_IDLE_INTERVAL). - void SetIdleHandler(const dmq::UnicastDelegate& handler, dmq::Duration interval = dmq::THREAD_IDLE_INTERVAL) - { - DMQ_ASSERT_TRUE(m_hThread == NULL); - DMQ_ASSERT_TRUE(interval > dmq::Duration::zero()); - m_idleHandler = handler; - m_idleInterval = interval; - } - void SetIdleHandler(dmq::UnicastDelegate&& handler, dmq::Duration interval = dmq::THREAD_IDLE_INTERVAL) - { - DMQ_ASSERT_TRUE(m_hThread == NULL); - DMQ_ASSERT_TRUE(interval > dmq::Duration::zero()); - m_idleHandler = std::move(handler); - m_idleInterval = interval; - } - - /// @brief Manually update the watchdog alive timestamp. - /// @details The Run() loop refreshes the timestamp automatically on every iteration. - /// Call this from inside long-running message handlers to prevent a false watchdog - /// alarm when a handler legitimately takes longer than watchdogTimeout. - void ThreadCheck(); - - /// @brief Static method to check all registered threads for watchdog expiration. - static void WatchdogCheckAll(); - -#if defined(DMQ_DATABUS_TOOLS) - /// @brief Capture and reset windowed statistics. - ThreadStats SnapshotStats(); -#endif - -private: - Win32Thread(const Win32Thread&) = delete; - Win32Thread& operator=(const Win32Thread&) = delete; - - /// Win32 thread proc entry point - static DWORD WINAPI ThreadProc(LPVOID lpParam); - - /// Entry point for the thread - void Process(); - - /// Check watchdog is expired. Called by WatchdogCheckAll(), which the application - /// calls periodically, typically from its highest-priority task. Thread-safe. - void WatchdogCheck(); - - /// Get registry head using the "Immortal" Pattern - static Win32Thread*& GetWatchdogHead(); - - /// Get registry lock using the "Immortal" Pattern - static dmq::RecursiveMutex& GetWatchdogLock(); - - HANDLE m_hThread = NULL; - DWORD m_threadId = 0; - - // Manual-reset event to synchronize thread startup - HANDLE m_hStartEvent = NULL; - - CRITICAL_SECTION m_cs; - - // Condition variable to wake up consumers when a message is enqueued - CONDITION_VARIABLE m_cvNotEmpty; - - // Condition variable to wake up blocked producers when space is available - CONDITION_VARIABLE m_cvNotFull; - - std::deque> m_highQueue; - std::deque> m_normalQueue; - - const dmq::xstring THREAD_NAME; - const dmq::xstring CPU_NAME; - - // Max queue size for back pressure (0 = unlimited) - const size_t MAX_QUEUE_SIZE; - - // Policy applied when the thread message queue is full. - const FullPolicy FULL_POLICY; - - // Timeout duration for TIMEOUT policy - const dmq::Duration m_dispatchTimeout; - - // Optional handler invoked when a message is dropped (FullPolicy::DROP or TIMEOUT) - dmq::UnicastDelegate m_droppedHandler; - - // Optional handlers invoked on the worker thread at start, exit and when idle - dmq::UnicastDelegate m_startHandler; - dmq::UnicastDelegate m_exitHandler; - dmq::UnicastDelegate m_idleHandler; - dmq::Duration m_idleInterval = dmq::Duration::zero(); - - std::atomic m_exit; - - // Watchdog related members - std::atomic m_lastAliveTime{dmq::TimePoint()}; - std::atomic m_watchdogTimeout{dmq::Duration(0)}; - Win32Thread* m_watchdogNext = nullptr; - - // Optional start gate (SetStartGate()): its state, and whether the thread is - // held at it (the watchdog doesn't report a thread waiting by design) - StartGateClient m_startGate; - -#if defined(DMQ_DATABUS_TOOLS) - // Monitoring statistics members - size_t m_queueDepthMaxWindow = 0; - size_t m_queueDepthMaxAll = 0; - - dmq::Duration m_latencyTotalWindow = dmq::Duration(0); - uint32_t m_latencyCountWindow = 0; - dmq::Duration m_latencyMaxWindow = dmq::Duration(0); - dmq::Duration m_latencyMaxAll = dmq::Duration(0); - - dmq::Duration m_invokeTotalWindow = dmq::Duration(0); - uint32_t m_invokeCountWindow = 0; - dmq::Duration m_invokeMaxWindow = dmq::Duration(0); - dmq::Duration m_invokeMaxAll = dmq::Duration(0); - - uint64_t m_dispatchCountAll = 0; -#endif -}; - -/// @brief Backward-compatible name: existing code referencing dmq::os::Thread -/// keeps compiling unchanged against the Win32 port. -using Thread = Win32Thread; - -} // namespace dmq::os - - -#endif diff --git a/DelegateMQ/port/os/zephyr/ZephyrClock.h b/DelegateMQ/port/os/zephyr/ZephyrClock.h deleted file mode 100644 index 6093a2b..0000000 --- a/DelegateMQ/port/os/zephyr/ZephyrClock.h +++ /dev/null @@ -1,22 +0,0 @@ -#ifndef ZEPHYR_CLOCK_H -#define ZEPHYR_CLOCK_H - -#include -#include - -namespace dmq::os { - struct ZephyrClock { - // Zephyr k_uptime_get() returns milliseconds (int64_t) - using rep = int64_t; - using period = std::milli; - using duration = std::chrono::duration; - using time_point = std::chrono::time_point; - static const bool is_steady = true; - - static time_point now() noexcept { - return time_point(duration(k_uptime_get())); - } - }; -} // namespace dmq::os - -#endif // ZEPHYR_CLOCK_H \ No newline at end of file diff --git a/DelegateMQ/port/os/zephyr/ZephyrCriticalSection.h b/DelegateMQ/port/os/zephyr/ZephyrCriticalSection.h deleted file mode 100644 index 0bf547b..0000000 --- a/DelegateMQ/port/os/zephyr/ZephyrCriticalSection.h +++ /dev/null @@ -1,72 +0,0 @@ -#ifndef ZEPHYR_CRITICAL_SECTION_H -#define ZEPHYR_CRITICAL_SECTION_H - -/// @file ZephyrCriticalSection.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief ISR-safe critical section for Zephyr. -/// -/// @details -/// k_mutex_lock() is a priority-inheritance-aware, thread-only primitive in -/// Zephyr, like every other RTOS here -- it cannot be used from ISR context. -/// This type uses irq_lock()/irq_unlock(key) instead, which Zephyr documents -/// as safe from both thread and ISR context (it's Zephyr's own primitive for -/// exactly this: protecting something tiny that ISR and thread code both -/// touch). Unlike ThreadX's plain disable/restore, irq_lock() returns a key -/// that must be threaded back into irq_unlock() -- stored here as a member so -/// it survives the gap between the separate lock()/unlock() calls. -/// -/// *** NARROW PURPOSE -- DO NOT USE THIS AS A GENERAL-PURPOSE LOCK *** -/// Holding this masks interrupts on the CPU for as long as it is held. Only -/// use it to protect something genuinely tiny and bounded that may be -/// touched from ISR context. Do NOT use it in place of dmq::Mutex / -/// dmq::RecursiveMutex for ordinary thread-to-thread synchronization (e.g. -/// DataBus internals, a Thread's message queue) -- anything that can block, -/// take a while, or run for an unbounded time must not run with interrupts -/// globally masked; that is a real-time correctness bug on hardware, not -/// just a style issue. -/// -/// *** NOT RE-LOCKABLE ON THE SAME INSTANCE *** -/// Unlike dmq::RecursiveMutex, calling lock() twice on the SAME instance -/// without an intervening unlock() is incorrect: the second lock() call -/// overwrites the single saved key with the (already locked) inner key, so -/// the outer unlock() restores the wrong state. There is no "recursive" -/// variant of this type -- it has no ownership concept to make recursion -/// meaningful, and Timer's own usage never nests. Locking two DIFFERENT -/// instances in proper LIFO lock/unlock order is fine: each instance saves -/// and restores its own key independently. - -#include - -namespace dmq::os { - - // ========================================================================= - // ZephyrCriticalSection - // See the file-level comment above before using this type anywhere new. - // ========================================================================= - class ZephyrCriticalSection { - public: - ZephyrCriticalSection() = default; - - void lock() { - m_key = irq_lock(); - } - - void unlock() { - irq_unlock(m_key); - } - - // No try_lock(): interrupt masking cannot fail to "acquire", so a - // try_lock() here would always trivially succeed and isn't meaningful. - - ZephyrCriticalSection(const ZephyrCriticalSection&) = delete; - ZephyrCriticalSection& operator=(const ZephyrCriticalSection&) = delete; - - private: - unsigned int m_key = 0; - }; - -} // namespace dmq::os - -#endif // ZEPHYR_CRITICAL_SECTION_H diff --git a/DelegateMQ/port/os/zephyr/ZephyrDelegateQueue.h b/DelegateMQ/port/os/zephyr/ZephyrDelegateQueue.h deleted file mode 100644 index 9e077eb..0000000 --- a/DelegateMQ/port/os/zephyr/ZephyrDelegateQueue.h +++ /dev/null @@ -1,187 +0,0 @@ -#ifndef ZEPHYR_DELEGATE_QUEUE_H -#define ZEPHYR_DELEGATE_QUEUE_H - -/// @file ZephyrDelegateQueue.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief Thin RAII wrapper around a pair of Zephyr k_msgq primitives used by -/// dmq::os::Thread to carry pending ThreadMsg pointers, with priority support. -/// -/// @details -/// Zephyr's k_msgq has no native "send to front" / priority-put primitive -/// (unlike FreeRTOS's xQueueSendToFront, ThreadX's tx_queue_front_send, or -/// CMSIS-RTOS2's osMessageQueuePut msg_prio argument) -- a single k_msgq is -/// strict FIFO, which previously meant dmq::Priority::HIGH was silently -/// treated as NORMAL on this port. To give HIGH the same "jumps the FIFO" -/// semantics here as on every other RTOS port, this wrapper keeps two -/// independent k_msgq instances (mirroring the desktop stdlib/win32/qt ports' -/// two-deque model) and Receive() always drains the high-priority queue -/// first. -/// -/// This doubles queue memory relative to a single-k_msgq design (each lane -/// gets its own 'capacity'-sized buffer, so worst-case combined depth is -/// 2x capacity rather than exactly capacity) and Receive() uses k_poll() to -/// block efficiently on whichever queue gets data first, rather than a -/// single native blocking receive. This class owns no policy decisions of -/// its own (FullPolicy, timeout computation, and stats stay in Thread.cpp) -/// -- it only knows how to move ThreadMsg* pointers through the two queues. -/// -/// @warning Unverified: written against the documented Zephyr k_msgq/k_poll -/// API but never compiled or run against a real Zephyr SDK/west workspace -/// (none is available in this development environment). The k_poll()-based -/// dual-queue wait is more novel API surface than the plain k_msgq_put/get -/// calls used elsewhere in this port, so review this file with extra care -/// and exercise it on a real target or simulator before relying on it in -/// production -- consistent with the existing caveat on this port's -/// CriticalSection implementation. - -#include -#include "port/os/common/ThreadMsg.h" -#include -#include - -namespace dmq::os { - -class ZephyrDelegateQueue -{ -public: - ZephyrDelegateQueue() - { - memset(&m_highMsgq, 0, sizeof(m_highMsgq)); - memset(&m_normalMsgq, 0, sizeof(m_normalMsgq)); - } - ~ZephyrDelegateQueue() { Destroy(); } - - ZephyrDelegateQueue(const ZephyrDelegateQueue&) = delete; - ZephyrDelegateQueue& operator=(const ZephyrDelegateQueue&) = delete; - - /// Create both queues, each sized to hold up to 'capacity' pointers. - /// @return true on success, false if either buffer allocation failed. - bool Create(size_t capacity) - { - if (m_created) - return true; - - size_t bufBytes = MSG_SIZE * capacity; - - char* highBuf = (char*)k_aligned_alloc(sizeof(void*), bufBytes); - if (!highBuf) - return false; - m_highBuffer.reset(highBuf); - k_msgq_init(&m_highMsgq, m_highBuffer.get(), MSG_SIZE, capacity); - - char* normalBuf = (char*)k_aligned_alloc(sizeof(void*), bufBytes); - if (!normalBuf) { - m_highBuffer.reset(); - return false; - } - m_normalBuffer.reset(normalBuf); - k_msgq_init(&m_normalMsgq, m_normalBuffer.get(), MSG_SIZE, capacity); - - m_created = true; - return true; - } - - bool IsCreated() const { return m_created; } - - /// Send a message. 'highPriority' routes to the high-priority queue, - /// which Receive() always drains first; otherwise the normal queue. - /// 'waitOption' is K_NO_WAIT for non-blocking, K_FOREVER to block - /// forever, or a finite k_timeout_t for a bounded wait -- applied only - /// to the one queue the message is routed to (each lane has its own - /// independent capacity; there is no combined-depth wait across both). - /// @return true if the message was enqueued. - bool Send(ThreadMsg* msg, bool highPriority, k_timeout_t waitOption) - { - struct k_msgq* q = highPriority ? &m_highMsgq : &m_normalMsgq; - return k_msgq_put(q, &msg, waitOption) == 0; - } - - /// Receive a message pointer, blocking up to 'waitOption'. The - /// high-priority queue is always checked -- and drained -- first, so a - /// pending HIGH message is returned even if NORMAL messages arrived - /// earlier. Uses k_poll() to block efficiently on both queues at once - /// rather than polling in a loop. - /// @return the message, or nullptr on timeout. - ThreadMsg* Receive(k_timeout_t waitOption) - { - ThreadMsg* msg = nullptr; - - // Fast path: don't pay for k_poll() if something is already pending. - if (k_msgq_get(&m_highMsgq, &msg, K_NO_WAIT) == 0) - return msg; - if (k_msgq_get(&m_normalMsgq, &msg, K_NO_WAIT) == 0) - return msg; - - if (K_TIMEOUT_EQ(waitOption, K_NO_WAIT)) - return nullptr; - - struct k_poll_event events[2]; - k_poll_event_init(&events[0], K_POLL_TYPE_MSGQ_DATA_AVAILABLE, K_POLL_MODE_NOTIFY_ONLY, &m_highMsgq); - k_poll_event_init(&events[1], K_POLL_TYPE_MSGQ_DATA_AVAILABLE, K_POLL_MODE_NOTIFY_ONLY, &m_normalMsgq); - - if (k_poll(events, 2, waitOption) != 0) - return nullptr; // timed out waiting for either queue - - // k_poll only signals readiness; re-check high first so a HIGH - // message still jumps the FIFO even if NORMAL became ready too. - if (k_msgq_get(&m_highMsgq, &msg, K_NO_WAIT) == 0) - return msg; - if (k_msgq_get(&m_normalMsgq, &msg, K_NO_WAIT) == 0) - return msg; - return nullptr; - } - - /// Combined number of messages waiting across both queues. - size_t Size() - { - if (!m_created) - return 0; - return static_cast(k_msgq_num_used_get(&m_highMsgq)) - + static_cast(k_msgq_num_used_get(&m_normalMsgq)); - } - - /// Remove and delete every pending message in both queues without - /// blocking. Used during shutdown once the owning thread has stopped - /// consuming the queues. - /// Each message is canceled first (CancelThreadMsg()), releasing a sender - /// blocked waiting on it. - void DrainAndDelete() - { - ThreadMsg* msg = nullptr; - while (k_msgq_get(&m_highMsgq, &msg, K_NO_WAIT) == 0) { - CancelThreadMsg(*msg); // Release a sender blocked on it - delete msg; - } - while (k_msgq_get(&m_normalMsgq, &msg, K_NO_WAIT) == 0) { - CancelThreadMsg(*msg); // Release a sender blocked on it - delete msg; - } - } - - void Destroy() - { - m_highBuffer.reset(); - m_normalBuffer.reset(); - m_created = false; - } - -private: - using ZephyrDeleter = void(*)(void*); - - static const size_t MSG_SIZE = sizeof(ThreadMsg*); - - struct k_msgq m_highMsgq; - struct k_msgq m_normalMsgq; - - // Dynamically allocated queue buffers, freed via k_free. - std::unique_ptr m_highBuffer{nullptr, k_free}; - std::unique_ptr m_normalBuffer{nullptr, k_free}; - - bool m_created = false; -}; - -} // namespace dmq::os - -#endif // ZEPHYR_DELEGATE_QUEUE_H diff --git a/DelegateMQ/port/os/zephyr/ZephyrMutex.h b/DelegateMQ/port/os/zephyr/ZephyrMutex.h deleted file mode 100644 index 0d916d6..0000000 --- a/DelegateMQ/port/os/zephyr/ZephyrMutex.h +++ /dev/null @@ -1,43 +0,0 @@ -#ifndef ZEPHYR_MUTEX_H -#define ZEPHYR_MUTEX_H - -#include - -namespace dmq::os { - - // ========================================================================= - // ZephyrMutex - // Wraps k_mutex. - // ========================================================================= - class ZephyrMutex { - public: - ZephyrMutex() { - k_mutex_init(&m_mutex); - } - - ~ZephyrMutex() { } - - void lock() { - k_mutex_lock(&m_mutex, K_FOREVER); - } - - // REQUIRED for std::unique_lock compatibility - bool try_lock() { - return k_mutex_lock(&m_mutex, K_NO_WAIT) == 0; - } - - void unlock() { - k_mutex_unlock(&m_mutex); - } - - ZephyrMutex(const ZephyrMutex&) = delete; - ZephyrMutex& operator=(const ZephyrMutex&) = delete; - - private: - struct k_mutex m_mutex; - }; - - using ZephyrRecursiveMutex = ZephyrMutex; -} // namespace dmq::os - -#endif // ZEPHYR_MUTEX_H \ No newline at end of file diff --git a/DelegateMQ/port/os/zephyr/ZephyrSemaphore.h b/DelegateMQ/port/os/zephyr/ZephyrSemaphore.h deleted file mode 100644 index 3693c19..0000000 --- a/DelegateMQ/port/os/zephyr/ZephyrSemaphore.h +++ /dev/null @@ -1,77 +0,0 @@ -#ifndef ZEPHYR_SEMAPHORE_H -#define ZEPHYR_SEMAPHORE_H - -/// @file ZephyrSemaphore.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief dmq::Semaphore backing for Zephyr, using Zephyr's native k_sem -/// directly instead of the generic dmq::ConditionVariable + dmq::Mutex -/// implementation in delegate/Semaphore.h. -/// -/// @details -/// Zephyr has no dmq::ConditionVariable port (no DMQ_HAS_CV), so the -/// generic Semaphore implementation isn't available here -- but Zephyr -/// already provides a native binary semaphore, which is a more direct fit -/// anyway (no need to build one out of a mutex + condition variable when -/// the RTOS already has a real one). DelegateOpt.h resolves dmq::Semaphore -/// to this type on Zephyr; see the "Semaphore" comment next to -/// DMQ_THREAD_ZEPHYR's `using Semaphore = ...;` there. -/// -/// @note This header is included from DelegateOpt.h's early port-include -/// block, before "namespace dmq { ... }" opens and dmq::Duration is defined -/// inside it (including it any later would nest as dmq::dmq::os instead of -/// dmq::os) -- so, like ThreadXConditionVariable.h and -/// FreeRTOSConditionVariable.h, Wait() is templated on the chrono duration -/// type instead of depending on dmq::Duration directly. A dmq::Duration -/// argument still deduces through it seamlessly at the call site, since -/// dmq::Duration is itself a std::chrono::duration specialization. - -#include -#include - -namespace dmq::os { - - // ========================================================================= - // ZephyrSemaphore - // Binary semaphore (max count 1), matching the semantics of the generic - // dmq::Semaphore this replaces: Signal() when already signaled is a - // no-op (not a counting semaphore), and Wait() consumes exactly one - // pending signal. - // ========================================================================= - class ZephyrSemaphore { - public: - ZephyrSemaphore() { - k_sem_init(&m_sem, 0, 1); - } - - ~ZephyrSemaphore() = default; - - /// Called to wait on a semaphore to be signaled. - /// @param[in] timeout - semaphore timeout - /// @return Return true if semaphore signaled, false if timeout occurred. - template - bool Wait(const std::chrono::duration& timeout) { - using DurationT = std::chrono::duration; - if (timeout == DurationT::max()) { - return k_sem_take(&m_sem, K_FOREVER) == 0; - } - auto ms = std::chrono::duration_cast(timeout).count(); - return k_sem_take(&m_sem, K_MSEC(ms)) == 0; - } - - /// Called to signal a semaphore. - void Signal() { - k_sem_give(&m_sem); - } - - ZephyrSemaphore(const ZephyrSemaphore&) = delete; - ZephyrSemaphore& operator=(const ZephyrSemaphore&) = delete; - - private: - struct k_sem m_sem; - }; - -} // namespace dmq::os - -#endif // ZEPHYR_SEMAPHORE_H diff --git a/DelegateMQ/port/os/zephyr/ZephyrThisThread.h b/DelegateMQ/port/os/zephyr/ZephyrThisThread.h deleted file mode 100644 index 5ac9c95..0000000 --- a/DelegateMQ/port/os/zephyr/ZephyrThisThread.h +++ /dev/null @@ -1,47 +0,0 @@ -#ifndef ZEPHYR_THIS_THREAD_H -#define ZEPHYR_THIS_THREAD_H - -/// @file ZephyrThisThread.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief Portable sleep_for()/yield() for the calling thread, Zephyr backend. -/// -/// @details -/// This is dmq::ThisThread for this port (see DelegateOpt.h). GetCurrent() -/// uses RegistryCurrentThread, keyed by the calling thread's id. Exists so -/// library internals that need to delay or yield (e.g. RetryMonitor backoff) -/// aren't forced to pull in the full dmq::os::Thread class -- which also -/// drags in the message queue, watchdog, and stats machinery -- just to -/// sleep. dmq::os::Thread::Sleep() forwards here too, so the Zephyr delay -/// call is implemented exactly once. - -#include -#include "ZephyrMutex.h" -#include "port/os/common/CurrentThreadStorage.h" -#include - -namespace dmq::os { - - /// @brief Key for RegistryCurrentThread: the calling thread's id, or 0 inside an ISR. - inline uintptr_t ZephyrCurrentThreadKey() { - if (k_is_in_isr()) - return 0; - return reinterpret_cast(k_current_get()); - } - - struct ZephyrThisThread : RegistryCurrentThread { - template - static void sleep_for(std::chrono::duration d) { - const auto ms = std::chrono::duration_cast(d); - k_sleep(K_MSEC(ms.count())); - } - - static void yield() noexcept { - k_yield(); - } - }; - -} // namespace dmq::os - -#endif // ZEPHYR_THIS_THREAD_H diff --git a/DelegateMQ/port/os/zephyr/ZephyrThread.cpp b/DelegateMQ/port/os/zephyr/ZephyrThread.cpp deleted file mode 100644 index eda46e8..0000000 --- a/DelegateMQ/port/os/zephyr/ZephyrThread.cpp +++ /dev/null @@ -1,684 +0,0 @@ -// Compiles to nothing unless DMQ_THREAD_ZEPHYR is selected, so every DelegateMQ source -// file can be added to a build (see src/DelegateMQ.cpp). -#include "delegate/DelegateSelect.h" -#if defined(DMQ_THREAD_ZEPHYR) - -#include "DelegateMQ.h" -#include "ZephyrThread.h" -#include "port/os/common/ThreadMsg.h" -#include "port/os/common/ThreadHooks.h" -#include "extras/util/Fault.h" -#include -#include // for memset - -// Define DMQ_ASSERT_TRUE if not already defined -#ifndef DMQ_ASSERT_TRUE -#define DMQ_ASSERT_TRUE(x) __ASSERT(x, "DelegateMQ Assertion Failed") -#endif - -namespace dmq::os { - -using namespace dmq::util; - -//---------------------------------------------------------------------------- -// Thread Constructor -//---------------------------------------------------------------------------- -ZephyrThread::ZephyrThread(const char* threadName, size_t maxQueueSize, FullPolicy fullPolicy, dmq::Duration dispatchTimeout, const char* cpuName) - : THREAD_NAME(threadName) - , CPU_NAME(cpuName) - , m_queueSize((maxQueueSize == 0) ? DEFAULT_QUEUE_SIZE : maxQueueSize) - , FULL_POLICY(fullPolicy) - , m_dispatchTimeout(dispatchTimeout) - , m_exit(false) -{ - m_priority = K_PRIO_PREEMPT(dmq::ZEPHYR_THREAD_PRIORITY); // Default priority, DMQ_ZEPHYR_THREAD_PRIORITY - - // Initialize objects to zero (m_queue zeroes its own control blocks in - // ZephyrDelegateQueue's constructor) - memset(&m_thread, 0, sizeof(m_thread)); - - // Initialize exit semaphore (Initial count 0, Limit 1) - k_sem_init(&m_exitSem, 0, 1); - k_sem_init(&m_startSem, 0, 1); - -#if defined(DMQ_DATABUS_TOOLS) - k_mutex_init(&m_statMutex); -#endif -} - -//---------------------------------------------------------------------------- -// Thread Destructor -//---------------------------------------------------------------------------- -ZephyrThread::~ZephyrThread() -{ - // Deleting a ZephyrThread from one of its own callbacks is not supported: the - // destructor would free the stack and control block the thread is still - // running on, and ThreadX/Zephyr (unlike FreeRTOS, whose idle task frees a - // self-deleted task's stack) have no way to free them afterwards. Fault - // immediately instead of corrupting memory. To stop a thread from inside - // its own callback, call ExitThread() and delete the object from another - // thread. - if (m_stackMemory && k_current_get() == &m_thread) - DMQ_ASSERT(); - - ExitThread(); - - const dmq::LockGuard lock(GetWatchdogLock()); - ZephyrThread** pp = &GetWatchdogHead(); - while (*pp != nullptr) - { - if (*pp == this) - { - *pp = this->m_watchdogNext; - this->m_watchdogNext = nullptr; - break; - } - pp = &((*pp)->m_watchdogNext); - } -} - -//---------------------------------------------------------------------------- -// CreateThread -//---------------------------------------------------------------------------- -bool ZephyrThread::CreateThread(std::optional watchdogTimeout) -{ - // Check if thread is already created (dummy check on stack ptr) - if (!m_stackMemory) - { - // Reset from a previous ExitThread(), so the thread can be created again - m_exit.store(false); - // Held from creation, so the watchdog never sees a gated thread as hung - // before it reaches the gate (e.g. created before the scheduler runs) - m_startGate.OnCreate(); - // Set before the thread exists: its loop reads the timeout before its - // first queue wait, and an idle thread waits forever with no timeout - m_lastAliveTime.store(Timer::GetNow()); - m_watchdogTimeout.store(watchdogTimeout.value_or(dmq::Duration(0))); - m_discard.store(false); - - // 1. Create Message Queues - DMQ_ASSERT_TRUE(m_queue.Create(m_queueSize)); - - // 2. Create Thread - // CRITICAL: Stacks must be aligned to Z_KERNEL_STACK_OBJ_ALIGN for MPU/Arch reasons. - // We use k_aligned_alloc instead of new char[]. - // K_THREAD_STACK_LEN calculates the correct size including guard pages/metadata. - size_t stackBytes = K_THREAD_STACK_LEN(STACK_SIZE); - char* stackBuf = (char*)k_aligned_alloc(Z_KERNEL_STACK_OBJ_ALIGN, stackBytes); - if (!stackBuf) - BAD_ALLOC(); - - m_stackMemory.reset(stackBuf); // Ownership passed to unique_ptr - - // Called from a thread, CreateThread() waits for the start handler. - // Pre-kernel or from an ISR it cannot block; the start handler then runs - // when the thread is first scheduled, still before any message. - m_startSync = !k_is_pre_kernel() && !k_is_in_isr(); - - k_tid_t tid = k_thread_create(&m_thread, - (k_thread_stack_t*)m_stackMemory.get(), - STACK_SIZE, - (k_thread_entry_t)ZephyrThread::Process, - this, NULL, NULL, - m_priority, - 0, - K_NO_WAIT); - - DMQ_ASSERT_TRUE(tid != nullptr); - - // Optional: Set thread name for debug - k_thread_name_set(tid, THREAD_NAME.c_str()); - - // Wait for the start handler to complete - if (m_startSync) - k_sem_take(&m_startSem, K_FOREVER); - - m_lastAliveTime.store(Timer::GetNow()); - - if (watchdogTimeout.has_value()) - { - - const dmq::LockGuard lock(GetWatchdogLock()); - - // Add to watchdog registry if not already present - bool found = false; - ZephyrThread* p = GetWatchdogHead(); - while (p != nullptr) - { - if (p == this) - { - found = true; - break; - } - p = p->m_watchdogNext; - } - - if (!found) - { - m_watchdogNext = GetWatchdogHead(); - GetWatchdogHead() = this; - } - } - } - return true; -} - -//---------------------------------------------------------------------------- -// ExitThread -//---------------------------------------------------------------------------- -void ZephyrThread::ExitThread(ExitPolicy policy) -{ - if (m_stackMemory) - { - // Set before m_exit: Run() reads it for every message ahead of the exit message - m_discard.store(policy == ExitPolicy::DISCARD); - m_exit.store(true); - - // A thread held at its start gate isn't waiting on its queue: wake it so it - // sees the exit flag (set above) and leaves. Never touches the gate itself, - // which may be destroyed once the thread is released. - m_startGate.Wake(); - - // Check self-exit BEFORE attempting to enqueue the exit message. If - // this thread is destroying itself from within its own dispatched - // callback, it is not consuming its own queue right now -- it is - // blocked here, inside ExitThread(). A blocking k_msgq_put() would - // deadlock forever if the queue happened to be full. No message needs - // to be queued in that case: Run()'s dispatch loop already checks - // m_selfExitPtr immediately after the current callback invoke - // returns, and unwinds without touching 'this' again. - // - // Crucially, a self-exiting thread must NOT touch m_queue or - // m_stackMemory here: it is still physically executing on - // m_stackMemory (unwinding back through Invoke()/Run()), and it - // cannot k_thread_join() itself. Set the flag and return immediately; - // the actual cleanup (queue drain/destroy, k_thread_join, stack free) - // is deferred to a later ExitThread() call made from a different - // thread context -- typically ~ZephyrThread(), which must itself run on - // another thread (it faults if run on this one) -- once m_selfExited - // tells that call it's safe to skip the message/semaphore handshake - // below (the thread already returned/is returning on its own) and go - // straight to the join+free. - if (k_current_get() == &m_thread) { - m_selfExited.store(true); - if (m_selfExitPtr) { *m_selfExitPtr = true; m_selfExitPtr = nullptr; } - m_startGate.Leave(); // exited from its start handler: never reaches the gate - // Self-exit: this thread runs no more messages, and the object may be - // destroyed once this handler returns. Stop watchdog checks now. - m_watchdogTimeout.store(dmq::Duration(0)); - return; - } - - if (!m_selfExited.load()) - { - // Send exit message - ThreadMsg* msg = new (std::nothrow) ThreadMsg(MSG_EXIT_THREAD); - if (msg) - { - // Wait forever to ensure message is sent - if (!m_queue.Send(msg, /*highPriority=*/false, K_FOREVER)) - { - delete msg; - } - } - - // Wait for thread to actually finish to avoid use-after-free of the stack. - k_sem_take(&m_exitSem, K_FOREVER); - } - - // k_sem_give() in Run() fires just before it returns -- taking the - // semaphore only proves Run() is about to return, not that the - // kernel has finished tearing the thread down (unlinking it from - // scheduler structures) after the entry function exits. Freeing - // m_thread's memory (this object may be stack-allocated) or - // m_stackMemory below before that teardown completes leaves the - // kernel with a dangling reference into memory about to be reused - // -- observed as a newly created thread at the same address never - // getting scheduled. k_thread_join() blocks until the kernel - // itself has marked the thread fully dead, which is the - // documented, race-free way to wait for this. It is also the right - // call in the deferred self-exit case: the thread has already - // returned or is in the process of returning on its own, so this - // either returns immediately or waits only as long as that natural - // teardown takes -- there is no risk of deadlock. - k_thread_join(&m_thread, K_FOREVER); - - // The thread has finished (or, on a self-exit, is in its last handler): - // stop watchdog checks. Not earlier, so a thread that hangs while - // ExitThread() waits for it is still reported. - m_watchdogTimeout.store(dmq::Duration(0)); - - m_queue.DrainAndDelete(); - m_queue.Destroy(); - - // Reset buffer to mark as exited. This prevents a double-entry deadlock: - // ~Thread() calls ExitThread() unconditionally, so if ExitThread() was already - // called explicitly, the second call must be a no-op (m_stackMemory is null). - m_stackMemory.reset(); - - // Allow this object to be reused for a fresh CreateThread()/Run() cycle. - m_selfExited.store(false); - - // Note: k_thread_abort is not needed because the thread will - // return from Run() and terminate naturally. - } -} - -//---------------------------------------------------------------------------- -// SetThreadPriority -//---------------------------------------------------------------------------- -void ZephyrThread::SetThreadPriority(int priority) -{ - m_priority = priority; - if (m_stackMemory) { - k_thread_priority_set(&m_thread, m_priority); - } -} - -//---------------------------------------------------------------------------- -// GetThreadId -//---------------------------------------------------------------------------- -k_tid_t ZephyrThread::GetThreadId() -{ - return &m_thread; -} - -//---------------------------------------------------------------------------- -// GetCurrentThreadId -//---------------------------------------------------------------------------- -k_tid_t ZephyrThread::GetCurrentThreadId() -{ - return k_current_get(); -} - -//---------------------------------------------------------------------------- -// IsCurrentThread -//---------------------------------------------------------------------------- -bool ZephyrThread::IsCurrentThread() -{ - return GetThreadId() == GetCurrentThreadId(); -} - -//---------------------------------------------------------------------------- -// GetQueueSize -//---------------------------------------------------------------------------- -size_t ZephyrThread::GetQueueSize() -{ - return m_queue.Size(); -} - -void ZephyrThread::Sleep(dmq::Duration timeout) { - dmq::ThisThread::sleep_for(timeout); -} - -//---------------------------------------------------------------------------- -// DispatchDelegate -//---------------------------------------------------------------------------- -bool ZephyrThread::DispatchDelegate(std::shared_ptr msg) -{ - DMQ_ASSERT_TRUE(m_stackMemory != nullptr); - - // 1. Allocate message container - ThreadMsg* threadMsg = new (std::nothrow) ThreadMsg(MSG_DISPATCH_DELEGATE, msg); - if (!threadMsg) return false; -#if defined(DMQ_DATABUS_TOOLS) - threadMsg->SetEnqueueTime(Timer::GetNow()); -#endif - - // 2. Send pointer to queue - k_timeout_t timeout; - if (FULL_POLICY == FullPolicy::TIMEOUT) - timeout = K_MSEC(std::chrono::duration_cast(m_dispatchTimeout).count()); - else - timeout = K_NO_WAIT; // DROP and FAULT: non-blocking - - // High priority routes to the queue Receive() always drains first. - bool sent = m_queue.Send(threadMsg, msg->GetPriority() == dmq::Priority::HIGH, timeout); - if (!sent) - { - if (FULL_POLICY == FullPolicy::FAULT) { - printf("[Thread] CRITICAL: Queue full on thread '%s'! TRIGGERING FAULT.\n", THREAD_NAME.c_str()); - DMQ_ASSERT_TRUE(sent); - } else if (FULL_POLICY == FullPolicy::TIMEOUT) { - printf("[Thread] WARNING: Queue post timed out on '%s' — possible deadlock. Message dropped.\n", THREAD_NAME.c_str()); - if (m_droppedHandler) - m_droppedHandler(GetQueueSize()); - } else { // DROP - if (m_droppedHandler) - m_droppedHandler(GetQueueSize()); - } - // Failed to enqueue (queue full or timed out) - delete threadMsg; - return false; - } - -#if defined(DMQ_DATABUS_TOOLS) - // Update monitoring stats - { - k_mutex_lock(&m_statMutex, K_FOREVER); - size_t currentDepth = GetQueueSize(); - if (currentDepth > m_queueDepthMaxWindow) m_queueDepthMaxWindow = currentDepth; - if (currentDepth > m_queueDepthMaxAll) m_queueDepthMaxAll = currentDepth; - k_mutex_unlock(&m_statMutex); - } -#endif - - return true; -} - -//---------------------------------------------------------------------------- -// Process (Static Entry Point) -//---------------------------------------------------------------------------- -void ZephyrThread::Process(void* p1, void* p2, void* p3) -{ - ZephyrThread* thread = static_cast(p1); - if (thread) - { - thread->Run(); - } - // Returning from entry point automatically terminates the thread in Zephyr -} - -//---------------------------------------------------------------------------- -// Run (Member Function Loop) -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- -// WatchdogCheck -//---------------------------------------------------------------------------- -void ZephyrThread::WatchdogCheck() -{ - if (m_startGate.IsHeld()) - return; // held at its start gate by design, not hung - - auto now = Timer::GetNow(); - auto lastAlive = m_lastAliveTime.load(); - auto watchdogTimeout = m_watchdogTimeout.load(); - - if (watchdogTimeout.count() > 0) - { - auto delta = now - lastAlive; - if (delta > watchdogTimeout) - { - WatchdogHandler(THREAD_NAME.c_str()); - } - } -} - -//---------------------------------------------------------------------------- -// ThreadCheck -//---------------------------------------------------------------------------- -void ZephyrThread::ThreadCheck() -{ - m_lastAliveTime.store(Timer::GetNow()); -} - -//---------------------------------------------------------------------------- -// WatchdogCheckAll -//---------------------------------------------------------------------------- -void ZephyrThread::WatchdogCheckAll() -{ - const dmq::LockGuard lock(GetWatchdogLock()); - ZephyrThread* p = GetWatchdogHead(); - while (p != nullptr) - { - p->WatchdogCheck(); - p = p->m_watchdogNext; - } -} - -//---------------------------------------------------------------------------- -// GetWatchdogHead -//---------------------------------------------------------------------------- -ZephyrThread*& ZephyrThread::GetWatchdogHead() -{ - static ZephyrThread* head = nullptr; - return head; -} - -//---------------------------------------------------------------------------- -// GetWatchdogLock -//---------------------------------------------------------------------------- -dmq::RecursiveMutex& ZephyrThread::GetWatchdogLock() -{ - static dmq::RecursiveMutex* lock = new dmq::RecursiveMutex(); - return *lock; -} - -//---------------------------------------------------------------------------- -// Run (Member Function Loop) -//---------------------------------------------------------------------------- -void ZephyrThread::Run() -{ - bool selfExit = false; - m_selfExitPtr = &selfExit; - - // Exit and idle handlers are copied onto this stack frame so they work on - // every return path, including a self-exit where 'this' may already be freed. - ThreadExitGuard exitGuard(m_exitHandler); - ThreadIdleTimer idle(m_idleHandler, m_idleInterval); - - // dmq::ThisThread::GetCurrent() returns this thread from here on. Reset - // before the exit handler runs (and destroyed before exitGuard on a - // self-exit), so the exit handler sees nullptr. - std::optional currentScope; - currentScope.emplace(this); - - if (m_startHandler) - m_startHandler(); - - // A start handler that exited this thread (ExitThread() on itself) leaves - // right after the signal below: once CreateThread() returns, the Thread may - // be destroyed, so nothing after the signal may touch 'this'. - const bool exitedInStart = selfExit; - - if (m_startSync) - k_sem_give(&m_startSem); - if (exitedInStart) - return; - - // Optional start gate: wait here, ready but processing nothing, until it opens - if (m_startGate.Enabled()) - { - const bool opened = m_startGate.Wait(m_exit); - m_lastAliveTime.store(Timer::GetNow()); // before Passed(): no stale watchdog read - m_startGate.Passed(); - // ExitThread() while held: run nothing. Cancel each queued message - // (DISCARD) until the exit message. Consuming them also keeps - // ExitThread()'s blocking send of the exit message from waiting on a - // full queue. - if (!opened) - m_discard.store(true); - } - - ThreadMsg* msg = nullptr; - while (!selfExit) - { - dmq::Duration watchdogTimeout; - { - m_lastAliveTime.store(Timer::GetNow()); - watchdogTimeout = m_watchdogTimeout.load(); - } - - // If watchdog active, use a finite timeout so we can periodically update - // m_lastAliveTime while idle. If an idle handler is set, wake no later - // than when it is due. Otherwise, block forever to save power. - dmq::Duration waitTime = idle.WaitTime(watchdogTimeout.count() > 0 ? watchdogTimeout / dmq::WATCHDOG_HEARTBEAT_DIVISOR : dmq::Duration(-1)); - k_timeout_t waitOption = K_FOREVER; - if (waitTime >= dmq::Duration::zero()) - { - // Rounded up, so only an idle handler that is already due waits 0 - waitOption = K_MSEC(std::chrono::ceil(waitTime).count()); - } - - // Block for a message or timeout - msg = m_queue.Receive(waitOption); - if (msg == nullptr) - { - // Exit requested but no exit message arrived (e.g. it could not be allocated) - if (m_exit.load()) - break; - - // Timed out with the queue empty: run the idle handler if it is due - if (idle.IsDue()) - { - idle.Run(); - // The idle handler exited this thread (and may have deleted it): leave - // without touching 'this', as the message path does - if (selfExit) - return; - } - } - else - { - int msgId = msg->GetId(); - if (msgId == MSG_DISPATCH_DELEGATE && m_discard.load()) - { - // ExitPolicy::DISCARD: skip messages queued ahead of the exit message - CancelThreadMsg(*msg); - } - else if (msgId == MSG_DISPATCH_DELEGATE) - { -#if defined(DMQ_DATABUS_TOOLS) - // Update latency stats before invoking - dmq::Duration latency = Timer::GetNow() - msg->GetEnqueueTime(); - { - k_mutex_lock(&m_statMutex, K_FOREVER); - m_latencyTotalWindow += latency; - m_latencyCountWindow++; - if (latency > m_latencyMaxWindow) m_latencyMaxWindow = latency; - if (latency > m_latencyMaxAll) m_latencyMaxAll = latency; - m_dispatchCountAll++; - k_mutex_unlock(&m_statMutex); - } -#endif - - auto delegateMsg = msg->GetData(); - DMQ_ASSERT_TRUE(delegateMsg); - auto invoker = delegateMsg->GetInvoker(); - DMQ_ASSERT_TRUE(invoker); - -#if defined(DMQ_DATABUS_TOOLS) - dmq::TimePoint start = Timer::GetNow(); -#endif -#if defined(__cpp_exceptions) && !defined(DMQ_ASSERTS) - bool success = false; - try { - success = invoker->Invoke(delegateMsg); - if (!selfExit) DMQ_ASSERT_TRUE(success); - } - catch (const std::bad_alloc& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled bad_alloc in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::invalid_argument& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled invalid_argument in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::runtime_error& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled runtime_error in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::exception& e) { - printf("[Thread:%s] Unhandled exception in delegate callback: %s\n", THREAD_NAME.c_str(), e.what()); - DMQ_ASSERT(); - } - catch (...) { - printf("[Thread:%s] Unhandled unknown exception in delegate callback.\n", THREAD_NAME.c_str()); - DMQ_ASSERT(); - } -#else - bool success = invoker->Invoke(delegateMsg); - if (!selfExit) DMQ_ASSERT_TRUE(success); -#endif - if (selfExit) { - delete msg; - return; - } - -#if defined(DMQ_DATABUS_TOOLS) - dmq::Duration invokeTime = Timer::GetNow() - start; - { - k_mutex_lock(&m_statMutex, K_FOREVER); - m_invokeTotalWindow += invokeTime; - m_invokeCountWindow++; - if (invokeTime > m_invokeMaxWindow) m_invokeMaxWindow = invokeTime; - if (invokeTime > m_invokeMaxAll) m_invokeMaxAll = invokeTime; - k_mutex_unlock(&m_statMutex); - } -#endif - } - - delete msg; - - if (msgId == MSG_EXIT_THREAD) { - break; - } - - // Any message restarts the idle countdown - idle.Restart(); - } - } - - // Run the exit handler before signalling ExitThread(), so it returns only after it - currentScope.reset(); - exitGuard.Fire(); - - // Clear before signalling: once ExitThread() returns, 'this' may be destroyed - m_selfExitPtr = nullptr; - // Signal that we are about to exit - k_sem_give(&m_exitSem); -} - -#if defined(DMQ_DATABUS_TOOLS) -//---------------------------------------------------------------------------- -// SnapshotStats -//---------------------------------------------------------------------------- -ZephyrThread::ThreadStats ZephyrThread::SnapshotStats() -{ - k_mutex_lock(&m_statMutex, K_FOREVER); - ThreadStats stats; - stats.cpu_name = CPU_NAME; - stats.thread_name = THREAD_NAME; - stats.queue_depth = GetQueueSize(); - stats.queue_depth_max_window = m_queueDepthMaxWindow; - stats.queue_depth_max_all = m_queueDepthMaxAll; - stats.queue_size_limit = m_queueSize; - - if (m_latencyCountWindow > 0) { - stats.latency_avg_ms = (float)std::chrono::duration_cast(m_latencyTotalWindow).count() / (static_cast(m_latencyCountWindow) * 1000.0f); - } else { - stats.latency_avg_ms = 0.0f; - } - - stats.latency_max_window_ms = (float)std::chrono::duration_cast(m_latencyMaxWindow).count() / 1000.0f; - stats.latency_max_all_ms = (float)std::chrono::duration_cast(m_latencyMaxAll).count() / 1000.0f; - - if (m_invokeCountWindow > 0) { - stats.invoke_avg_ms = (float)std::chrono::duration_cast(m_invokeTotalWindow).count() / (static_cast(m_invokeCountWindow) * 1000.0f); - } else { - stats.invoke_avg_ms = 0.0f; - } - - stats.invoke_max_window_ms = (float)std::chrono::duration_cast(m_invokeMaxWindow).count() / 1000.0f; - stats.invoke_max_all_ms = (float)std::chrono::duration_cast(m_invokeMaxAll).count() / 1000.0f; - - stats.dispatch_count = m_dispatchCountAll; - - // Reset windowed stats - m_queueDepthMaxWindow = 0; - m_latencyTotalWindow = Duration(0); - m_latencyCountWindow = 0; - m_latencyMaxWindow = Duration(0); - - m_invokeTotalWindow = Duration(0); - m_invokeCountWindow = 0; - m_invokeMaxWindow = Duration(0); - - k_mutex_unlock(&m_statMutex); - return stats; -} -#endif - -} // namespace dmq::os - -#endif // DMQ_THREAD_ZEPHYR diff --git a/DelegateMQ/port/os/zephyr/ZephyrThread.h b/DelegateMQ/port/os/zephyr/ZephyrThread.h deleted file mode 100644 index bcc9d6d..0000000 --- a/DelegateMQ/port/os/zephyr/ZephyrThread.h +++ /dev/null @@ -1,298 +0,0 @@ -#ifndef _THREAD_ZEPHYR_H -#define _THREAD_ZEPHYR_H - -/// @file ZephyrThread.h -/// @brief Zephyr RTOS implementation of the DelegateMQ IThread interface. -/// -/// @note This implementation is a basic port. For reference, the stdlib and win32 -/// implementations provide additional features: -/// 1. Synchronized Startup: CreateThread() blocks until the worker thread is ready. -/// -/// **Key Features:** -/// * **Task Integration:** Wraps `k_thread_create` to establish a dedicated worker loop. -/// * **FullPolicy Support:** Configurable back-pressure (DROP or TIMEOUT) when the -/// message queue is full. -/// * **Priority Support:** Normal and High priorities. Since Zephyr's `k_msgq` has -/// no native "send to front", `ZephyrDelegateQueue` keeps two `k_msgq` instances -/// (mirroring the desktop two-deque model) and always drains the high-priority -/// one first -- see ZephyrDelegateQueue.h for the tradeoffs this implies. -/// * **Queue-Based Dispatch:** Uses `ZephyrDelegateQueue` (a thin RAII wrapper -/// around a pair of `k_msgq` instances) to receive and process incoming -/// delegate messages in a thread-safe manner. -/// * **Watchdog Integration:** Optional heartbeat mechanism detects stalled or deadlocked -/// threads. Enable by passing a timeout to CreateThread(). Requires -/// Thread::WatchdogCheckAll() to be called periodically from a context that can preempt -/// watched threads -- the highest-priority task in the system, not an ISR. -/// * **Start Gate:** Optional `SetStartGate(StartGate*)`, called before `CreateThread()`, -/// holds the thread ready but processing no messages, at any priority, until -/// `StartGate::Open()` releases every thread sharing the gate at once. - -#include "delegate/IThread.h" -#include "delegate/UnicastDelegate.h" -#include "port/os/common/ThreadMsg.h" -#include "port/os/common/StartGate.h" -#include "ZephyrDelegateQueue.h" -#include "extras/util/Timer.h" -#include -#include -#include -#include -#include - -namespace dmq::os { - -/// @brief Policy applied when the thread message queue is full. See dmq::FullPolicy -/// in DelegateOpt.h for the canonical definition, shared by every dmq::os::Thread port. -using FullPolicy = dmq::FullPolicy; - -/// @brief What ExitThread() does with queued messages. See dmq::ExitPolicy in DelegateOpt.h. -using ExitPolicy = dmq::ExitPolicy; - -class ZephyrThread : public dmq::IThread -{ -public: -#if defined(DMQ_DATABUS_TOOLS) - /// @brief Statistics captured for thread monitoring. - struct ThreadStats { - dmq::xstring cpu_name; - dmq::xstring thread_name; - size_t queue_depth; // Current depth - size_t queue_depth_max_window;// Max depth since last snapshot - size_t queue_depth_max_all; // All-time max depth - size_t queue_size_limit; // Max allowed - float latency_avg_ms; // Avg wait in window - float latency_max_window_ms; // Max wait since last snapshot - float latency_max_all_ms; // All-time max wait - float invoke_avg_ms; // Avg execution in window - float invoke_max_window_ms; // Max execution since last snapshot - float invoke_max_all_ms; // All-time max execution - uint64_t dispatch_count; // Total dispatches (all-time) - }; -#endif - - /// Default queue size if 0 is passed - static const size_t DEFAULT_QUEUE_SIZE = dmq::DEFAULT_QUEUE_SIZE; - - /// Constructor - /// @param threadName Name for the Zephyr thread - /// @param maxQueueSize Max number of messages in queue (0 = Default dmq::DEFAULT_QUEUE_SIZE) - /// @param fullPolicy Action when queue is full: FAULT (default), DROP, or TIMEOUT. - /// @param dispatchTimeout Duration to wait before giving up when policy is TIMEOUT. - /// @param cpuName Optional CPU/Core name grouping for monitoring tools. - ZephyrThread(const char* threadName, size_t maxQueueSize = 0, FullPolicy fullPolicy = FullPolicy::FAULT, - dmq::Duration dispatchTimeout = dmq::DEFAULT_DISPATCH_TIMEOUT, const char* cpuName = ""); - - ZephyrThread(const std::string& threadName, size_t maxQueueSize = 0, FullPolicy fullPolicy = FullPolicy::FAULT, - dmq::Duration dispatchTimeout = dmq::DEFAULT_DISPATCH_TIMEOUT, const std::string& cpuName = "") - : ZephyrThread(threadName.c_str(), maxQueueSize, fullPolicy, dispatchTimeout, cpuName.c_str()) {} - - ~ZephyrThread(); - - /// Called once to create the worker thread. If watchdogTimeout value - /// provided, the maximum watchdog interval is used. Otherwise no watchdog. - /// @param[in] watchdogTimeout - optional watchdog timeout. - /// @return TRUE if thread is created. FALSE otherwise. - bool CreateThread(std::optional watchdogTimeout = std::nullopt); - - /// Shut down the worker thread. - /// @param[in] policy - DRAIN (default) invokes every message queued before this - /// call first; DISCARD invokes only the message already running and cancels - /// the rest (see dmq::ExitPolicy). Called from the thread's own message - /// handler (a self-exit), queued messages are always discarded. - void ExitThread(ExitPolicy policy = ExitPolicy::DRAIN); - - // Note: k_tid_t is a struct k_thread* in Zephyr - k_tid_t GetThreadId(); - static k_tid_t GetCurrentThreadId(); - - /// Returns true if the calling thread is this thread - virtual bool IsCurrentThread() override; - - /// Set the Zephyr Priority. - /// Can be called before or after CreateThread(). - void SetThreadPriority(int priority); - - dmq::xstring GetThreadName() { return THREAD_NAME; } - - /// Get current queue size - size_t GetQueueSize(); - - /// Sleep for a duration. - /// @param[in] timeout - the duration to sleep. - static void Sleep(dmq::Duration timeout); - - virtual bool DispatchDelegate(std::shared_ptr msg) override; - - /// @brief Register a handler invoked when DispatchDelegate() drops a message: - /// under FullPolicy::DROP (queue full, discarded immediately) or - /// FullPolicy::TIMEOUT (queue stayed full for dispatchTimeout, discarded). - /// Optional; unset by default. Called synchronously on the calling (producer) - /// thread, with the queue depth at the time of the drop. - void SetDroppedHandler(const dmq::UnicastDelegate& handler) { m_droppedHandler = handler; } - void SetDroppedHandler(dmq::UnicastDelegate&& handler) { m_droppedHandler = std::move(handler); } - - /// @brief Register a handler invoked on the worker thread before it processes - /// any message. Use it for per-thread setup (COM, a language runtime attach, - /// thread-local state, affinity). CreateThread() returns only after it completes. - /// @details Must be called while the thread is not running (before CreateThread(), - /// or after ExitThread()); calling it on a running thread faults. It runs again - /// on each CreateThread(). Messages dispatched meanwhile are queued, not lost. - void SetStartHandler(const dmq::UnicastDelegate& handler) { DMQ_ASSERT_TRUE(!m_stackMemory); m_startHandler = handler; } - void SetStartHandler(dmq::UnicastDelegate&& handler) { DMQ_ASSERT_TRUE(!m_stackMemory); m_startHandler = std::move(handler); } - - /// @brief Optional: hold this thread at `gate` once it is created, until - /// `gate->Open()`. Pass nullptr (the default) to start at once. - /// @details CreateThread() still runs the start handler and returns when the - /// thread is ready; the thread then processes nothing, at any priority, until - /// the gate opens. Use one gate for a group of threads so they all start - /// together after setup. See port/os/common/StartGate.h. Must be called while - /// the thread is not running; calling it on a running thread faults. - void SetStartGate(StartGate* gate) { DMQ_ASSERT_TRUE(!m_stackMemory); m_startGate.Set(gate); } - - /// @brief Register a handler invoked on the worker thread after it processes - /// its last message, as the thread exits. Use it to undo SetStartHandler() setup. - /// @details Must be called while the thread is not running; calling it on a - /// running thread faults. The handler is copied when the thread starts. - /// ExitThread() from another thread returns after it completes. If the thread - /// exits itself (ExitThread() from a handler on this thread), it runs after the - /// owning ZephyrThread may already be destroyed, so it must not touch that object. - void SetExitHandler(const dmq::UnicastDelegate& handler) { DMQ_ASSERT_TRUE(!m_stackMemory); m_exitHandler = handler; } - void SetExitHandler(dmq::UnicastDelegate&& handler) { DMQ_ASSERT_TRUE(!m_stackMemory); m_exitHandler = std::move(handler); } - - /// @brief Register a handler invoked on the worker thread when its queue has - /// been empty for `interval`, then again every `interval` while it stays empty. - /// Any message processed restarts the countdown. Use it for background work that - /// should yield to messages: polling, housekeeping, entering low power. - /// @details Must be called while the thread is not running; calling it on a - /// running thread faults. The handler and interval are copied when the thread - /// starts. Not called once ExitThread() has been requested. - /// @param[in] handler - the idle handler, or an empty delegate to disable. - /// @param[in] interval - quiet time before each call. Must be greater than zero. - /// Defaults to dmq::THREAD_IDLE_INTERVAL (DMQ_THREAD_IDLE_INTERVAL). - void SetIdleHandler(const dmq::UnicastDelegate& handler, dmq::Duration interval = dmq::THREAD_IDLE_INTERVAL) - { - DMQ_ASSERT_TRUE(!m_stackMemory); - DMQ_ASSERT_TRUE(interval > dmq::Duration::zero()); - m_idleHandler = handler; - m_idleInterval = interval; - } - void SetIdleHandler(dmq::UnicastDelegate&& handler, dmq::Duration interval = dmq::THREAD_IDLE_INTERVAL) - { - DMQ_ASSERT_TRUE(!m_stackMemory); - DMQ_ASSERT_TRUE(interval > dmq::Duration::zero()); - m_idleHandler = std::move(handler); - m_idleInterval = interval; - } - - /// @brief Manually update the watchdog alive timestamp. - /// @details The Run() loop refreshes the timestamp automatically on every iteration. - /// Call this from inside long-running message handlers to prevent a false watchdog - /// alarm when a handler legitimately takes longer than watchdogTimeout. - void ThreadCheck(); - - /// @brief Static method to check all registered threads for watchdog expiration. - static void WatchdogCheckAll(); - -#if defined(DMQ_DATABUS_TOOLS) - /// @brief Capture and reset windowed statistics. - ThreadStats SnapshotStats(); -#endif - -private: - ZephyrThread(const ZephyrThread&) = delete; - ZephyrThread& operator=(const ZephyrThread&) = delete; - - // ZephyrThread entry point - static void Process(void* p1, void* p2, void* p3); - void Run(); - - /// Check watchdog is expired. Called by WatchdogCheckAll(). - void WatchdogCheck(); - - /// Get registry head using the "Immortal" Pattern - static ZephyrThread*& GetWatchdogHead(); - - /// Get registry lock using the "Immortal" Pattern - static dmq::RecursiveMutex& GetWatchdogLock(); - - const dmq::xstring THREAD_NAME; - const dmq::xstring CPU_NAME; - const size_t m_queueSize; - const FullPolicy FULL_POLICY; - const dmq::Duration m_dispatchTimeout; - int m_priority; - - // Zephyr Kernel Objects - struct k_thread m_thread; - ZephyrDelegateQueue m_queue; - - // Optional handler invoked when a message is dropped (FullPolicy::DROP or TIMEOUT) - dmq::UnicastDelegate m_droppedHandler; - - // Optional handlers invoked on the worker thread at start, exit and when idle - dmq::UnicastDelegate m_startHandler; - dmq::UnicastDelegate m_exitHandler; - dmq::UnicastDelegate m_idleHandler; - dmq::Duration m_idleInterval = dmq::Duration::zero(); - struct k_sem m_exitSem; // Semaphore to signal thread completion - struct k_sem m_startSem; // Given by Run() once the start handler has run - bool m_startSync = false; // CreateThread() waits for the start handler (called from a thread) - std::atomic m_exit = false; - - // Optional start gate (SetStartGate()): its state, and whether the thread is - // held at it (the watchdog doesn't report a thread waiting by design) - StartGateClient m_startGate; - std::atomic m_discard = false; // ExitPolicy::DISCARD: cancel queued messages instead of invoking - bool* m_selfExitPtr = nullptr; - - // Set when the thread terminates itself (ExitThread() called from within - // its own dispatched callback). A self-exiting thread cannot join or free - // its own stack, so a later ExitThread() call (typically from ~ZephyrThread(), - // made from a different thread context) checks this to skip the - // message-send/semaphore handshake and go straight to the k_thread_join() - // + stack-free cleanup instead. - std::atomic m_selfExited = false; - - // Custom deleter for Zephyr kernel memory (wraps k_free) - using ZephyrDeleter = void(*)(void*); - - // Dynamically allocated stack, managed by unique_ptr but allocated via - // k_aligned_alloc and freed via k_free. Also doubles as the - // "is thread created" sentinel checked throughout this class. - std::unique_ptr m_stackMemory{nullptr, k_free}; - - // Stack size in bytes - static const size_t STACK_SIZE = dmq::ZEPHYR_STACK_BYTES; // DMQ_ZEPHYR_STACK_BYTES - - // Watchdog related members - std::atomic m_lastAliveTime{dmq::TimePoint()}; - std::atomic m_watchdogTimeout{dmq::Duration(0)}; - ZephyrThread* m_watchdogNext = nullptr; - -#if defined(DMQ_DATABUS_TOOLS) - struct k_mutex m_statMutex; // Mutex to protect statistics - // Monitoring statistics members - size_t m_queueDepthMaxWindow = 0; - size_t m_queueDepthMaxAll = 0; - - dmq::Duration m_latencyTotalWindow = dmq::Duration(0); - uint32_t m_latencyCountWindow = 0; - dmq::Duration m_latencyMaxWindow = dmq::Duration(0); - dmq::Duration m_latencyMaxAll = dmq::Duration(0); - - dmq::Duration m_invokeTotalWindow = dmq::Duration(0); - uint32_t m_invokeCountWindow = 0; - dmq::Duration m_invokeMaxWindow = dmq::Duration(0); - dmq::Duration m_invokeMaxAll = dmq::Duration(0); - - uint64_t m_dispatchCountAll = 0; -#endif -}; - -/// @brief Backward-compatible name: existing code referencing dmq::os::Thread -/// keeps compiling unchanged against the Zephyr port. -using Thread = ZephyrThread; - -} // namespace dmq::os - -#endif // _THREAD_ZEPHYR_H diff --git a/DelegateMQ/port/serialize/README.md b/DelegateMQ/port/serialize/README.md deleted file mode 100644 index 13af0f8..0000000 --- a/DelegateMQ/port/serialize/README.md +++ /dev/null @@ -1,42 +0,0 @@ -# Serializers (DelegateMQ Abstraction Layer) - -This directory contains the serializer part of the **DelegateMQ Abstraction Layer**: the `ISerializer` adapters responsible for marshaling function arguments into binary or text formats for remote transmission. - -DelegateMQ is designed to be **serialization-agnostic**. You can choose the serializer that best fits your project's performance, size, or compatibility requirements. - -## Supported Serializers - -The following subdirectories contain adapters for popular C++ serialization libraries: - -* **`serialize`**: The built-in, header-only **MessageSerialize** library. - * *Best for:* Zero dependencies, simple projects, and built-in STL container support. - * *Features:* Endianness handling, versioning, and no external requirements. -* **`msgpack`**: Adapter for **MessagePack** (msgpack-c). - * *Best for:* High-performance binary serialization and compact data size. -* **`rapidjson`**: Adapter for **RapidJSON**. - * *Best for:* Human-readable JSON output and web API integration. -* **`cereal`**: Adapter for **Cereal**. - * *Best for:* Modern C++11/17 features and robust object serialization. -* **`bitsery`**: Adapter for **Bitsery**. - * *Best for:* Ultra-fast, zero-buffer serialization for real-time applications. - -Alternatively, you can implement your own adapter by inheriting from the `dmq::ISerializer` interface and injecting it into your `dmq::DelegateRemote` instance. - -## Embedded Tradeoffs - -Choosing a serializer for an embedded target involves constraints that do not apply on Linux or Windows: limited heap, no or restricted exception support, code-size budgets, and endianness differences between the MCU and any host it communicates with. - -| Serializer | Embedded suitability | Notes | -|---|---|---| -| `serialize` | Good | Zero external dependencies, automatic endianness handling, builds without exceptions (errors are reported through the stream state). Structs must inherit `serialize::I` and implement `read()`/`write()`. Slightly larger wire format due to size-prefix versioning. | -| `bitsery` | Best for tight constraints | Header-only, designed for real-time/embedded use, produces the smallest payloads of all supported options. Plain structs work with a `serialize()` annotation — no base class required. Endianness is configured at the adapter level rather than handled automatically, so cross-architecture communication requires explicit configuration. | -| `msgpack` | Linux/Windows only | The msgpack-c library allocates dynamically (`msgpack::sbuffer`, `std::vector`) and carries an external dependency. These characteristics are manageable on a host but are a significant concern on a MCU with a constrained FreeRTOS heap. | -| `cereal` | Poor | Heavy template machinery and reliance on `` and `` increases code size considerably. Rarely justified on a Cortex-M or similar resource-constrained target. | -| `rapidjson` | Poor | JSON payload overhead (field names, brackets, quotes) is typically 3–10× larger than an equivalent binary format. Appropriate when a host-side consumer needs human-readable output or REST interoperability, not for high-rate sensor data loops on an MCU. | - -### Guidance - -- **Default embedded choice**: `serialize` — works out of the box with no external dependencies and handles the endianness problem automatically, which matters when an MCU (commonly big-endian capable) communicates with an x86 host. -- **Upgrade path**: `bitsery` — if wire payload size or serialization throughput is a priority on real hardware, bitsery is the natural next step. Only the struct annotations in the message definitions change; `dmq::databus::DataBus` API calls are unaffected. -- **Host-side only**: `msgpack`, `cereal`, and `rapidjson` are appropriate for Linux/Windows nodes in a mixed system but should not be the embedded node's serializer on a resource-constrained target. -- **Message field types**: on the MCU, prefer `std::array`, `xlist`/`xmap`/`xset` and `xstring` over `std::vector`. See [Choosing Containers on Embedded Targets](serialize/README.md#choosing-containers-on-embedded-targets). diff --git a/DelegateMQ/port/serialize/bitsery/BitserySerializer.h b/DelegateMQ/port/serialize/bitsery/BitserySerializer.h deleted file mode 100644 index 472d7c2..0000000 --- a/DelegateMQ/port/serialize/bitsery/BitserySerializer.h +++ /dev/null @@ -1,84 +0,0 @@ -#ifndef DMQ_BITSERY_SERIALIZER_H -#define DMQ_BITSERY_SERIALIZER_H - -/// @file BitserySerializer.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// Serialize callable argument data using Bitsery for transport -/// to a remote. Bitsery provides fast, compact binary serialization. - -#include "delegate/ISerializer.h" - -#if defined(DMQ_SERIALIZE_BITSERY) - -// Core Bitsery -#include -#include - -// Common Traits (Include these so standard types work out of the box) -#include -#include -#include - -#include -#include -#include - -namespace dmq::serialization::bitsery { - -template -struct Serializer; // Not defined - -template -class Serializer : public dmq::ISerializer -{ -public: - // Bitsery Adapters for std::ostream / std::istream - using OutputAdapter = ::bitsery::OutputStreamAdapter; - using InputAdapter = ::bitsery::InputStreamAdapter; - - // No try/catch here: this adapter must build without exceptions (-fno-exceptions), - // the common embedded setting. Failures are reported through the stream state, - // which DelegateRemote checks (ERR_DESERIALIZE / ERR_STREAM_NOT_GOOD). - virtual std::ostream& Write(std::ostream& os, const Args&... args) override { - // Reset stream position. - os.seekp(0, std::ios::beg); - - // Clear stringstreams explicitly to avoid appending new data to old data. - // DelegateMQ often reuses the stream object. - if (auto* ss = dynamic_cast(&os)) { - ss->str(""); - } - - // Construct the adapter properly passing the stream - ::bitsery::Serializer writer{ OutputAdapter{os} }; - - // Serialize each argument using C++17 fold expression - (writer.object(args), ...); - - // Ensure buffer is flushed to the stream - writer.adapter().flush(); - return os; - } - - virtual std::istream& Read(std::istream& is, Args&... args) override { - // Construct the adapter properly passing the stream - ::bitsery::Deserializer reader{ InputAdapter{is} }; - - // Deserialize each argument using fold expression - (reader.object(args), ...); - - // A truncated or malformed message: fail the stream. - if (reader.adapter().error() != ::bitsery::ReaderError::NoError) { - is.setstate(std::ios::failbit); - } - return is; - } -}; - -} // namespace dmq::serialization::bitsery - -#endif // DMQ_SERIALIZE_BITSERY - -#endif // DMQ_BITSERY_SERIALIZER_H diff --git a/DelegateMQ/port/serialize/cereal/CerealSerializer.h b/DelegateMQ/port/serialize/cereal/CerealSerializer.h deleted file mode 100644 index efcd304..0000000 --- a/DelegateMQ/port/serialize/cereal/CerealSerializer.h +++ /dev/null @@ -1,53 +0,0 @@ -#ifndef DMQ_CEREAL_SERIALIZER_H -#define DMQ_CEREAL_SERIALIZER_H - -/// @file CerealSerializer.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// Serialize callable argument data using Cereal library for transport -/// to a remote. Endianness handled internally by Cereal. -/// -/// Cereal reports errors by throwing; the exception propagates to -/// DelegateRemote, which reports ERR_SERIALIZE / ERR_DESERIALIZE_EXCEPTION. - -#include -#include -#include -#include "delegate/ISerializer.h" -#include -#include -#include - -namespace dmq::serialization::cereal { - -template -struct Serializer; // Not defined - -// Serialize all target function argument data using Cereal -template -class Serializer : public dmq::ISerializer -{ -public: - // Write arguments to a stream - virtual std::ostream& Write(std::ostream& os, const Args&... args) override { - os.seekp(0); - if (auto* ss = dynamic_cast(&os)) - ss->str(""); - ::cereal::BinaryOutputArchive archive(os); - (archive(args), ...); // C++17 fold expression to serialize each argument - return os; - } - - // Read arguments from a stream - virtual std::istream& Read(std::istream& is, Args&... args) override { - ::cereal::BinaryInputArchive archive(is); - (archive(args), ...); // C++17 fold expression to deserialize - return is; - } -}; - -} // namespace dmq::serialization::cereal - - -#endif // DMQ_CEREAL_SERIALIZER_H diff --git a/DelegateMQ/port/serialize/msgpack/MsgpackSerializer.h b/DelegateMQ/port/serialize/msgpack/MsgpackSerializer.h deleted file mode 100644 index 7485155..0000000 --- a/DelegateMQ/port/serialize/msgpack/MsgpackSerializer.h +++ /dev/null @@ -1,92 +0,0 @@ -#ifndef DMQ_MSGPACK_SERIALIZER_H -#define DMQ_MSGPACK_SERIALIZER_H - -/// @file MsgpackSerializer.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// Serialize callable argument data using MessagePack library for transport -/// to a remote. Endianness correctly handled by MessagePack library. -/// -/// MessagePack reports errors by throwing (e.g. msgpack::type_error); the -/// exception propagates to DelegateRemote, which reports ERR_SERIALIZE / -/// ERR_DESERIALIZE_EXCEPTION. - -#include "msgpack.hpp" -#include "delegate/ISerializer.h" -#include -#include -#include // Needed for dynamic_cast check -#include -#include - -namespace dmq::serialization::msgpack { - -// make_serialized serializes each remote function argument -template -void make_serialized(::msgpack::sbuffer& buffer, Args&&... args) { - (::msgpack::pack(buffer, args), ...); // C++17 fold expression to serialize -} - -template -struct Serializer; // Not defined - -// Serialize all target function argument data using MessagePack library -template -class Serializer : public dmq::ISerializer -{ -public: - // Write arguments to a stream - virtual std::ostream& Write(std::ostream& os, const Args&... args) override { - // Reset stream position. DelegateMQ reuses the stream instance. - // If we don't reset, we append new data to old data, sending [Old][New] - // and the receiver will always deserialize [Old]. - os.seekp(0, std::ios::beg); - - // Optimization: If it's a stringstream, clear it completely to avoid - // sending "tail garbage" if the new packet is smaller than the previous one. - // (Note: Even with garbage tail, msgpack works because it stops reading - // after the valid object, but clearing saves network bandwidth). - if (auto* ss = dynamic_cast(&os)) { - ss->str(""); - } - - ::msgpack::sbuffer buffer; - make_serialized(buffer, args...); - os.write(buffer.data(), buffer.size()); - return os; - } - - // Read arguments from a stream - virtual std::istream& Read(std::istream& is, Args&... args) override { - // Read entire stream into memory buffer - std::vector buffer_data((std::istreambuf_iterator(is)), std::istreambuf_iterator()); - - // No data for the arguments: fail, so the caller reports a - // deserialize error instead of invoking with default values. - if (buffer_data.empty() && sizeof...(Args) > 0) { - is.setstate(std::ios::failbit); - return is; - } - - size_t offset = 0; - - // Helper lambda to unpack one argument at a time from the buffer - auto unpack_one = [&](auto& arg) { - // msgpack::unpack parses one object and updates 'offset' to point to the next byte - ::msgpack::object_handle oh = ::msgpack::unpack(buffer_data.data(), buffer_data.size(), offset); - - // Convert msgpack object to specific C++ type - arg = oh.get().as>(); - }; - - // Use C++17 fold expression to call unpack_one for each argument in 'args' - (unpack_one(args), ...); - return is; - } -}; - -} // namespace dmq::serialization::msgpack - - -#endif // DMQ_MSGPACK_SERIALIZER_H diff --git a/DelegateMQ/port/serialize/rapidjson/RapidJsonSerializer.h b/DelegateMQ/port/serialize/rapidjson/RapidJsonSerializer.h deleted file mode 100644 index a2dab15..0000000 --- a/DelegateMQ/port/serialize/rapidjson/RapidJsonSerializer.h +++ /dev/null @@ -1,88 +0,0 @@ -#ifndef DMQ_RAPIDJSON_SERIALIZER_H -#define DMQ_RAPIDJSON_SERIALIZER_H - -/// @file RapidJsonSerializer.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// Serialize callable argument data using RapidJSON for transport -/// to a remote. JSON is text, so endianness doesn't apply. -/// -/// Errors are reported through the stream state (and any exception from an -/// argument's Write()/Read() propagates); DelegateRemote reports them as -/// ERR_SERIALIZE / ERR_DESERIALIZE. - -#include "delegate/ISerializer.h" -#include -#include -#include "rapidjson/document.h" -#include "rapidjson/prettywriter.h" -#include - -namespace dmq::serialization::rapidjson { - -template -struct Serializer; // Not defined - -// Serialize all target function argument data using serialize class -template -class Serializer : public dmq::ISerializer -{ -public: - // Write arguments to a stream - virtual std::ostream& Write(std::ostream& os, const Args&... args) override { - os.seekp(0, std::ios::beg); - // Empty a reused stream: transports send the whole buffer, so bytes left - // over from a longer previous message would follow the JSON and fail - // the receiver's parse. - if (auto* ss = dynamic_cast(&os)) - ss->str(""); - ::rapidjson::StringBuffer sb; - ::rapidjson::PrettyWriter<::rapidjson::StringBuffer> writer(sb); - (args.Write(writer, os), ...); // C++17 fold expression to write each argument - if (writer.IsComplete()) - os << sb.GetString(); - else - os.setstate(std::ios::failbit); - return os; - } - - // Read arguments from a stream - virtual std::istream& Read(std::istream& is, Args&... args) override { - // Get stream length - std::streampos current_pos = is.tellg(); - is.seekg(0, std::ios::end); - std::streampos end_pos = is.tellg(); - is.seekg(current_pos, std::ios::beg); - - if (end_pos < 0 || !is.good()) - { - is.setstate(std::ios::failbit); - return is; - } - - std::streamsize length = static_cast(end_pos); - - // Allocate storage buffer (null terminator appended for RapidJSON) - std::vector buf(static_cast(length) + 1); - is.rdbuf()->sgetn(buf.data(), length); - buf[length] = 0; // null terminate incoming data - - // Parse JSON; a parse error fails the stream (ERR_DESERIALIZE) - ::rapidjson::Document doc; - doc.Parse(buf.data()); - if (doc.HasParseError()) - { - is.setstate(std::ios::failbit); - return is; - } - - (args.Read(doc, is), ...); // C++17 fold expression to read each argument - return is; - } -}; - -} // namespace dmq::serialization::rapidjson - - -#endif // DMQ_RAPIDJSON_SERIALIZER_H diff --git a/DelegateMQ/port/serialize/serialize/DmqSerializer.h b/DelegateMQ/port/serialize/serialize/DmqSerializer.h deleted file mode 100644 index 6dfcbac..0000000 --- a/DelegateMQ/port/serialize/serialize/DmqSerializer.h +++ /dev/null @@ -1,51 +0,0 @@ -#ifndef DMQ_DMQ_SERIALIZER_H -#define DMQ_DMQ_SERIALIZER_H - -/// @file DmqSerializer.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// Serialize callable argument data using serialize class for transport -/// to a remote. Endianness correctly handled by serialize class. -/// -/// Errors are reported through the stream state (and any exception from a -/// user type's read()/write() propagates); DelegateRemote reports them as -/// ERR_SERIALIZE / ERR_DESERIALIZE. No try/catch here, per the library rules. - -#include "delegate/ISerializer.h" -#include -#include -#include "msg_serialize.h" - -namespace dmq::serialization::serializer { - -template -struct Serializer; // Not defined - -// Serialize all target function argument data using serialize class -template -class Serializer : public dmq::ISerializer -{ -public: - // Write arguments to a stream - virtual std::ostream& Write(std::ostream& os, const Args&... args) override { - os.seekp(0, std::ios::beg); - if (auto* ss = dynamic_cast(&os)) - ss->str(""); - ::serialize ser; - (ser.write(os, args), ...); // C++17 fold expression to serialize each argument - return os; - } - - // Read arguments from a stream - virtual std::istream& Read(std::istream& is, Args&... args) override { - ::serialize ser; - (ser.read(is, args), ...); // C++17 fold expression to unserialize each argument - return is; - } -}; - -} // namespace dmq::serialization::serializer - - -#endif // DMQ_DMQ_SERIALIZER_H diff --git a/DelegateMQ/port/serialize/serialize/README.md b/DelegateMQ/port/serialize/serialize/README.md deleted file mode 100644 index 890fa73..0000000 --- a/DelegateMQ/port/serialize/serialize/README.md +++ /dev/null @@ -1,121 +0,0 @@ -# MessageSerialize - -A robust, header-only C++ binary serialization library designed for DelegateMQ. It provides a simple yet powerful framework for marshaling C++ objects, primitives, and STL containers into binary streams. - -## Features - -- **Header-Only**: No external dependencies beyond the C++ Standard Library. -- **Endianness Aware**: Uses a little-endian wire format. Automatically handles byte-swapping on big-endian hosts. -- **STL Support**: Native support for `std::vector`, `std::array`, `std::list`, `std::map`, `std::set`, `std::string`, and `std::wstring`, including nested containers (e.g. `std::vector>`, `std::map>`). -- **Custom Allocators**: Fully compatible with custom allocators, including DelegateMQ's `xstring`, `xlist`, `xmap` and `xset`. Declare message fields with these types and `DMQ_ALLOCATOR` switches them between the fixed-block allocator and the heap, with no serializer changes. -- **Versioning**: Supports forward and backward compatibility for user-defined objects. -- **Type Safety**: Uses compile-time checks to ensure only supported types are serialized. -- **Pointer Support**: Supports serializing containers of pointers with automatic memory allocation during deserialization. -- **Stream Verification**: Includes runtime and compile-time checks (via `is_seekable` trait) to ensure streams support the required seeking operations. - -## Stream Requirements - -- **Seekable**: The library requires seekable streams (e.g., `std::stringstream`, `std::fstream`) to handle object versioning and size backfilling. Non-seekable streams (like sockets or `std::cout`) will trigger a runtime error. -- **Binary Mode**: Always open files or streams in **binary mode** (`std::ios::binary`). Failure to do so may lead to data corruption due to automatic newline translations (especially on Windows). - -## Limits - -Set in `DelegateMQConfig.h` (defaults in `DelegateMQConfig_Default.h`). They apply on write and on read, so a received message can't make the receiver allocate more than this. Exceeding one fails the stream with the error shown. - -| Setting | Default | Limits | Error | -|---|---|---|---| -| `DMQ_SERIALIZE_MAX_STRING_SIZE` | 1024 | String length in bytes, not counting a terminator (none is sent); at most 65535 | `STRING_TOO_LONG` | -| `DMQ_SERIALIZE_MAX_CONTAINER_SIZE` | 64 | Elements in a vector, list, set or map; at most 65535 | `CONTAINER_TOO_MANY` | -| `DMQ_SERIALIZE_MAX_NESTING` | 5 | Depth of `serialize::I` objects nested inside each other | `NESTING_TOO_DEEP` | - -## Basic Usage - -### Serializing Primitives - -```cpp -#include "msg_serialize.h" -#include - -serialize ms; -int value = 123; -std::stringstream ss; - -// Write to stream -ms.write(ss, value); - -// Read from stream -int outValue; -ms.read(ss, outValue); -``` - -### Custom Serializable Objects - -User-defined types must inherit from `serialize::I` and implement the `read()` and `write()` methods. - -```cpp -struct MyData : public serialize::I { - int id = 0; - std::string name; - - // Serialize object to stream - std::ostream& write(serialize& ms, std::ostream& os) const override { - ms.write(os, id); - ms.write(os, name); - return os; - } - - // Deserialize object from stream - std::istream& read(serialize& ms, std::istream& is) override { - ms.read(is, id); - ms.read(is, name); - return is; - } -}; -``` - -### STL Containers and Custom Allocators - -The library handles standard containers and those using custom allocators (like fixed-block pools) automatically. - -```cpp -xlist myList = {1, 2, 3}; -std::stringstream ss; -serialize ms; - -ms.write(ss, myList); - -xlist outList; -ms.read(ss, outList); -``` - -### Choosing Containers on Embedded Targets - -What a message type's fields allocate matters more on an MCU than how they're serialized. With `DMQ_ALLOCATOR`, memory comes from fixed-block pools, one pool per power-of-two block size, and blocks are kept for reuse rather than returned to the heap. - -| Field type | Allocation | Embedded use | -|---|---|---| -| `std::array`, `char[N]` | None | **Best.** Fixed size, no heap and no pool. | -| `xlist`, `xmap`, `xset` | One same-size node per element, from one fixed-block pool | **Good.** Freed nodes are reused exactly. | -| `xstring` | One block sized to the string, from a fixed-block pool | **Good**, bounded by `DMQ_SERIALIZE_MAX_STRING_SIZE`. | -| `std::vector` | One contiguous block that is reallocated larger as it grows | **Host-side only.** Each growth step needs a new, larger block size, so a vector touches several pools and each keeps its blocks. In static-pool mode the largest block is 4096 bytes. | - -- On the MCU, declare message fields with `std::array`, `xlist`/`xmap`/`xset` and `xstring`. On desktop or gateway nodes, `std::vector` is fine. -- `std::array` deliberately uses the vector type marker rather than a separate array type, so its bytes match a vector's (marker, count, elements) and one node can use `std::vector` while the other uses `std::array` for the same field. The count on the wire catches a mismatch: reading into a `std::array` fails with `INVALID_INPUT` unless exactly `N` elements arrive, and a list, set or map fails with `TYPE_MISMATCH`. As with vectors, the marker identifies the container kind, not the element type. -- Reading into a `std::vector` reserves the received count first, so it makes one allocation of the final size rather than regrowing per element. - -## Advanced Features - -### Versioning & Compatibility - -When serializing objects derived from `serialize::I`, the library records the object size in the stream. -- **Forward Compatibility**: If a receiver gets a newer (larger) version of an object, it reads what it knows and safely skips the remaining bytes. -- **Backward Compatibility**: If a receiver gets an older (smaller) version, it reads the available data and leaves the remaining members at their default values. - -### Pointer Containers - -When serializing `std::vector` or `std::list`, the library: -1. Writes a boolean flag for each element indicating if it's null. -2. For non-null elements, it serializes the pointed-to object. -3. During deserialization, it calls `new T` to recreate the objects. - -*Note: The caller is responsible for managing the memory of objects created during pointer container deserialization.* diff --git a/DelegateMQ/port/serialize/serialize/msg_serialize.h b/DelegateMQ/port/serialize/serialize/msg_serialize.h deleted file mode 100644 index 8d2c005..0000000 --- a/DelegateMQ/port/serialize/serialize/msg_serialize.h +++ /dev/null @@ -1,1874 +0,0 @@ -/// @file msg_serialize.h -/// @see https://github.com/endurodave/MessageSerialize -/// @author David Lafreniere -/// @date 2024 -/// -/// @brief A robust, header-only C++ binary serialization library. -/// -/// @details -/// This library provides a framework for marshaling C++ objects, primitives, and STL -/// containers into binary streams (std::ostream) and demarshaling them back (std::istream). -/// It is designed for network communication and data persistence where binary compatibility -/// and protocol evolution are required. -/// -/// **CRITICAL REQUIREMENTS:** -/// * **Binary Mode:** Streams MUST be opened in binary mode (std::ios::binary). Text-mode -/// streams will corrupt binary data (e.g., newline conversion on Windows). -/// * **Seekable Streams:** User-defined objects (inheriting from `serialize::I`) require -/// seekable streams (e.g., `std::stringstream`, `std::fstream`) to backfill object sizes. -/// Non-seekable streams (like `std::cout` or sockets) will trigger a `NON_SEEKABLE_STREAM` error. -/// -/// **Key Features:** -/// * **Single Header:** A self-contained, header-only library with no external dependencies -/// beyond the standard C++ library (STL). -/// * **Endianness Handling:** Wire format is little-endian. Automatic byte-swapping on -/// big-endian hosts ensures compatibility between mixed-endian architectures. -/// * **STL Container Support:** Native serialization for std::vector, std::list, std::map, -/// std::set, std::string, and std::wstring. -/// * **Protocol Versioning:** Supports "Forward/Backward Compatibility" by handling -/// size mismatches. If a received user-defined object is larger than expected (newer version), -/// the parser safely discards the extra data. -/// * **Type Safety:** Uses SFINAE and compile-time static assertions to prevent -/// serialization of unsupported types or unsafe pointers. -/// * **Deep Copying:** Supports serializing containers of pointers, automatically -/// allocating memory upon deserialization. -/// * **Error Handling:** Includes a callback-based error reporting mechanism for -/// stream errors, type mismatches, and boundary violations. -/// -/// **Usage:** -/// User-defined classes must inherit from `serialize::I` and implement the `read()` -/// and `write()` methods. - -#ifndef MSG_SERIALIZE_H_ -#define MSG_SERIALIZE_H_ - -#include -#include -#include -#include "delegate/DelegateOpt.h" // DMQ_ASSERT_TRUE, dmq::SERIALIZE_* limits -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace serialize_traits -{ - template - struct is_shared_ptr : std::false_type {}; - - template - struct is_shared_ptr> : std::true_type {}; - - template - struct is_unsupported_container : std::false_type {}; - - /// @brief Trait to check if a stream type is seekable. - template - struct is_seekable : std::false_type {}; - - template - struct is_seekable().seekp(std::declval())), - decltype(std::declval().tellp()) - >> : std::true_type {}; -} - -// Define to enable compile-time checking of unsupported container types -// Undefine for less compile-time include file dependencies -#define CHECK_UNSUPPORTED_CONTAINER -#ifdef CHECK_UNSUPPORTED_CONTAINER - -#include -#include -#include -#include -#include -#include - - template - struct serialize_traits::is_unsupported_container> : std::true_type {}; - - template - struct serialize_traits::is_unsupported_container> : std::true_type {}; - - template - struct serialize_traits::is_unsupported_container> : std::true_type {}; - - template - struct serialize_traits::is_unsupported_container> : std::true_type {}; - - template - struct serialize_traits::is_unsupported_container>> : std::true_type {}; - - template - struct serialize_traits::is_unsupported_container> : std::true_type {}; - - template - struct serialize_traits::is_unsupported_container> : std::true_type {}; - - template - struct serialize_traits::is_unsupported_container> : std::true_type {}; - - template - struct serialize_traits::is_unsupported_container> : std::true_type {}; - - template - struct serialize_traits::is_unsupported_container> : std::true_type {}; -#endif // CHECK_UNSUPPORTED_CONTAINER - -/// @brief The serialize class binary serializes and deserializes C++ objects. -/// @details Each class need to implement the serialize::I abstract interface -/// to allow binary serialization to any stream. A default constructor is required -/// for the serialized object. Most container elements can be stored by value or -/// by pointer. C++ containers supported are: -/// -/// vector -/// array (std::array, uses the VECTOR type so it interoperates with vector) -/// list -/// map -/// set -/// string -/// wstring -/// char[] -/// -/// Always check the input stream or output stream to ensure no errors -/// before using data. e.g. -/// -/// if (ss.good()) -/// // Do something with input or output data -/// -/// This serialization class is not thread safe and a serialize instance should -/// only be accessed from a single task. -/// -/// The serialize class support receiving objects that have more or less data fields -/// than what is currently being parsed. If more data is received after parsing an -/// object, the extra data is discarded. If less data is received, the parsing of the -/// extra data fields does not occur. This supports the protocol changing by adding new -/// data elements to an object. Once the protocol is released at a particular version, -/// new data elements can be added but existing ones cannot be removed/changed. -/// -/// @note write() requires a seekable stream (i.e. std::ostringstream). The size field -/// for user-defined objects is backfilled via seekp() after the object is written. -/// Using a non-seekable stream produces a corrupt size field and triggers an error. -class serialize -{ -public: - /// @brief Abstract interface that all serialized user defined classes inherit. - class I - { - public: - virtual ~I() = default; - - /// Inheriting class implements the write function. Write each - /// class member to the ostream. Write in the same order as read(). - /// Each level within the hierarchy must implement. Ensure base - /// write() implementation is called if necessary. - /// @param[in] ms - the message serialize instance - /// @param[in] os - the output stream - /// @return The output stream - virtual std::ostream& write(serialize& ms, std::ostream& os) = 0; - - /// Inheriting class implements the read function. Read each - /// class member from the istream. Read in the same order as write(). - /// Each level within the hierarchy must implement. Ensure base - /// read() implementation is called if necessary. - /// @param[in] ms - the message serialize instance - /// @param[in] is - the input stream - /// @return The input stream - virtual std::istream& read(serialize& ms, std::istream& is) = 0; - }; - - enum class Type - { - UNKNOWN = 0, - LITERAL = 1, - STRING = 8, - WSTRING = 9, - VECTOR = 20, - MAP = 21, - LIST = 22, - SET = 23, - ENDIAN = 30, - USER_DEFINED = 31, - }; - - enum class ParsingError - { - NONE, - TYPE_MISMATCH, - STREAM_ERROR, - NON_SEEKABLE_STREAM, // Stream does not support tellp/seekp (required for objects) - STRING_TOO_LONG, - CONTAINER_TOO_MANY, - INVALID_INPUT, - END_OF_FILE, - NESTING_TOO_DEEP // USER_DEFINED nesting exceeded MAX_PARSE_STACK_DEPTH - }; - - serialize() = default; - ~serialize() = default; - - /// Returns true if the host is little-endian. - /// @return Returns true if little-endian. - static bool LE() - { - const static int n = 1; - const static bool le = (*reinterpret_cast(&n) == 1); - return le; - } - - /// Read endian from stream. - /// @param[in] is - input stream - /// @param[out] littleEndian - set to true if stream was written on a little-endian host - /// @return The input stream. - std::istream& readEndian(std::istream& is, bool& littleEndian) - { - if (read_type(is, Type::ENDIAN)) - { - is.read(reinterpret_cast(&littleEndian), sizeof(littleEndian)); - } - return is; - } - - /// Write current CPU endian to stream. - /// @param[in] os - output stream - void writeEndian(std::ostream& os) - { - bool littleEndian = LE(); - write_type(os, Type::ENDIAN); - os.write(reinterpret_cast(&littleEndian), sizeof(littleEndian)); - } - - /// Read a user defined object implementing the serialize::I interface from a stream. - /// Normally the sender and receiver object is the same size. However, if a newer version of - /// the object is introduced on one side the sizes will differ. If received object is smaller - /// than sent object, the extra data in the sent object is discarded. - /// @param[in] is - the input stream - /// @param[in] t_ - the object to read - /// @return The input stream - std::istream& read(std::istream& is, I* t_) - { - if (check_stop_parse(is)) - return is; - - if (check_pointer(is, t_)) - { - if (read_type(is, Type::USER_DEFINED)) - { - uint16_t size = 0; - std::streampos startPos = is.tellg(); - if (startPos == std::streampos(-1)) - { - raiseError(ParsingError::NON_SEEKABLE_STREAM, __LINE__, __FILE__); - is.setstate(std::ios::failbit); - return is; - } - - read(is, size, false); - - std::streampos targetStopPos = startPos + std::streampos(size); - - // Bounds check: ensure size does not exceed stream EOF - std::streampos dataPos = is.tellg(); - is.seekg(0, std::ios::end); - std::streampos endPosStream = is.tellg(); - is.seekg(dataPos); - - if (targetStopPos > endPosStream) { - raiseError(ParsingError::INVALID_INPUT, __LINE__, __FILE__); - is.setstate(std::ios::failbit); - return is; - } - - // Bounds check: ensure size does not exceed parent object's bounds - if (stopParsePosIdx > 0 && targetStopPos > stopParsePosStack[stopParsePosIdx - 1]) { - raiseError(ParsingError::INVALID_INPUT, __LINE__, __FILE__); - is.setstate(std::ios::failbit); - return is; - } - - parseStatus(typeid(*t_), size); - - // Save the stop parsing position to prevent parsing overrun - if (!push_stop_parse_pos(targetStopPos)) { - raiseError(ParsingError::NESTING_TOO_DEEP, __LINE__, __FILE__); - is.setstate(std::ios::failbit); - return is; - } - - t_->read(*this, is); - - pop_stop_parse_pos(); - - if (is.good()) - { - std::streampos endPos = is.tellg(); - uint16_t rcvdSize = static_cast(endPos - startPos); - - // Did sender send a larger object than what receiver parsed? - if (rcvdSize < size) - { - // Skip over the extra received data - uint16_t seekOffset = size - rcvdSize; - is.seekg(seekOffset, std::ios_base::cur); - } - } - return is; - } - } - return is; - } - - /// Read a std::string from a stream. - /// @param[in] is - the input stream - /// @param[in] s - the string to read - /// @return The input stream - template - std::istream& read(std::istream& is, std::basic_string& s) - { - if (check_stop_parse(is)) - return is; - - if (read_type(is, Type::STRING)) - { - uint16_t size = 0; - read(is, size, false); - s.clear(); - if (check_stream(is) && check_slength(is, size)) - { - s.resize(size); - parseStatus(typeid(s), s.size()); - read_internal(is, &s[0], size, true); - } - } - return is; - } - - /// Read a std::wstring from a stream. - /// @param[in] is - the input stream - /// @param[in] s - the string to read - /// @return The input stream - template - std::istream& read(std::istream& is, std::basic_string& s) - { - if (check_stop_parse(is)) - return is; - - if (read_type(is, Type::WSTRING)) - { - uint16_t size = 0; - read(is, size, false); - s.clear(); - if (check_stream(is) && check_slength(is, size)) - { - s.resize(size); - parseStatus(typeid(s), s.size()); - for (uint16_t ii = 0; ii < size; ii++) - { - wchar_t c = 0; - int offset = LE() ? 0 : (sizeof(wchar_t) - WCHAR_SIZE); - read_internal(is, reinterpret_cast(&c) + offset, WCHAR_SIZE); - s[ii] = c; - } - } - } - return is; - } - - /// Read a character string from a stream. - /// @param[in] is - the input stream - /// @param[in] str - the character string to read into - /// @param[in] maxLen - the capacity of str in bytes (including null terminator) - /// @return The input stream - std::istream& read(std::istream& is, char* str, size_t maxLen) - { - if (check_stop_parse(is)) - return is; - - if (read_type(is, Type::STRING)) - { - uint16_t size = 0; - read(is, size, false); - if (!check_stream(is) || !check_pointer(is, str)) - return is; - if (maxLen == 0) - { - raiseError(ParsingError::STRING_TOO_LONG, __LINE__, __FILE__); - is.setstate(std::ios::failbit); - return is; - } - // Leave str a valid (empty) C string on every early return below. - // An empty std::string is sent with size 0 and no bytes. - str[0] = '\0'; - if (size == 0) - return is; - if (!check_slength(is, size)) - return is; - if (size > maxLen) - { - raiseError(ParsingError::STRING_TOO_LONG, __LINE__, __FILE__); - is.setstate(std::ios::failbit); - return is; - } - parseStatus(typeid(str), size); - read_internal(is, str, size, true); - - // Truncated stream: is.read() stopped early, so str[gcount()..size-1] - // is uninitialized. Report the stream error, not STRING_TOO_LONG. - if (!check_stream(is)) - { - str[0] = '\0'; - return is; - } - - // Strings go out without a terminator (older versions sent one with - // a const char*). Terminate here if the data didn't, failing if - // there's no room. - if (str[size - 1] != '\0') - { - if (size < maxLen) - { - str[size] = '\0'; - } - else - { - str[maxLen - 1] = '\0'; - raiseError(ParsingError::STRING_TOO_LONG, __LINE__, __FILE__); - is.setstate(std::ios::failbit); - } - } - } - return is; - } - - /// Read a vector container from a stream. The vector items are - /// stored differently and therefore need special handling to serialize. - /// Unlike other specializations of vector, std::vector does not manage a - /// dynamic array of bool objects. Instead, it is supposed to pack the boolean - /// values into a single bit each. - /// @param[in] is - the input stream - /// @param[in] container - the vector container to read into - /// @return The input stream - std::istream& read(std::istream& is, std::vector& container) - { - if (check_stop_parse(is)) - return is; - - container.clear(); - if (read_type(is, Type::VECTOR)) - { - uint16_t size = 0; - read(is, size, false); - if (check_stream(is) && check_container_size(is, size)) - { - parseStatus(typeid(container), size); - // One allocation of the final size instead of regrowing per element. - container.reserve(size); - for (uint16_t i = 0; i < size; ++i) - { - bool t; - read(is, t); - container.push_back(t); - } - } - } - return is; - } - - /// Write a user defined object implementing the serialize::I interface to a stream. - /// @note The stream must support seekp(). The object size is backfilled after writing. - /// @param[in] os - the output stream - /// @param[in] t_ - the object to write - /// @return The output stream - std::ostream& write(std::ostream& os, I* t_) - { - if (check_pointer(os, t_)) - { - uint16_t elementSize = 0; - - write_type(os, Type::USER_DEFINED); - std::streampos elementSizePos = os.tellp(); - if (elementSizePos == std::streampos(-1)) - { - raiseError(ParsingError::NON_SEEKABLE_STREAM, __LINE__, __FILE__); - os.setstate(std::ios::failbit); - return os; - } - write(os, elementSize, false); - - // Write user defined object - t_->write(*this, os); - - if (os.good()) - { - // Backfill the object size into the stream (requires seekable stream) - std::streampos currentPos = os.tellp(); - os.seekp(elementSizePos); - auto sizeDiff = currentPos - elementSizePos; - if (sizeDiff > UINT16_MAX) { - raiseError(ParsingError::INVALID_INPUT, __LINE__, __FILE__); - os.setstate(std::ios::failbit); - return os; - } - elementSize = static_cast(sizeDiff); - write(os, elementSize, false); - os.seekp(currentPos); - } - return os; - } - return os; - } - - /// Write a const std::string to a stream. - /// @param[in] os - the output stream - /// @param[in] s - the string to write - /// @return The output stream - template - std::ostream& write(std::ostream& os, const std::basic_string& s) - { - if (s.size() > MAX_STRING_SIZE) { - raiseError(ParsingError::STRING_TOO_LONG, __LINE__, __FILE__); - os.setstate(std::ios::failbit); - return os; - } - uint16_t size = static_cast(s.size()); - write_type(os, Type::STRING); - write(os, size, false); - if (check_stream(os) && check_slength(os, size)) - { - write_internal(os, s.c_str(), size, true); - } - return os; - } - - /// Write a std::string to a stream. - /// @param[in] os - the output stream - /// @param[in] s - the string to write - /// @return The output stream - template - std::ostream& write(std::ostream& os, std::basic_string& s) - { - return write(os, static_cast&>(s)); - } - - /// Write a const std::wstring to a stream. - /// @param[in] os - the output stream - /// @param[in] s - the string to write - /// @return The output stream - template - std::ostream& write(std::ostream& os, const std::basic_string& s) - { - if (s.size() > MAX_STRING_SIZE) { - raiseError(ParsingError::STRING_TOO_LONG, __LINE__, __FILE__); - os.setstate(std::ios::failbit); - return os; - } - uint16_t size = static_cast(s.size()); - write_type(os, Type::WSTRING); - write(os, size, false); - if (check_stream(os) && check_slength(os, size)) - { - for (uint16_t ii = 0; ii < size; ii++) - { - wchar_t c = s[ii]; - int offset = LE() ? 0 : (sizeof(wchar_t) - WCHAR_SIZE); - write_internal(os, reinterpret_cast(&c) + offset, WCHAR_SIZE); - } - } - return os; - } - - /// Write a std::wstring to a stream. - /// @param[in] os - the output stream - /// @param[in] s - the string to write - /// @return The output stream - template - std::ostream& write(std::ostream& os, std::basic_string& s) - { - return write(os, static_cast&>(s)); - } - - /// Write a character string to a stream. - /// @param[in] os - the output stream - /// @param[in] str - the character string to write. - /// @return The output stream - std::ostream& write(std::ostream& os, char* str) - { - return write(os, static_cast(str)); - } - - /// Write a const character string to a stream. - /// @param[in] os - the output stream - /// @param[in] str - the character string to write. - /// @return The output stream - std::ostream& write(std::ostream& os, const char* str) - { - if (check_pointer(os, str)) - { - // Check before narrowing: a length over 65535 would wrap the 16-bit - // size and silently send a truncated string. - const size_t len = strlen(str); - if (len > MAX_STRING_SIZE) - { - raiseError(ParsingError::STRING_TOO_LONG, __LINE__, __FILE__); - os.setstate(std::ios::failbit); - return os; - } - // No terminator on the wire, the same as std::string: the reader - // adds one for a char buffer, and a std::string keeps every byte. - uint16_t size = static_cast(len); - write_type(os, Type::STRING); - write(os, size, false); - if (check_stream(os) && check_slength(os, size)) - { - write_internal(os, str, size, true); - } - } - return os; - } - - /// Write a vector container to a stream. The vector items are - /// stored differently and therefore need special handling to serialize. - /// Unlike other specializations of vector, std::vector does not manage a - /// dynamic array of bool objects. Instead, it is supposed to pack the boolean - /// values into a single bit each. - /// @param[in] os - the output stream - /// @param[in] container - the vector container to write - /// @return The output stream - std::ostream& write(std::ostream& os, const std::vector& container) - { - if (container.size() > MAX_CONTAINER_SIZE) { - raiseError(ParsingError::CONTAINER_TOO_MANY, __LINE__, __FILE__); - os.setstate(std::ios::failbit); - return os; - } - uint16_t size = static_cast(container.size()); - write_type(os, Type::VECTOR); - write(os, size, false); - if (check_stream(os) && check_container_size(os, size)) - { - for (const bool& c : container) - { - write(os, c); - } - } - return os; - } - - /// Read an object from a stream. - /// @param[in] is - the input stream - /// @param[in] t_ - the object to read into - /// @return The input stream - template - std::istream& read(std::istream& is, T& t_, bool readPrependedType = true) - { - static_assert(!serialize_traits::is_unsupported_container::value, "Unsupported C++ container type"); - - static_assert(!(std::is_pointer::value && - (std::is_arithmetic::type>::value || - std::is_class::type>::value)), - "T cannot be a pointer to a built-in or custom data type. Use values instead."); - - // Same check as write(): any other class type would be cast to I* below. - static_assert(!std::is_class::value || std::is_base_of::value, - "T must inherit from serialize::I"); - - if (check_stop_parse(is)) - return is; - - // If C++17 or higher -#if defined(_MSVC_LANG) && _MSVC_LANG >= 201703L || __cplusplus >= 201703L - // Check if T is a user-defined class - if constexpr (std::is_class::value) - { - // C-style cast required: T may be const-qualified (e.g. const AlarmMsg) - // when called from a const context, and neither static_cast nor - // reinterpret_cast can strip const. A C-style cast combines const_cast - // with the pointer conversion in one step. The static_assert above - // guarantees T derives from I whenever this branch is executed. - read(is, (serialize::I*)(&t_)); - return is; - } - else - { - // If T is not a class, handle built-in data types - if constexpr (std::is_pointer::value == false) - { - if (readPrependedType) - { - if (!read_type(is, Type::LITERAL)) - { - return is; - } - } - - if (readPrependedType) - parseStatus(typeid(t_), sizeof(t_)); - read_internal(is, reinterpret_cast(&t_), sizeof(t_)); - return is; - } - else - { - // Can't read pointers to built-in types - raiseError(ParsingError::INVALID_INPUT, __LINE__, __FILE__); - is.setstate(std::ios::failbit); - return is; - } - } -#else - // Is T a built-in data type (e.g. float, int, ...)? -#if defined(_MSC_VER) -#pragma warning(push) -#pragma warning(disable: 6326) -#endif - if (std::is_class::value == false) - { - // Is T is not a pointer type - if (std::is_pointer::value == false) - { - if (readPrependedType) - { - if (!read_type(is, Type::LITERAL)) - { - return is; - } - } - - if (readPrependedType) - parseStatus(typeid(t_), sizeof(t_)); - read_internal(is, reinterpret_cast(&t_), sizeof(t_)); - return is; - } - else - { - // Can't read pointers to built-in type - raiseError(ParsingError::INVALID_INPUT, __LINE__, __FILE__); - is.setstate(std::ios::failbit); - return is; - } - } - // Else T is a user defined data type (e.g. MyData) - else - { - // C-style cast required: without if constexpr (C++14) this branch is - // compiled for all T including primitives, so static_cast is rejected - // for non-class types. The branch is only reached when is_class is - // true, making the cast safe at runtime. - read(is, (serialize::I*)(&t_)); - return is; - } -#if defined(_MSC_VER) -#pragma warning(pop) -#endif -#endif - } - - /// Write an object to a stream. - /// @param[in] os - the output stream - /// @param[in] t_ - the object to write - /// @return The output stream - template - std::ostream& write(std::ostream& os, T& t_, bool prependType = true) - { - static_assert(!serialize_traits::is_unsupported_container::value, "Unsupported C++ container type"); - - static_assert(!(std::is_pointer::value && - (std::is_arithmetic::type>::value || - std::is_class::type>::value)), - "T cannot be a pointer to a built-in or custom data type. Use values instead."); - - // When T is a class it must inherit from serialize::I. - // The combined form (!is_class || is_base_of) is valid for all T — non-class - // types satisfy the first clause so the assertion always passes for them. - static_assert(!std::is_class::value || std::is_base_of::value, - "T must inherit from serialize::I"); - - // If C++17 or higher -#if defined(_MSVC_LANG) && _MSVC_LANG >= 201703L || __cplusplus >= 201703L - // Check if T is a user-defined class - if constexpr (std::is_class::value) - { - // C-style cast required: T may be const-qualified (e.g. const AlarmMsg) - // when called from a const context, and neither static_cast nor - // reinterpret_cast can strip const. A C-style cast combines const_cast - // with the pointer conversion in one step. The static_assert above - // guarantees T derives from I whenever this branch is executed. - return write(os, (serialize::I*)(&t_)); - } - else - { - // If T is not a class, handle built-in data types - if constexpr (std::is_pointer::value == false) - { - if (prependType) - { - write_type(os, Type::LITERAL); - } - return write_internal(os, reinterpret_cast(&t_), sizeof(t_)); - } - else - { - // Can't write pointers to built-in types - raiseError(ParsingError::INVALID_INPUT, __LINE__, __FILE__); - os.setstate(std::ios::failbit); - return os; - } - } -#else - // Is T type a built-in data type (e.g. float, int, ...)? -#if defined(_MSC_VER) -#pragma warning(push) -#pragma warning(disable: 6326) -#endif - if (std::is_class::value == false) - { - // Is T is not a pointer type - if (std::is_pointer::value == false) - { - if (prependType) - { - write_type(os, Type::LITERAL); - } - return write_internal(os, reinterpret_cast(&t_), sizeof(t_)); - } - else - { - // Can't write pointers to built-in type - raiseError(ParsingError::INVALID_INPUT, __LINE__, __FILE__); - os.setstate(std::ios::failbit); - return os; - } - } - // Else T type is a user defined data type (e.g. MyData) - else - { - // C-style cast required: without if constexpr (C++14) this branch is - // compiled for all T including primitives, so static_cast and static_assert - // are rejected for non-class types. The branch is only reached when - // is_class is true, making the cast safe at runtime. - return write(os, (serialize::I*)(&t_)); - } -#if defined(_MSC_VER) -#pragma warning(pop) -#endif -#endif - } - - /// Write a vector container to a stream. The items in vector are stored - /// by value. - /// @param[in] os - the output stream - /// @param[in] container - the vector container to write - /// @return The output stream - template - std::ostream& write(std::ostream& os, const std::vector& container) - { - static_assert(!serialize_traits::is_shared_ptr::value, "Type T must not be a shared_ptr type"); - - if (container.size() > MAX_CONTAINER_SIZE) { - raiseError(ParsingError::CONTAINER_TOO_MANY, __LINE__, __FILE__); - os.setstate(std::ios::failbit); - return os; - } - uint16_t size = static_cast(container.size()); - write_type(os, Type::VECTOR); - write(os, size, false); - if (check_stream(os) && check_container_size(os, size)) - { - for (const auto& item : container) - { - write_element(os, item); - } - } - return os; - } - - /// Read into a vector container from a stream. Items in vector are stored - /// by value. - /// @param[in] is - the input stream - /// @param[in] container - the vector container to read into - /// @return The input stream - template - std::istream& read(std::istream& is, std::vector& container) - { - static_assert(!serialize_traits::is_shared_ptr::value, "Type T must not be a shared_ptr type"); - - if (check_stop_parse(is)) - return is; - - container.clear(); - if (read_type(is, Type::VECTOR)) - { - uint16_t size = 0; - read(is, size, false); - if (check_stream(is) && check_container_size(is, size)) - { - parseStatus(typeid(container), size); - // One allocation of the final size instead of regrowing per element. - container.reserve(size); - for (uint16_t i = 0; i < size; ++i) - { - T t; - read_element(is, t); - container.push_back(t); - } - } - } - return is; - } - - /// Write a vector container to a stream. The items in vector are stored - /// by pointer. - /// @param[in] os - the output stream - /// @param[in] container - the vector container to write - /// @return The output stream - template - std::ostream& write(std::ostream& os, const std::vector& container) - { - static_assert(std::is_base_of::value, "Type T must be derived from serialize::I"); - - if (container.size() > MAX_CONTAINER_SIZE) { - raiseError(ParsingError::CONTAINER_TOO_MANY, __LINE__, __FILE__); - os.setstate(std::ios::failbit); - return os; - } - uint16_t size = static_cast(container.size()); - write_type(os, Type::VECTOR); - write(os, size, false); - - if (check_stream(os) && check_container_size(os, size)) - { - for (auto* ptr : container) - { - if (ptr != nullptr) - { - bool notNULL = true; - write(os, notNULL, false); - - auto* i = static_cast(ptr); - write(os, i); - } - else - { - bool notNULL = false; - write(os, notNULL, false); - } - } - - } - return os; - } - - /// Read into a vector container from a stream. Items in vector stored - /// by pointer. Operator new called to create object instances. - /// @param[in] is - the input stream - /// @param[in] container - the vector container to read into - /// @return The input stream - template - std::istream& read(std::istream& is, std::vector& container) - { - static_assert(std::is_base_of::value, "Type T must be derived from serialize::I"); - - if (check_stop_parse(is)) - return is; - - container.clear(); - if (read_type(is, Type::VECTOR)) - { - uint16_t size = 0; - read(is, size, false); - if (check_stream(is) && check_container_size(is, size)) - { - parseStatus(typeid(container), size); - // One allocation of the final size instead of regrowing per element. - container.reserve(size); - for (uint16_t i = 0; i < size; ++i) - { - bool notNULL = false; - read(is, notNULL, false); - - if (notNULL) - { - T* object = new T; - auto* iface = static_cast(object); - read(is, iface); - container.push_back(object); - } - else - { - container.push_back(nullptr); - } - } - } - } - return is; - } - - /// Write a map container to a stream. The items in map are stored - /// by value. - /// @param[in] os - the output stream - /// @param[in] container - the map container to write - /// @return The output stream - template - std::ostream& write(std::ostream& os, const std::map& container) - { - static_assert(!serialize_traits::is_shared_ptr::value, "Type V must not be a shared_ptr type"); - - if (container.size() > MAX_CONTAINER_SIZE) { - raiseError(ParsingError::CONTAINER_TOO_MANY, __LINE__, __FILE__); - os.setstate(std::ios::failbit); - return os; - } - uint16_t size = static_cast(container.size()); - write_type(os, Type::MAP); - write(os, size, false); - if (check_stream(os) && check_container_size(os, size)) - { - for (const auto& entry : container) - { - write_element(os, entry.first); - write_element(os, entry.second); - } - } - return os; - } - - /// Read into a map container from a stream. Items in map are stored - /// by value. - /// @param[in] is - the input stream - /// @param[in] container - the map container to read into - /// @return The input stream - template - std::istream& read(std::istream& is, std::map& container) - { - static_assert(!serialize_traits::is_shared_ptr::value, "Type V must not be a shared_ptr type"); - - if (check_stop_parse(is)) - return is; - - container.clear(); - if (read_type(is, Type::MAP)) - { - uint16_t size = 0; - read(is, size, false); - if (check_stream(is) && check_container_size(is, size)) - { - parseStatus(typeid(container), size); - for (uint16_t i = 0; i < size; ++i) - { - K key; - V value; - read_element(is, key); - read_element(is, value); - container[key] = value; - } - } - } - return is; - } - - /// Write a map container to a stream. The items in map are stored - /// by pointer. - /// @param[in] os - the output stream - /// @param[in] container - the map container to write - /// @return The output stream - template - std::ostream& write(std::ostream& os, const std::map& container) - { - static_assert(std::is_base_of::value, "Type V must be derived from serialize::I"); - - if (container.size() > MAX_CONTAINER_SIZE) { - raiseError(ParsingError::CONTAINER_TOO_MANY, __LINE__, __FILE__); - os.setstate(std::ios::failbit); - return os; - } - uint16_t size = static_cast(container.size()); - write_type(os, Type::MAP); - write(os, size, false); - - if (check_stream(os) && check_container_size(os, size)) - { - for (const auto& entry : container) - { - write_element(os, entry.first); - - if (entry.second != nullptr) - { - bool notNULL = true; - write(os, notNULL, false); - - auto* i = static_cast(entry.second); - write(os, i); - } - else - { - bool notNULL = false; - write(os, notNULL, false); - } - } - } - return os; - } - - /// Read into a map container from a stream. Items in map stored - /// by pointer. Operator new called to create object instances. - /// @param[in] is - the input stream - /// @param[in] container - the map container to read into - /// @return The input stream - template - std::istream& read(std::istream& is, std::map& container) - { - static_assert(std::is_base_of::value, "Type V must be derived from serialize::I"); - - if (check_stop_parse(is)) - return is; - - container.clear(); - if (read_type(is, Type::MAP)) - { - uint16_t size = 0; - read(is, size, false); - if (check_stream(is) && check_container_size(is, size)) - { - parseStatus(typeid(container), size); - for (uint16_t i = 0; i < size; ++i) - { - K key; - read_element(is, key); - bool notNULL; - read(is, notNULL, false); - if (notNULL) - { - V* object = new V; - auto* iface = static_cast(object); - read(is, iface); - container[key] = static_cast(object); - } - else - { - container[key] = nullptr; - } - } - } - } - return is; - } - - /// Write a set container to a stream. The items in set are stored - /// by value. - /// @param[in] os - the output stream - /// @param[in] container - the set container to write - /// @return The output stream - template - std::ostream& write(std::ostream& os, const std::set& container) - { - static_assert(!serialize_traits::is_shared_ptr::value, "Type T must not be a shared_ptr type"); - - if (container.size() > MAX_CONTAINER_SIZE) { - raiseError(ParsingError::CONTAINER_TOO_MANY, __LINE__, __FILE__); - os.setstate(std::ios::failbit); - return os; - } - uint16_t size = static_cast(container.size()); - write_type(os, Type::SET); - write(os, size, false); - - if (check_stream(os) && check_container_size(os, size)) - { - for (const auto& item : container) - { - write_element(os, item); - } - } - return os; - } - - /// Read into a set container from a stream. Items in set are stored - /// by value. - /// @param[in] is - the input stream - /// @param[in] container - the set container to read into - /// @return The input stream - template - std::istream& read(std::istream& is, std::set& container) - { - static_assert(!serialize_traits::is_shared_ptr::value, "Type T must not be a shared_ptr type"); - - if (check_stop_parse(is)) - return is; - - container.clear(); - if (read_type(is, Type::SET)) - { - uint16_t size = 0; - read(is, size, false); - if (check_stream(is) && check_container_size(is, size)) - { - parseStatus(typeid(container), size); - for (uint16_t i = 0; i < size; ++i) - { - T t; - read_element(is, t); - container.insert(t); - } - } - } - return is; - } - - /// Write a set container to a stream. The items in set are stored - /// by pointer. - /// @param[in] os - the output stream - /// @param[in] container - the set container to write - /// @return The output stream - template - std::ostream& write(std::ostream& os, const std::set& container) - { - static_assert(std::is_base_of::value, "Type T must be derived from serialize::I"); - - if (container.size() > MAX_CONTAINER_SIZE) { - raiseError(ParsingError::CONTAINER_TOO_MANY, __LINE__, __FILE__); - os.setstate(std::ios::failbit); - return os; - } - uint16_t size = static_cast(container.size()); - write_type(os, Type::SET); - write(os, size, false); - if (check_stream(os) && check_container_size(os, size)) - { - for (auto ptr : container) - { - if (ptr != nullptr) - { - bool notNULL = true; - write(os, notNULL, false); - - auto* i = static_cast(ptr); - write(os, i); - } - else - { - bool notNULL = false; - write(os, notNULL, false); - } - } - } - return os; - } - - /// Read into a set container from a stream. Items in set stored - /// by pointer. Operator new called to create object instances. - /// @param[in] is - the input stream - /// @param[in] container - the set container to read into - /// @return The input stream - template - std::istream& read(std::istream& is, std::set& container) - { - static_assert(std::is_base_of::value, "Type T must be derived from serialize::I"); - - if (check_stop_parse(is)) - return is; - - container.clear(); - if (read_type(is, Type::SET)) - { - uint16_t size = 0; - read(is, size, false); - if (check_stream(is) && check_container_size(is, size)) - { - parseStatus(typeid(container), size); - for (uint16_t i = 0; i < size; ++i) - { - bool notNULL = false; - read(is, notNULL, false); - if (notNULL) - { - T* object = new T; - auto* iface = static_cast(object); - read(is, iface); - container.insert(object); - } - else - { - container.insert(nullptr); - } - } - } - } - return is; - } - - /// Write a list container to a stream. The items in list are stored - /// by value. - /// @param[in] os - the output stream - /// @param[in] container - the list container to write - /// @return The output stream - template - std::ostream& write(std::ostream& os, const std::list& container) - { - static_assert(!serialize_traits::is_shared_ptr::value, "Type T must not be a shared_ptr type"); - - if (container.size() > MAX_CONTAINER_SIZE) { - raiseError(ParsingError::CONTAINER_TOO_MANY, __LINE__, __FILE__); - os.setstate(std::ios::failbit); - return os; - } - uint16_t size = static_cast(container.size()); - write_type(os, Type::LIST); - write(os, size, false); - - if (check_stream(os) && check_container_size(os, size)) - { - for (const auto& item : container) - { - write_element(os, item); - } - } - return os; - } - - /// Read into a list container from a stream. Items in list are stored - /// by value. - /// @param[in] is - the input stream - /// @param[in] container - the list container to read into - /// @return The input stream - template - std::istream& read(std::istream& is, std::list& container) - { - static_assert(!serialize_traits::is_shared_ptr::value, "Type T must not be a shared_ptr type"); - - if (check_stop_parse(is)) - return is; - - container.clear(); - if (read_type(is, Type::LIST)) - { - uint16_t size = 0; - read(is, size, false); - if (check_stream(is) && check_container_size(is, size)) - { - parseStatus(typeid(container), size); - for (uint16_t i = 0; i < size; ++i) - { - T t; - read_element(is, t); - container.push_back(t); - } - } - } - return is; - } - - /// Write a list container to a stream. The items in list are stored - /// by pointer. - /// @param[in] os - the output stream - /// @param[in] container - the list container to write - /// @return The output stream - template - std::ostream& write(std::ostream& os, const std::list& container) - { - static_assert(std::is_base_of::value, "Type T must be derived from serialize::I"); - - if (container.size() > MAX_CONTAINER_SIZE) { - raiseError(ParsingError::CONTAINER_TOO_MANY, __LINE__, __FILE__); - os.setstate(std::ios::failbit); - return os; - } - uint16_t size = static_cast(container.size()); - write_type(os, Type::LIST); - write(os, size, false); - - if (check_stream(os) && check_container_size(os, size)) - { - for (auto* ptr : container) - { - if (ptr != nullptr) - { - bool notNULL = true; - write(os, notNULL, false); - - auto* i = static_cast(ptr); - write(os, i); - } - else - { - bool notNULL = false; - write(os, notNULL, false); - } - } - } - return os; - } - - /// Read into a list container from a stream. Items in list stored - /// by pointer. Operator new called to create object instances. - /// @param[in] is - the input stream - /// @param[in] container - the list container to read into - /// @return The input stream - template - std::istream& read(std::istream& is, std::list& container) - { - static_assert(std::is_base_of::value, "Type T must be derived from serialize::I"); - - if (check_stop_parse(is)) - return is; - - container.clear(); - if (read_type(is, Type::LIST)) - { - uint16_t size = 0; - read(is, size, false); - if (check_stream(is) && check_container_size(is, size)) - { - parseStatus(typeid(container), size); - for (uint16_t i = 0; i < size; ++i) - { - bool notNULL = false; - read(is, notNULL, false); - if (notNULL) - { - T* object = new T; - auto* iface = static_cast(object); - read(is, iface); - container.push_back(object); - } - else - { - container.push_back(nullptr); - } - } - } - } - return is; - } - - /// Write a std::array. Uses the VECTOR type marker on purpose (no separate ARRAY - /// type), so the bytes match a std::vector and one side can declare the field as - /// std::vector while the other uses std::array. The element count on the - /// wire is what catches a mismatch: the array read requires exactly N. A fixed-size - /// array needs no allocation, which suits fixed-block / no-heap targets. - /// @param[in] os - the output stream - /// @param[in] container - the array to write - /// @return The output stream - template - std::ostream& write(std::ostream& os, const std::array& container) - { - static_assert(N <= MAX_CONTAINER_SIZE, "std::array larger than DMQ_SERIALIZE_MAX_CONTAINER_SIZE"); - static_assert(!std::is_pointer::value, "std::array of pointers is not supported"); - write_type(os, Type::VECTOR); - uint16_t size = static_cast(N); - write(os, size, false); - if (check_stream(os)) - { - for (const auto& item : container) - write_element(os, item); - } - return os; - } - - /// Read into a std::array. Accepts the VECTOR type marker, so it reads data - /// written from a std::vector or a std::array. The received element count must - /// equal N; otherwise the read fails (INVALID_INPUT) and the array is unchanged. - /// A list, set or map fails with TYPE_MISMATCH. - /// @param[in] is - the input stream - /// @param[in] container - the array to read into - /// @return The input stream - template - std::istream& read(std::istream& is, std::array& container) - { - static_assert(N <= MAX_CONTAINER_SIZE, "std::array larger than DMQ_SERIALIZE_MAX_CONTAINER_SIZE"); - static_assert(!std::is_pointer::value, "std::array of pointers is not supported"); - - if (check_stop_parse(is)) - return is; - - if (read_type(is, Type::VECTOR)) - { - uint16_t size = 0; - read(is, size, false); - if (check_stream(is) && check_container_size(is, size)) - { - if (size != N) - { - raiseError(ParsingError::INVALID_INPUT, __LINE__, __FILE__); - is.setstate(std::ios::failbit); - return is; - } - parseStatus(typeid(container), size); - for (auto& item : container) - read_element(is, item); - } - } - return is; - } - - // Non-const containers forward to the const overloads above. Without these, - // a non-const container binds better to the generic write(os, T&, bool) - // template than to a const overload, and fails its static_assert. - std::ostream& write(std::ostream& os, std::vector& container) - { - return write(os, static_cast&>(container)); - } - template - std::ostream& write(std::ostream& os, std::vector& container) - { - return write(os, static_cast&>(container)); - } - template - std::ostream& write(std::ostream& os, std::vector& container) - { - return write(os, static_cast&>(container)); - } - template - std::ostream& write(std::ostream& os, std::map& container) - { - return write(os, static_cast&>(container)); - } - template - std::ostream& write(std::ostream& os, std::map& container) - { - return write(os, static_cast&>(container)); - } - template - std::ostream& write(std::ostream& os, std::set& container) - { - return write(os, static_cast&>(container)); - } - template - std::ostream& write(std::ostream& os, std::set& container) - { - return write(os, static_cast&>(container)); - } - template - std::ostream& write(std::ostream& os, std::list& container) - { - return write(os, static_cast&>(container)); - } - template - std::ostream& write(std::ostream& os, std::list& container) - { - return write(os, static_cast&>(container)); - } - - template - std::ostream& write(std::ostream& os, std::array& container) - { - return write(os, static_cast&>(container)); - } - - typedef void (*ErrorHandler)(ParsingError error, int line, const char* file); - void setErrorHandler(ErrorHandler error_handler_) - { - error_handler = error_handler_; - } - - ParsingError getLastError() const { return lastError; } - void clearLastError() { lastError = ParsingError::NONE; } - - typedef void (*ParseHandler)(const std::type_info& typeId, size_t size); - void setParseHandler(ParseHandler parse_handler_) - { - parse_handler = parse_handler_; - } - -private: - /// Write/read one container element (or map key). Strings and nested - /// containers go to their own overloads (with their type prefix and size); - /// everything else to write()/read() without a type prefix. A 3-argument - /// write(os, x, false) on a string or container would pick the generic - /// template instead, which only handles literals and serialize::I types. - template - std::ostream& write_element(std::ostream& os, const std::basic_string& s) - { - return write(os, s); - } - - template - std::ostream& write_element(std::ostream& os, const std::vector& c) - { - return write(os, c); - } - - template - std::ostream& write_element(std::ostream& os, const std::list& c) - { - return write(os, c); - } - - template - std::ostream& write_element(std::ostream& os, const std::set& c) - { - return write(os, c); - } - - template - std::ostream& write_element(std::ostream& os, const std::map& c) - { - return write(os, c); - } - - template - std::ostream& write_element(std::ostream& os, const std::array& c) - { - return write(os, c); - } - - template - std::ostream& write_element(std::ostream& os, const T& t_) - { - return write(os, t_, false); - } - - template - std::istream& read_element(std::istream& is, std::basic_string& s) - { - return read(is, s); - } - - template - std::istream& read_element(std::istream& is, std::vector& c) - { - return read(is, c); - } - - template - std::istream& read_element(std::istream& is, std::list& c) - { - return read(is, c); - } - - template - std::istream& read_element(std::istream& is, std::set& c) - { - return read(is, c); - } - - template - std::istream& read_element(std::istream& is, std::map& c) - { - return read(is, c); - } - - template - std::istream& read_element(std::istream& is, std::array& c) - { - return read(is, c); - } - - template - std::istream& read_element(std::istream& is, T& t_) - { - return read(is, t_, false); - } - - /// Read from stream into caller's character buffer. - /// Wire format is little-endian. On a big-endian host the bytes are reversed - /// after the read so that multi-byte values are correctly stored in memory. - /// @param[in] is - input stream - /// @param[out] p - buffer to receive the bytes - /// @param[in] size - number of bytes to read - /// @param[in] no_swap - true suppresses byte-order reversal (used for char arrays) - /// @return The input stream. - std::istream& read_internal(std::istream& is, char* p, uint32_t size, bool no_swap = false) - { - if (check_stop_parse(is)) - return is; - - if (!check_pointer(is, p)) - return is; - - // Single read for all bytes, then reverse in-place when host is big-endian - is.read(p, size); - if (!LE() && !no_swap && size > 1) - std::reverse(p, p + size); - - return is; - } - - /// Write bytes from caller's buffer to stream. - /// Wire format is little-endian. On a big-endian host the bytes are reversed - /// before writing so that multi-byte values appear in little-endian order on the wire. - /// @param[in] os - output stream - /// @param[in] p - bytes to write - /// @param[in] size - number of bytes to write - /// @param[in] no_swap - true suppresses byte-order reversal (used for char arrays) - /// @return The output stream. - std::ostream& write_internal(std::ostream& os, const char* p, uint32_t size, bool no_swap = false) - { - if (!check_pointer(os, p)) - return os; - - if (!LE() && !no_swap && size > 1) - { - if (size > 8) - { - raiseError(ParsingError::INVALID_INPUT, __LINE__, __FILE__); - os.setstate(std::ios::failbit); - return os; - } - - // Reverse bytes into a small stack buffer then write in a single call. - // Primitives are at most 8 bytes (double / int64_t). - char tmp[8]; - for (uint32_t i = 0; i < size; ++i) - tmp[i] = p[size - 1 - i]; - os.write(tmp, size); - } - else - { - os.write(p, size); - } - return os; - } - - // Maximum sizes allowed by parser (DMQ_SERIALIZE_* in DelegateMQConfig.h) - static constexpr uint16_t MAX_STRING_SIZE = dmq::SERIALIZE_MAX_STRING_SIZE; - static constexpr uint16_t MAX_CONTAINER_SIZE = dmq::SERIALIZE_MAX_CONTAINER_SIZE; - - // Keep wchar_t serialize size consistent on any platform - static const size_t WCHAR_SIZE = 2; - - // LIFO stack used to track stop-parse positions for versioned object reads. - static constexpr size_t MAX_PARSE_STACK_DEPTH = dmq::SERIALIZE_MAX_NESTING; - std::array stopParsePosStack; - size_t stopParsePosIdx = 0; - - ErrorHandler error_handler = nullptr; - ParsingError lastError = ParsingError::NONE; - void raiseError(ParsingError error, int line, const char* file) - { - lastError = error; - if (error_handler) - error_handler(error, line, file); - } - - ParseHandler parse_handler = nullptr; - void parseStatus(const std::type_info& typeId, size_t size = 0) const - { - if (parse_handler) - parse_handler(typeId, size); - } - - void write_type(std::ostream& os, Type type_) - { - uint8_t type = static_cast(type_); - write_internal(os, reinterpret_cast(&type), sizeof(type)); - } - - bool read_type(std::istream& is, Type type_) - { - // Check for end-of-stream before attempting the cast - auto peeked = is.peek(); - if (peeked == std::istream::traits_type::eof()) - { - raiseError(ParsingError::END_OF_FILE, __LINE__, __FILE__); - is.setstate(std::ios::failbit); - return false; - } - Type type = static_cast(peeked); - if (type == type_) - { - uint8_t typeByte = 0; - read_internal(is, reinterpret_cast(&typeByte), sizeof(typeByte)); - return true; - } - else - { - raiseError(ParsingError::TYPE_MISMATCH, __LINE__, __FILE__); - is.setstate(std::ios::failbit); - return false; - } - } - - bool check_stream(std::ios& stream) - { - if (!stream.good()) - { - raiseError(ParsingError::STREAM_ERROR, __LINE__, __FILE__); - stream.setstate(std::ios::failbit); - } - return stream.good(); - } - - bool check_slength(std::ios& stream, int stringSize) - { - bool sizeOk = stringSize <= MAX_STRING_SIZE; - if (!sizeOk) - { - raiseError(ParsingError::STRING_TOO_LONG, __LINE__, __FILE__); - stream.setstate(std::ios::failbit); - } - if (stringSize == 0) - return false; - return sizeOk; - } - - bool check_container_size(std::ios& stream, int containerSize) - { - bool sizeOk = containerSize <= MAX_CONTAINER_SIZE; - if (!sizeOk) - { - raiseError(ParsingError::CONTAINER_TOO_MANY, __LINE__, __FILE__); - stream.setstate(std::ios::failbit); - } - return sizeOk; - } - - bool check_pointer(std::ios& stream, const void* ptr) - { - if (!ptr) - { - raiseError(ParsingError::INVALID_INPUT, __LINE__, __FILE__); - stream.setstate(std::ios::failbit); - } - return ptr != nullptr; - } - - // Returns false if the stack is full (nesting too deep) instead of faulting — - // reachable from remote/untrusted input (deserializing a USER_DEFINED object - // nested more than MAX_PARSE_STACK_DEPTH levels deep), so a malformed message - // must fail that one parse, not hard-fault the process. Caller must not call - // pop_stop_parse_pos() for a push that returned false. - bool push_stop_parse_pos(std::streampos stopParsePos) - { - if (stopParsePosIdx >= MAX_PARSE_STACK_DEPTH) - return false; - stopParsePosStack[stopParsePosIdx++] = stopParsePos; - return true; - } - - // Every call site pairs this 1:1 with a push_stop_parse_pos() that returned - // true, so an empty stack here means internal state corruption, not malformed - // input — stays a hard fault. - std::streampos pop_stop_parse_pos() - { - DMQ_ASSERT_TRUE(stopParsePosIdx > 0); - return stopParsePosStack[--stopParsePosIdx]; - } - - bool check_stop_parse(std::istream& is) - { - if (is.eof()) - { - raiseError(ParsingError::END_OF_FILE, __LINE__, __FILE__); - return true; - } - if (stopParsePosIdx > 0) - { - std::streampos stopParsePos = stopParsePosStack[stopParsePosIdx - 1]; - if (is.tellg() >= stopParsePos) - { - return true; - } - } - return false; - } -}; - -#endif // MSG_SERIALIZE_H_ \ No newline at end of file diff --git a/DelegateMQ/port/transport/README.md b/DelegateMQ/port/transport/README.md deleted file mode 100644 index 00e097d..0000000 --- a/DelegateMQ/port/transport/README.md +++ /dev/null @@ -1,45 +0,0 @@ -# Transports (DelegateMQ Abstraction Layer) - -This directory contains the transport part of the **DelegateMQ Abstraction Layer**: the `ITransport` implementations that enable remote function invocation across various physical media and protocols. - -## Core Interfaces - -* **`dmq::transport::ITransport`**: The abstract base class that all transport implementations must inherit from. Defines the `Send()` and `Receive()` contract. -* **`dmq::transport::DmqHeader`**: Defines the protocol header structure (Marker, ID, Sequence Number, Length) used for framing messages. -* **`dmq::transport::ITransportMonitor`**: Interface for reliability monitoring (ACKs, timeouts, and retries). - -## Implementations - -The subdirectories contain ready-to-use transport implementations for specific platforms and libraries: - -### Network (IP-based) -* **`zeromq`**: High-performance asynchronous messaging using **ZeroMQ**. -* **`nng`**: Scalability protocols using **NNG** (Nanomsg Next Gen). -* **`mqtt`**: Publish/Subscribe messaging using **Paho MQTT**. -* **`linux-tcp` / `linux-udp`**: Standard BSD socket implementations for Linux. -* **`win32-tcp` / `win32-udp`**: Winsock implementations for Windows. -* **`arm-lwip-udp`**: Lightweight IP (lwIP) raw-API implementation for embedded ARM (FreeRTOS/Bare-metal). -* **`arm-lwip-netconn-udp`**: lwIP netconn-API UDP implementation for RTOS targets (selected via `DMQ_TRANSPORT_ARM_LWIP_NETCONN_UDP`). -* **`netx-udp`**: Azure RTOS **NetX / NetX Duo** implementation for ThreadX (selected via `DMQ_TRANSPORT_THREADX_UDP`). -* **`zephyr-udp`**: Native **Zephyr Networking** (BSD Socket API) implementation for Zephyr RTOS. - -### IPC & Serial -* **`win32-pipe`**: Inter-Process Communication (IPC) using Windows Named Pipes. -* **`linux-uds`**: Inter-Process Communication (IPC) using Linux Unix domain datagram sockets (`AF_UNIX`, `SOCK_DGRAM`). Duplex, path-addressed, no start-order dependency. A stale socket file left by a crashed process is reused; a path still bound by a live process makes `Create()` fail. Socket access follows the directory's permissions, so prefer a per-user directory such as `$XDG_RUNTIME_DIR` over `/tmp` when other local users must not be able to send. Selected via `DMQ_TRANSPORT_LINUX_UDS`. -* **`serial`**: Serial port (UART/RS-232) transport using **libserialport**. -* **`stm32-uart`**: Interrupt-driven STM32 HAL UART transport for embedded targets (selected via `DMQ_TRANSPORT_STM32_UART`). - -## Usage - -To use a specific transport, simply include the corresponding header in your application and inject it into your `dmq::Dispatcher` or `dmq::DelegateRemote`. - -```cpp -// Example: Using UDP on Windows -#include "port/transport/win32-udp/Win32UdpTransport.h" - -dmq::transport::Win32UdpTransport transport; -transport.Create(dmq::transport::Win32UdpTransport::Type::PUB, "127.0.0.1", 5000); - -// Link transport to the dispatcher -dispatcher.SetTransport(&transport); -``` diff --git a/DelegateMQ/port/transport/arm-lwip-netconn-udp/ArmLwipNetconnUdpTransport.h b/DelegateMQ/port/transport/arm-lwip-netconn-udp/ArmLwipNetconnUdpTransport.h deleted file mode 100644 index 8423fc9..0000000 --- a/DelegateMQ/port/transport/arm-lwip-netconn-udp/ArmLwipNetconnUdpTransport.h +++ /dev/null @@ -1,278 +0,0 @@ -#ifndef ARM_LWIP_NETCONN_UDP_TRANSPORT_H -#define ARM_LWIP_NETCONN_UDP_TRANSPORT_H - -/// @file ArmLwipNetconnUdpTransport.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief ARM lwIP Netconn UDP transport implementation for DelegateMQ. -/// -/// @details -/// This class implements the ITransport interface using the lwIP "Netconn" API. -/// This API is specific to lwIP+FreeRTOS and is more efficient than the BSD -/// Socket API as it avoids the socket wrapper overhead. -/// -/// Prerequisites: -/// - lwIP must be compiled with `LWIP_NETCONN=1` -/// - FreeRTOS must be running (Netconn relies on OS primitives) - -#include "delegate/DelegateOpt.h" -#include "port/transport/common/ITransport.h" -#include "port/transport/common/DmqHeader.h" -#include "port/transport/common/ITransportMonitor.h" - - -// lwIP Netconn Includes -#include "lwip/api.h" -#include "lwip/inet.h" -#include "lwip/ip_addr.h" - -#include -#include - -namespace dmq::transport { - -class NetconnUdpTransport : public ITransport -{ -public: - enum class Type - { - PUB, - SUB - }; - - NetconnUdpTransport() : m_sendTransport(this), m_recvTransport(this) - { - } - - ~NetconnUdpTransport() - { - Close(); - } - - /// Initialize the Netconn UDP connection - /// @param type PUB or SUB - /// @param addr Target IP string (e.g. "192.168.1.50") for PUB; Ignored for SUB. - /// @param port Local port to bind (SUB) or Remote port to target (PUB). - /// @return 0 on success, -1 on failure - int Create(Type type, const char* addr, uint16_t port) - { - const dmq::LockGuard recvLock(m_recvMutex); - const dmq::LockGuard lock(m_mutex); - Close(); // a second Create() replaces the connection instead of leaking it - m_type = type; - m_remotePort = port; - - // 1. Create a new UDP connection - m_conn = netconn_new(NETCONN_UDP); - if (m_conn == nullptr) - { - return -1; - } - - // 2. Configure Address - if (type == Type::PUB) - { - // Parse string IP to LwIP ip_addr_t - if (ipaddr_aton(addr, &m_remoteIp) == 0) - { - Close(); // Prevent memory leak on invalid IP - return -1; - } - netconn_set_recvtimeout(m_conn, static_cast(dmq::UDP_PUB_RECV_TIMEOUT.count())); - } - else if (type == Type::SUB) - { - // Bind to all interfaces (IP_ADDR_ANY) on the specified port - if (netconn_bind(m_conn, IP_ADDR_ANY, port) != ERR_OK) - { - Close(); // Prevent memory leak on bind failure - return -1; - } - // Receive timeout, so the receive thread can check for exit - netconn_set_recvtimeout(m_conn, static_cast(dmq::UDP_SUB_RECV_TIMEOUT.count())); - } - - return 0; - } - - /// Clean up the netconn resources. Waits for a Receive() in progress on - /// another thread to return (at most its receive timeout) first. - void Close() - { - const dmq::LockGuard recvLock(m_recvMutex); - const dmq::LockGuard lock(m_mutex); - if (m_conn) - { - netconn_delete(m_conn); - m_conn = nullptr; - } - } - - void SetRecvTimeout(std::chrono::milliseconds timeout) - { - const dmq::LockGuard lock(m_mutex); - if (m_conn) - { - netconn_set_recvtimeout(m_conn, static_cast(timeout.count())); - } - } - - virtual int Send(xostringstream& os, const DmqHeader& header) override - { - const dmq::LockGuard lock(m_mutex); - if (os.bad() || os.fail() || !m_conn) { - return -1; - } - - // Only SUBs should block non-ACK traffic - if (m_type == Type::SUB && header.GetId() != dmq::ACK_REMOTE_ID) { - return -1; - } - - if (m_sendTransport != this) { - return -1; - } - - // Get payload data without string copy if possible - auto payload = os.str(); - if (payload.length() > (BUFFER_SIZE - DmqHeader::HEADER_SIZE)) { - return -1; - } - uint16_t payloadLen = static_cast(payload.length()); - - // Prepare header values in Network Byte Order - DmqHeader wireHeader = header; - wireHeader.SetLength(payloadLen); - wireHeader.Encode(m_sendBuffer); - - if (payloadLen > 0) { - memcpy(m_sendBuffer + DmqHeader::HEADER_SIZE, payload.data(), payloadLen); - } - - // Allocate a Netbuf - struct netbuf* buf = netbuf_new(); - if (!buf) return -1; - - void* dataPtr = netbuf_alloc(buf, DmqHeader::HEADER_SIZE + payloadLen); - if (!dataPtr) { - netbuf_delete(buf); - return -1; - } - - // Copy to NetX/LwIP internal buffer - memcpy(dataPtr, m_sendBuffer, DmqHeader::HEADER_SIZE + payloadLen); - - // PUB uses pre-configured IP; SUB uses last-received IP (Reply) - err_t err = netconn_sendto(m_conn, buf, &m_remoteIp, m_remotePort); - - netbuf_delete(buf); - - if (err != ERR_OK) return -1; - - return 0; - } - - virtual int Receive(xstringstream& is, DmqHeader& header) override - { - // m_recvMutex, not m_mutex: a Send() on another thread (e.g. a PUB that - // also drains its ACKs here) isn't held up for the receive timeout. - const dmq::LockGuard recvLock(m_recvMutex); - if (m_recvTransport != this || !m_conn) { - return -1; - } - - struct netbuf* buf = nullptr; - err_t err = netconn_recv(m_conn, &buf); - - if (err == ERR_TIMEOUT) return RECEIVE_NO_DATA; - if (err != ERR_OK || buf == nullptr) return -1; - - uint16_t len = netbuf_len(buf); - if (len < DmqHeader::HEADER_SIZE) { - netbuf_delete(buf); - return -1; - } - - // Read Header (Network Byte Order) - char headerBuf[DmqHeader::HEADER_SIZE]; - netbuf_copy(buf, headerBuf, DmqHeader::HEADER_SIZE); - - header.Decode(headerBuf); - - // One datagram is one message: the header length must match exactly - // and fit the buffer. Anything else is malformed and must not be - // delivered (cut short) or ACKed. - const uint16_t payloadSize = header.GetLength(); - if (!header.IsValid() || len != DmqHeader::HEADER_SIZE + payloadSize || - payloadSize > BUFFER_SIZE) { - netbuf_delete(buf); - return -1; - } - - // A SUB replies to whoever sent the last valid message. Only a SUB, and - // only now: a stray or malformed datagram must never redirect where a - // PUB sends. - if (m_type == Type::SUB) { - const dmq::LockGuard lock(m_mutex); - ip_addr_t* addr = netbuf_fromaddr(buf); - if (addr) ip_addr_copy(m_remoteIp, *addr); - m_remotePort = netbuf_fromport(buf); - } - - // Extract Payload - if (payloadSize > 0) { - netbuf_copy_partial(buf, m_recvBuffer, payloadSize, DmqHeader::HEADER_SIZE); - is.clear(); - is.str(""); - is.write(m_recvBuffer, payloadSize); - } - - netbuf_delete(buf); - - // Handle Reliability Logic - if (header.GetId() == dmq::ACK_REMOTE_ID) { - if (m_transportMonitor) m_transportMonitor->Remove(header.GetSeqNum()); - } - // ACK whenever a send path exists, whether or not this transport also - // tracks its own sends: a receive-only transport (e.g. NetworkNode's SUB) - // has no monitor but must still ACK the sender's RELIABLE messages. - else if (m_sendTransport) { - // Auto-ACK using Send logic - dmq::xostringstream ss_ack; - DmqHeader ack; - ack.SetId(dmq::ACK_REMOTE_ID); - ack.SetSeqNum(header.GetSeqNum()); - ack.SetLength(0); - m_sendTransport->Send(ss_ack, ack); - } - - return 0; - } - - void SetTransportMonitor(ITransportMonitor* monitor) { m_transportMonitor = monitor; } - void SetSendTransport(ITransport* transport) { m_sendTransport = transport; } - void SetRecvTransport(ITransport* transport) { m_recvTransport = transport; } - -private: - struct netconn* m_conn = nullptr; - ip_addr_t m_remoteIp{}; - uint16_t m_remotePort = 0; - Type m_type = Type::PUB; - - ITransport* m_sendTransport = nullptr; - ITransport* m_recvTransport = nullptr; - ITransportMonitor* m_transportMonitor = nullptr; - - // Datagram buffer (header + payload): DMQ_UDP_BUFFER_SIZE, default the - // 1500-byte Ethernet MTU. - static constexpr size_t BUFFER_SIZE = dmq::UDP_BUFFER_SIZE; - char m_recvBuffer[BUFFER_SIZE] = { 0 }; - char m_sendBuffer[BUFFER_SIZE] = { 0 }; - dmq::RecursiveMutex m_mutex; ///< Connection open/close and Send() state (remote address) - dmq::RecursiveMutex m_recvMutex; ///< Held by Receive(); taken before m_mutex -}; - -} - -#endif // ARM_LWIP_NETCONN_UDP_TRANSPORT_H \ No newline at end of file diff --git a/DelegateMQ/port/transport/arm-lwip-udp/ArmLwipUdpTransport.h b/DelegateMQ/port/transport/arm-lwip-udp/ArmLwipUdpTransport.h deleted file mode 100644 index 1e38785..0000000 --- a/DelegateMQ/port/transport/arm-lwip-udp/ArmLwipUdpTransport.h +++ /dev/null @@ -1,297 +0,0 @@ -#ifndef ARM_LWIP_UDP_TRANSPORT_H -#define ARM_LWIP_UDP_TRANSPORT_H - -/// @file ArmLwipUdpTransport.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief ARM lwIP UDP transport implementation for DelegateMQ. -/// -/// @details -/// This class implements the ITransport interface using the lwIP (Lightweight IP) -/// BSD-style socket API. It is designed for embedded ARM targets running FreeRTOS -/// (or similar) with the lwIP stack. -/// -/// Prerequisites: -/// - lwIP must be compiled with `LWIP_SOCKET=1` -/// - lwIP must be compiled with `LWIP_SO_RCVTIMEO=1` (for non-blocking timeouts) - -#include "delegate/DelegateOpt.h" -#include "port/transport/common/ITransport.h" -#include "port/transport/common/DmqHeader.h" -#include "port/transport/common/ITransportMonitor.h" - -// lwIP Includes -#include "lwip/sockets.h" -#include "lwip/inet.h" -#include "lwip/sys.h" -#include "lwip/api.h" - -#include -#include -#include - -// Ensure lwIP is configured correctly -#if !defined(LWIP_SO_RCVTIMEO) || LWIP_SO_RCVTIMEO == 0 - #error "ArmLwipUdpTransport requires LWIP_SO_RCVTIMEO=1 in lwipopts.h" -#endif - -namespace dmq::transport { - -class UdpTransport : public ITransport -{ -public: - enum class Type - { - PUB, - SUB - }; - - UdpTransport() : m_sendTransport(this), m_recvTransport(this) - { - } - - ~UdpTransport() - { - Close(); - } - - int Create(Type type, const char* addr, uint16_t port) - { - const dmq::LockGuard recvLock(m_recvMutex); - const dmq::LockGuard lock(m_mutex); - Close(); // a second Create() replaces the socket instead of leaking it - m_type = type; - - // Create lwIP UDP socket - m_socket = lwip_socket(AF_INET, SOCK_DGRAM, 0); - if (m_socket < 0) - { - return -1; - } - - memset(&m_addr, 0, sizeof(m_addr)); - m_addr.sin_family = AF_INET; - m_addr.sin_port = htons(port); - - if (type == Type::PUB) - { - // Note: inet_aton in lwIP returns 1 on success - if (inet_aton(addr, &m_addr.sin_addr) == 0) - { - Close(); - return -1; - } - - // Short timeout so polling this socket for ACKs doesn't hang. - struct timeval timeout = ToTimeval(dmq::UDP_PUB_RECV_TIMEOUT); - - if (lwip_setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) < 0) - { - Close(); - return -1; - } - } - else if (type == Type::SUB) - { - m_addr.sin_addr.s_addr = INADDR_ANY; - - if (lwip_bind(m_socket, (struct sockaddr*)&m_addr, sizeof(m_addr)) < 0) - { - Close(); - return -1; - } - - // Receive timeout, so the receive thread can check for exit - struct timeval timeout = ToTimeval(dmq::UDP_SUB_RECV_TIMEOUT); - - if (lwip_setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) < 0) - { - Close(); - return -1; - } - } - - return 0; - } - - /// @details Waits for a Receive() in progress on another thread to return - /// (at most its receive timeout) before closing, so the socket is never - /// closed under it. - void Close() - { - const dmq::LockGuard recvLock(m_recvMutex); - const dmq::LockGuard lock(m_mutex); - if (m_socket >= 0) - { - lwip_close(m_socket); - m_socket = -1; - } - } - - virtual int Send(xostringstream& os, const DmqHeader& header) override - { - const dmq::LockGuard lock(m_mutex); - if (os.bad() || os.fail() || m_socket < 0) { - return -1; - } - - // Allow ACKs on SUB sockets. Block only regular data. - if (m_type == Type::SUB && header.GetId() != dmq::ACK_REMOTE_ID) { - return -1; - } - - if (m_sendTransport != this) { - return -1; - } - - // Get payload and set length on the copy - auto payload = os.str(); - if (payload.length() > (BUFFER_SIZE - DmqHeader::HEADER_SIZE)) { - return -1; - } - uint16_t payloadLen = static_cast(payload.length()); - - // Convert header fields to Network Byte Order (Big Endian) - DmqHeader wireHeader = header; - wireHeader.SetLength(payloadLen); - wireHeader.Encode(m_sendBuffer); - - if (payloadLen > 0) { - memcpy(m_sendBuffer + DmqHeader::HEADER_SIZE, payload.data(), payloadLen); - } - - size_t totalSize = DmqHeader::HEADER_SIZE + payloadLen; - - ssize_t sent = lwip_sendto(m_socket, m_sendBuffer, totalSize, 0, - (struct sockaddr*)&m_addr, sizeof(m_addr)); - - if (sent != (ssize_t)totalSize) return -1; - - return 0; - } - - virtual int Receive(xstringstream& is, DmqHeader& header) override - { - // m_recvMutex, not m_mutex: a Send() on another thread (e.g. a PUB socket - // that also drains its ACKs here) isn't held up for the receive timeout. - const dmq::LockGuard recvLock(m_recvMutex); - if (m_recvTransport != this || m_socket < 0) { - return -1; - } - - sockaddr_in fromAddr; - socklen_t addrLen = sizeof(fromAddr); - - // lwip_recvfrom - ssize_t size = lwip_recvfrom(m_socket, m_buffer, sizeof(m_buffer), 0, - (struct sockaddr*)&fromAddr, &addrLen); - - if (size < 0) - { - // Explicit check for timeout vs real error - if (errno == EWOULDBLOCK || errno == EAGAIN) - return RECEIVE_NO_DATA; - - // Real socket error - return -1; - } - - if (static_cast(size) < DmqHeader::HEADER_SIZE) { // size >= 0 here (checked above) - return -1; - } - - // 1. Read Header (Network Byte Order) - header.Decode(m_buffer); - - if (!header.IsValid()) - { - return -1; // Sync marker mismatch - } - - // 2. Extract Payload. One datagram is one message, so the header length - // must match exactly; anything else (including a datagram cut short by - // the buffer) is malformed and must not be delivered or ACKed. - uint16_t payloadSize = header.GetLength(); - if (payloadSize != static_cast(size) - DmqHeader::HEADER_SIZE) - return -1; - - // Update m_addr to the sender's address so we can ACK back. Only after - // validation, and under m_mutex since Send() uses it. - if (m_type == Type::SUB) { - const dmq::LockGuard lock(m_mutex); - m_addr = fromAddr; - } - - if (payloadSize > 0) { - is.clear(); - is.str(""); - is.write(m_buffer + DmqHeader::HEADER_SIZE, payloadSize); - } - - if (header.GetId() == dmq::ACK_REMOTE_ID) - { - if (m_transportMonitor) - m_transportMonitor->Remove(header.GetSeqNum()); - } - // ACK whenever a send path exists, whether or not this transport also - // tracks its own sends: a receive-only transport (e.g. NetworkNode's SUB) - // has no monitor but must still ACK the sender's RELIABLE messages. - else if (m_sendTransport) - { - // Send ACK back using Send logic (recursive mutex handles it) - xostringstream ss_ack; - DmqHeader ack; - ack.SetId(dmq::ACK_REMOTE_ID); - ack.SetSeqNum(header.GetSeqNum()); - ack.SetLength(0); - m_sendTransport->Send(ss_ack, ack); - } - - return 0; - } - - void SetTransportMonitor(ITransportMonitor* transportMonitor) - { - m_transportMonitor = transportMonitor; - } - - void SetSendTransport(ITransport* sendTransport) - { - m_sendTransport = sendTransport; - } - - void SetRecvTransport(ITransport* recvTransport) - { - m_recvTransport = recvTransport; - } - -private: - int m_socket = -1; - sockaddr_in m_addr{}; - Type m_type = Type::PUB; - - ITransport* m_sendTransport = nullptr; - ITransport* m_recvTransport = nullptr; - ITransportMonitor* m_transportMonitor = nullptr; - - static struct timeval ToTimeval(std::chrono::milliseconds ms) - { - struct timeval tv; - tv.tv_sec = static_cast(ms.count() / 1000); - tv.tv_usec = static_cast((ms.count() % 1000) * 1000); - return tv; - } - - // Datagram buffer (header + payload): DMQ_UDP_BUFFER_SIZE, default the - // 1500-byte Ethernet MTU. - static constexpr size_t BUFFER_SIZE = dmq::UDP_BUFFER_SIZE; - char m_buffer[BUFFER_SIZE] = { 0 }; - char m_sendBuffer[BUFFER_SIZE] = { 0 }; - dmq::RecursiveMutex m_mutex; ///< Socket open/close and Send() state (m_addr) - dmq::RecursiveMutex m_recvMutex; ///< Held by Receive(); taken before m_mutex -}; - -} - -#endif // ARM_LWIP_UDP_TRANSPORT_H \ No newline at end of file diff --git a/DelegateMQ/port/transport/common/DmqHeader.h b/DelegateMQ/port/transport/common/DmqHeader.h deleted file mode 100644 index a2ef56d..0000000 --- a/DelegateMQ/port/transport/common/DmqHeader.h +++ /dev/null @@ -1,130 +0,0 @@ -#ifndef DMQ_HEADER_H -#define DMQ_HEADER_H - -/// @file -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. - -#include "delegate/DelegateOpt.h" -#include -#include -#include - -namespace dmq::transport { - -/// @brief Header for remote delegate messages. -/// @details Stores values in host byte order. On the wire it is 10 bytes, every -/// multi-byte field big-endian (network byte order): -/// -/// | Offset | Size | Field | Notes | -/// |--------|------|----------|----------------------------------------------------| -/// | 0 | 2 | marker | Always `MARKER` (0xAA55). Frame check. | -/// | 2 | 1 | nodeId | Sender's node ID. 0 = unset. | -/// | 3 | 1 | version | Wire protocol version, `VERSION`. | -/// | 4 | 2 | id | DelegateRemoteId. `ACK_REMOTE_ID` (0) for an ACK. | -/// | 6 | 2 | seqNum | Sender's sequence number. | -/// | 8 | 2 | length | Payload bytes following the header. | -/// -/// Transports write and read the header with `Encode()`/`Decode()` and check it -/// with `IsValid()`, so the layout lives only here. -class DmqHeader -{ -public: - /// Frame marker (10101010 01010101). - static constexpr uint16_t MARKER = 0xAA55; - - /// Wire protocol version this build sends and accepts. - static constexpr uint8_t VERSION = 1; - - /// Encoded header size in bytes. - static constexpr size_t HEADER_SIZE = 10; - - DmqHeader() = default; - DmqHeader(uint16_t id, uint16_t seqNum, uint16_t length = 0) - : m_id(id), m_seqNum(seqNum), m_length(length) { - } - - // --- Getters (host byte order) --- - - uint16_t GetMarker() const { return m_marker; } - uint8_t GetNodeId() const { return m_nodeId; } - uint8_t GetVersion() const { return m_version; } - uint16_t GetId() const { return m_id; } - uint16_t GetSeqNum() const { return m_seqNum; } - uint16_t GetLength() const { return m_length; } - - // --- Setters (host byte order) --- - - void SetMarker(uint16_t marker) { m_marker = marker; } - void SetNodeId(uint8_t nodeId) { m_nodeId = nodeId; } - void SetVersion(uint8_t version) { m_version = version; } - void SetId(uint16_t id) { m_id = id; } - void SetSeqNum(uint16_t seqNum) { m_seqNum = seqNum; } - void SetLength(uint16_t length) { m_length = length; } - - /// @brief True if the marker matches. False means garbage or lost framing. - bool HasValidMarker() const { return m_marker == MARKER; } - - /// @brief True if the marker and protocol version both match. A valid marker - /// with another version is a well-formed frame from an incompatible peer. - bool IsValid() const { return m_marker == MARKER && m_version == VERSION; } - - /// @brief Write the header to `buf` in wire format. - /// @param[out] buf At least HEADER_SIZE bytes. - void Encode(void* buf) const { - uint8_t* p = static_cast(buf); - Put16(p + 0, m_marker); - p[2] = m_nodeId; - p[3] = m_version; - Put16(p + 4, m_id); - Put16(p + 6, m_seqNum); - Put16(p + 8, m_length); - } - - /// @brief Read a header from `buf` in wire format. Doesn't validate it; - /// call IsValid() afterwards. - /// @param[in] buf At least HEADER_SIZE bytes. - void Decode(const void* buf) { - const uint8_t* p = static_cast(buf); - m_marker = Get16(p + 0); - m_nodeId = p[2]; - m_version = p[3]; - m_id = Get16(p + 4); - m_seqNum = Get16(p + 6); - m_length = Get16(p + 8); - } - - /// @brief This process's node ID, stamped into every header it creates. - /// Defaults to dmq::NODE_ID (DMQ_NODE_ID). - static uint8_t GetLocalNodeId() { return LocalNodeId().load(std::memory_order_relaxed); } - - /// @brief Set this process's node ID (1-255, 0 = unset). Call once at - /// startup, before any messages are sent. - static void SetLocalNodeId(uint8_t nodeId) { LocalNodeId().store(nodeId, std::memory_order_relaxed); } - -private: - static std::atomic& LocalNodeId() { - static std::atomic nodeId{ dmq::NODE_ID }; - return nodeId; - } - - static void Put16(uint8_t* p, uint16_t v) { - p[0] = static_cast(v >> 8); - p[1] = static_cast(v); - } - static uint16_t Get16(const uint8_t* p) { - return static_cast((static_cast(p[0]) << 8) | p[1]); - } - - uint16_t m_marker = MARKER; - uint8_t m_nodeId = GetLocalNodeId(); - uint8_t m_version = VERSION; - uint16_t m_id = 0; // DelegateRemoteId - uint16_t m_seqNum = 0; - uint16_t m_length = 0; // Payload length -}; - -} // namespace dmq::transport - - -#endif diff --git a/DelegateMQ/port/transport/common/ITransport.h b/DelegateMQ/port/transport/common/ITransport.h deleted file mode 100644 index 3f67a2e..0000000 --- a/DelegateMQ/port/transport/common/ITransport.h +++ /dev/null @@ -1,37 +0,0 @@ -#ifndef ITRANSPORT_H -#define ITRANSPORT_H - -#include "DmqHeader.h" -#include "../../../delegate/DelegateOpt.h" - -namespace dmq::transport { - -/// @TODO Implement the ITransport interface if necessary. -/// @brief DelegateMQ transport interface. -class ITransport -{ -public: - virtual ~ITransport() = default; - /// Send data to a remote - /// @param[in] os Output stream to send. - /// @param[in] header The header to send. - /// @return 0 if success. - virtual int Send(dmq::xostringstream& os, const DmqHeader& header) = 0; - - /// Returned by Receive() when nothing arrived within the transport's receive - /// timeout (or, for a non-blocking transport, nothing was waiting). Not an - /// error: callers poll again. - static constexpr int RECEIVE_NO_DATA = 1; - - /// Receive data from a remote - /// @param[out] is The received incoming data bytes, not including the header. - /// @param[out] header Incoming delegate message header. - /// @return 0 if a message was received, RECEIVE_NO_DATA if nothing arrived, - /// or a negative value on error (socket failure, malformed or truncated frame). - virtual int Receive(dmq::xstringstream& is, DmqHeader& header) = 0; -}; - -} // namespace dmq::transport - - -#endif \ No newline at end of file diff --git a/DelegateMQ/port/transport/common/ITransportMonitor.h b/DelegateMQ/port/transport/common/ITransportMonitor.h deleted file mode 100644 index 642d937..0000000 --- a/DelegateMQ/port/transport/common/ITransportMonitor.h +++ /dev/null @@ -1,29 +0,0 @@ -#ifndef ITRANSPORT_MONITOR_H -#define ITRANSPORT_MONITOR_H - -//#include "DmqHeader.h" -//#include - -namespace dmq::transport { - -/// @TODO Implement the ITransportMonitor interface if necessary. -/// @brief DelegateMQ transport monitor interface. -class ITransportMonitor -{ -public: - virtual ~ITransportMonitor() = default; - /// Add a sequence number - /// param[in] seqNum - the message sequence number - /// param[in] remoteId - the remote ID - /// @return true if added; false otherwise. - virtual bool Add(uint16_t seqNum, dmq::DelegateRemoteId remoteId) = 0; - - /// Remove a sequence number - /// param[in] seqNum - the message sequence number - virtual void Remove(uint16_t seqNum) = 0; -}; - -} // namespace dmq::transport - - -#endif \ No newline at end of file diff --git a/DelegateMQ/port/transport/linux-tcp/LinuxTcpTransport.h b/DelegateMQ/port/transport/linux-tcp/LinuxTcpTransport.h deleted file mode 100644 index 61a59d1..0000000 --- a/DelegateMQ/port/transport/linux-tcp/LinuxTcpTransport.h +++ /dev/null @@ -1,386 +0,0 @@ -#ifndef LINUX_TCP_TRANSPORT_H -#define LINUX_TCP_TRANSPORT_H - -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// @brief Linux TCP transport implementation for DelegateMQ. -/// -/// @details -/// This class implements the ITransport interface using standard Linux BSD sockets. -/// It supports both CLIENT and SERVER modes for reliable, stream-based communication. -/// In SERVER mode, it supports multiple simultaneous client connections and broadcasts -/// outgoing messages to all connected participants. -/// -/// Key Features: -/// 1. **Thread-Safe I/O**: Executes socket operations directly on the calling thread, -/// relying on OS-level thread safety for concurrent Send/Receive operations. -/// 2. **Low Latency**: Configures `TCP_NODELAY` to disable Nagle's algorithm, optimized -/// for the small, frequent packets typical of RPC/delegate calls. -/// 3. **Non-Blocking Poll**: Utilizes `select()` in the receive loop to prevent -/// thread blocking when no data is available, facilitating clean shutdowns. -/// 4. **Multi-Client Multiplexing**: SERVER mode manages a list of clients and -/// polls them for data using `select()`. -/// 5. **Reliability**: Fully integrated with `TransportMonitor` to handle sequence -/// tracking and ACK generation. -/// -/// @note This class is specific to Linux and uses POSIX socket APIs. - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "delegate/DelegateOpt.h" -#include "port/transport/common/ITransport.h" -#include "port/transport/common/DmqHeader.h" -#include "port/transport/common/ITransportMonitor.h" - -namespace dmq::transport { - -/// @brief A TCP transport implementation for Linux using BSD sockets. -class LinuxTcpTransport : public ITransport -{ - XALLOCATOR -public: - enum class Type { SERVER, CLIENT }; - - LinuxTcpTransport() : m_sendTransport(this), m_recvTransport(this) - { - } - - ~LinuxTcpTransport() { Close(); } - - /// @brief Create a TCP transport. - /// @param type SERVER or CLIENT. - /// @param addr The IP address string. - /// @param port The TCP port. - /// @return 0 on success, -1 on failure. - int Create(Type type, const char* addr, uint16_t port) - { - Close(); // a second Create() replaces the sockets instead of leaking them - m_type = type; - m_socket = socket(AF_INET, SOCK_STREAM, 0); - if (m_socket < 0) return -1; - - // Set TCP_NODELAY to disable Nagle's algorithm for low-latency RPC - int flag = 1; - setsockopt(m_socket, IPPROTO_TCP, TCP_NODELAY, (char*)&flag, sizeof(int)); - - sockaddr_in srv_addr{}; - srv_addr.sin_family = AF_INET; - srv_addr.sin_port = htons(port); - inet_aton(addr, &srv_addr.sin_addr); - - if (type == Type::SERVER) { - int opt = 1; - setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); - if (bind(m_socket, (struct sockaddr*)&srv_addr, sizeof(srv_addr)) < 0) { Close(); return -1; } - if (listen(m_socket, 5) < 0) { Close(); return -1; } - } - else { - if (connect(m_socket, (struct sockaddr*)&srv_addr, sizeof(srv_addr)) < 0) { Close(); return -1; } - m_connFd = m_socket; - - struct timeval tv; - tv.tv_sec = 2; tv.tv_usec = 0; - setsockopt(m_connFd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof(tv)); - } - - return 0; - } - - /// @brief Close all sockets and clean up. - void Close() - { - // m_mutex: Receive() may close the client socket on another thread - const std::lock_guard lock(m_mutex); - - // Close Connected Socket - if (m_connFd >= 0) - { - shutdown(m_connFd, SHUT_RDWR); - if (m_connFd != m_socket) - { - close(m_connFd); - } - } - - // Close all server-accepted clients - { - for (auto s : m_serverClients) { - shutdown(s, SHUT_RDWR); - close(s); - } - m_serverClients.clear(); - } - - // Close Listen Socket - if (m_socket >= 0) - { - shutdown(m_socket, SHUT_RDWR); - close(m_socket); - } - - m_connFd = m_socket = -1; - } - - /// @brief Set the receive timeout for all active sockets. - void SetRecvTimeout(std::chrono::milliseconds timeout) - { - m_recvTimeout = timeout; - struct timeval tv; - tv.tv_sec = timeout.count() / 1000; - tv.tv_usec = (timeout.count() % 1000) * 1000; - - if (m_connFd >= 0) - { - setsockopt(m_connFd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); - } - - const std::lock_guard lock(m_mutex); - for (auto s : m_serverClients) { - setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); - } - } - - /// @brief Send data over the TCP link. - /// @details In SERVER mode, this broadcasts to all connected clients. - virtual int Send(xostringstream& os, const DmqHeader& header) override - { - // m_mutex guards m_sendBuffer and keeps frames from different threads - // (including ACKs written by Receive()) from interleaving on the stream. - const std::lock_guard lock(m_mutex); - if (m_type == Type::CLIENT) { - return SendToSocket(m_connFd, os, header); - } else { - int lastErr = 0; - for (auto fd : m_serverClients) { - if (SendToSocket(fd, os, header) != 0) lastErr = -1; - } - return lastErr; - } - } - - /// @brief Receive data from the TCP link. - virtual int Receive(xstringstream& is, DmqHeader& header) override - { - if (m_type == Type::SERVER) { - return ReceiveServer(is, header); - } else { - if (m_connFd < 0) { - // The connection was dropped (see below). Wait out one receive - // timeout before reporting it again, so a caller polling in a - // tight loop (RemoteDispatcher's receive thread) doesn't spin. - std::this_thread::sleep_for(m_recvTimeout); - return -1; - } - int result = ReceiveSocket(m_connFd, is, header); - if (result == -2) { - // Disconnected, or the stream lost framing (bad header, partial - // frame). Either way nothing more on it can be trusted. Close it: - // a shut-down but still open socket stays readable at EOF, so the - // next select() would return at once and the caller would spin. - const std::lock_guard lock(m_mutex); - if (m_connFd >= 0) { - shutdown(m_connFd, SHUT_RDWR); - close(m_connFd); - m_connFd = m_socket = -1; - } - } - return result; - } - } - - void SetTransportMonitor(ITransportMonitor* tm) { - m_transportMonitor = tm; - } - void SetSendTransport(ITransport* st) { - m_sendTransport = st; - } - void SetRecvTransport(ITransport* rt) { - m_recvTransport = rt; - } - -private: - /// @brief Internal helper to send to a specific socket. - int SendToSocket(int fd, xostringstream& os, const DmqHeader& header) { - if (fd < 0) return -1; - - // Get payload data without string copy if possible - auto payload = os.str(); - if (payload.length() > (BUFFER_SIZE - DmqHeader::HEADER_SIZE)) { - std::cerr << "Error: Payload too large for static buffer." << std::endl; - return -1; - } - uint16_t payloadLen = static_cast(payload.length()); - - // Prepare header values in Network Byte Order - DmqHeader wireHeader = header; - wireHeader.SetLength(payloadLen); - wireHeader.Encode(m_sendBuffer); - - // Copy payload after header - if (payloadLen > 0) { - memcpy(m_sendBuffer + DmqHeader::HEADER_SIZE, payload.data(), payloadLen); - } - - size_t totalSize = DmqHeader::HEADER_SIZE + payloadLen; - - return WriteAll(fd, m_sendBuffer, totalSize) ? 0 : -1; - } - - /// @brief Internal helper to handle server-side multiplexing. - int ReceiveServer(xstringstream& is, DmqHeader& header) { - // 1. Lazy Accept: Check for new client connections - fd_set fds; - FD_ZERO(&fds); - FD_SET(m_socket, &fds); - struct timeval tv = { 0, 1000 }; // 1ms poll - - if (select(m_socket + 1, &fds, nullptr, nullptr, &tv) > 0) { - int client = accept(m_socket, nullptr, nullptr); - if (client >= 0) { - struct timeval t; - t.tv_sec = m_recvTimeout.count() / 1000; - t.tv_usec = (m_recvTimeout.count() % 1000) * 1000; - setsockopt(client, SOL_SOCKET, SO_RCVTIMEO, &t, sizeof(t)); - const std::lock_guard lock(m_mutex); - m_serverClients.push_back(client); - } - } - - // 2. Poll all connected clients for data - fd_set readfds; - FD_ZERO(&readfds); - int max_fd = -1; - { - const std::lock_guard lock(m_mutex); - if (m_serverClients.empty()) return RECEIVE_NO_DATA; - for (auto s : m_serverClients) { - FD_SET(s, &readfds); - if (s > max_fd) max_fd = s; - } - } - - tv.tv_usec = 1000; // 1ms poll - if (select(max_fd + 1, &readfds, nullptr, nullptr, &tv) > 0) { - const std::lock_guard lock(m_mutex); - for (auto it = m_serverClients.begin(); it != m_serverClients.end(); ) { - if (FD_ISSET(*it, &readfds)) { - int result = ReceiveSocket(*it, is, header); - if (result == -2) { - // Disconnected, or lost framing (bad header): drop this client. - close(*it); - it = m_serverClients.erase(it); - continue; - } - return result; - } - ++it; - } - } - return RECEIVE_NO_DATA; - } - - /// @brief Internal helper to read from a specific socket and parse DMQ protocol. - int ReceiveSocket(int fd, xstringstream& is, DmqHeader& header) { - if (fd < 0) return -1; - - fd_set readfds; - FD_ZERO(&readfds); - FD_SET(fd, &readfds); - struct timeval tv = { 0, 1000 }; - int ready = select(fd + 1, &readfds, nullptr, nullptr, &tv); - if (ready == 0) return RECEIVE_NO_DATA; - if (ready < 0) return -1; - - // 1. Read Header - char headerBuf[DmqHeader::HEADER_SIZE]; - if (!ReadExact(fd, headerBuf, DmqHeader::HEADER_SIZE)) return -2; // Disconnected - - // Parse Header (Convert Network -> Host) - header.Decode(headerBuf); - - // A stream has no resync point: after a bad header (or a payload we - // can't hold and so can't skip), the next bytes aren't a header either. - // Report it like a disconnect (-2) so the connection is dropped. - if (!header.IsValid()) return -2; - - // 2. Read Payload - uint16_t payloadSize = header.GetLength(); - if (payloadSize > 0) { - if (payloadSize > BUFFER_SIZE) return -2; - if (!ReadExact(fd, m_recvBuffer, payloadSize)) return -2; - is.write(m_recvBuffer, payloadSize); - } - - // 3. Handle Acknowledgment - if (header.GetId() == dmq::ACK_REMOTE_ID) { - if (m_transportMonitor) m_transportMonitor->Remove(header.GetSeqNum()); - } - else if (m_sendTransport) { - // Send ACK using a small stack buffer - DmqHeader ack(dmq::ACK_REMOTE_ID, header.GetSeqNum()); - char ackBuf[DmqHeader::HEADER_SIZE]; - ack.Encode(ackBuf); - - const std::lock_guard lock(m_mutex); // don't interleave with Send() - (void)WriteAll(fd, ackBuf, DmqHeader::HEADER_SIZE); - } - return 0; - } - - /// @brief Write all 'len' bytes; a short write would otherwise leave half a - /// frame on the stream. - bool WriteAll(int fd, const char* buf, size_t len) - { - size_t total = 0; - while (total < len) { - ssize_t w = write(fd, buf + total, len - total); - if (w < 0 && errno == EINTR) continue; - if (w <= 0) return false; - total += static_cast(w); - } - return true; - } - - /// @brief Read exactly 'len' bytes from the socket. - bool ReadExact(int fd, char* buf, size_t len) - { - size_t total = 0; - while (total < len) { - ssize_t r = read(fd, buf + total, len - total); - if (r <= 0) return false; - total += r; - } - return true; - } - - int m_socket = -1; - int m_connFd = -1; - std::vector m_serverClients; - static const int BUFFER_SIZE = 4096; - char m_recvBuffer[BUFFER_SIZE] = { 0 }; - char m_sendBuffer[BUFFER_SIZE] = { 0 }; - std::chrono::milliseconds m_recvTimeout{2000}; - Type m_type = Type::SERVER; - - ITransport* m_sendTransport, * m_recvTransport; - ITransportMonitor* m_transportMonitor = nullptr; - dmq::RecursiveMutex m_mutex; -}; - -using TcpTransport = LinuxTcpTransport; - -} // namespace dmq::transport - -#endif // LINUX_TCP_TRANSPORT_H diff --git a/DelegateMQ/port/transport/linux-udp/LinuxUdpTransport.h b/DelegateMQ/port/transport/linux-udp/LinuxUdpTransport.h deleted file mode 100644 index 09fa757..0000000 --- a/DelegateMQ/port/transport/linux-udp/LinuxUdpTransport.h +++ /dev/null @@ -1,324 +0,0 @@ -#ifndef LINUX_UDP_TRANSPORT_H -#define LINUX_UDP_TRANSPORT_H - -/// @file LinuxUdpTransport.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// @brief Linux UDP transport implementation for DelegateMQ. -/// -/// @details -/// This class implements the ITransport interface using standard Linux BSD sockets -/// for connectionless UDP communication. It supports both PUB (Publisher/Sender) -/// and SUB (Subscriber/Receiver) modes. -/// -/// Key Features: -/// 1. **Direct Execution**: Executes socket operations directly on the calling thread, -/// relying on OS-level thread safety to avoid deadlocks. -/// 2. **Reliability Support**: Integrates with `TransportMonitor` to track outgoing -/// sequence numbers and process incoming ACKs to detect packet loss. -/// 3. **Non-Blocking I/O**: Configures socket receive timeouts (`SO_RCVTIMEO`) to -/// prevent indefinite blocking during polling loops. -/// 4. **Address Management**: Automatically updates the target address on the receiver -/// side to support reliable bidirectional ACKs. -/// -/// @note This class is specific to Linux and uses POSIX socket APIs. - -#include "delegate/DelegateOpt.h" -#include "port/transport/common/ITransport.h" -#include "port/transport/common/DmqHeader.h" -#include "port/transport/common/ITransportMonitor.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace dmq::transport { - -// Linux UDP transport example -class LinuxUdpTransport : public ITransport -{ - XALLOCATOR -public: - enum class Type - { - PUB, - SUB - }; - - LinuxUdpTransport() : m_sendTransport(this), m_recvTransport(this) - { - } - - ~LinuxUdpTransport() - { - Close(); - } - - int Create(Type type, const char* addr, uint16_t port) - { - const std::lock_guard recvLock(m_recvMutex); - const std::lock_guard lock(m_mutex); - Close(); // a second Create() replaces the socket instead of leaking it - m_type = type; - - // Create UDP socket - m_socket = socket(AF_INET, SOCK_DGRAM, 0); - if (m_socket < 0) - { - std::cerr << "Socket creation failed: " << strerror(errno) << std::endl; - return -1; - } - - int opt = 1; - setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); -#ifdef SO_REUSEPORT - setsockopt(m_socket, SOL_SOCKET, SO_REUSEPORT, &opt, sizeof(opt)); -#endif - - memset(&m_addr, 0, sizeof(m_addr)); - m_addr.sin_family = AF_INET; - m_addr.sin_port = htons(port); - - if (type == Type::PUB) - { - if (inet_aton(addr, &m_addr.sin_addr) == 0) - { - std::cerr << "Invalid IP address format." << std::endl; - Close(); - return -1; - } - - // Set a short timeout (e.g. 2ms) so Sender::Send() doesn't hang - // while polling for ACKs. - struct timeval timeout; - timeout.tv_sec = 0; - timeout.tv_usec = 2000; // 2ms - - if (setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) < 0) - { - std::cerr << "setsockopt(SO_RCVTIMEO) failed: " << strerror(errno) << std::endl; - Close(); - return -1; - } - } - else if (type == Type::SUB) - { - if (inet_aton(addr, &m_addr.sin_addr) == 0) - { - m_addr.sin_addr.s_addr = INADDR_ANY; - } - - if (bind(m_socket, (struct sockaddr*)&m_addr, sizeof(m_addr)) < 0) - { - std::cerr << "Bind failed: " << strerror(errno) << std::endl; - Close(); - return -1; - } - - struct timeval timeout; - timeout.tv_sec = 2; - timeout.tv_usec = 0; - - if (setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) < 0) - { - std::cerr << "setsockopt(SO_RCVTIMEO) failed: " << strerror(errno) << std::endl; - Close(); - return -1; - } - } - - return 0; - } - - /// @details Waits for a Receive() in progress on another thread to return - /// (at most its receive timeout) before closing, so the socket is never - /// closed under it. - void Close() - { - const std::lock_guard recvLock(m_recvMutex); - const std::lock_guard lock(m_mutex); - if (m_socket != -1) - { - shutdown(m_socket, SHUT_RDWR); - close(m_socket); - m_socket = -1; - } - } - - void SetRecvTimeout(std::chrono::milliseconds timeout) - { - const std::lock_guard lock(m_mutex); - if (m_socket != -1) - { - struct timeval tv; - tv.tv_sec = timeout.count() / 1000; - tv.tv_usec = (timeout.count() % 1000) * 1000; - setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); - } - } - - virtual int Send(xostringstream& os, const DmqHeader& header) override - { - const std::lock_guard lock(m_mutex); - // Allow ACKs on SUB sockets. Block only regular data. - if (m_type == Type::SUB && header.GetId() != dmq::ACK_REMOTE_ID) { - std::cerr << "Send operation not allowed on SUB socket." << std::endl; - return -1; - } - - if (m_sendTransport != this) { - std::cerr << "Send operation not allowed (Receive only)." << std::endl; - return -1; - } - - // Get payload data without string copy if possible - // Note: os.str() still creates a copy. In a full zero-copy version, - // we would use a custom streambuf that points to m_sendBuffer. - auto payload = os.str(); - if (payload.length() > (BUFFER_SIZE - DmqHeader::HEADER_SIZE)) { - std::cerr << "Error: Payload too large for static buffer." << std::endl; - return -1; - } - uint16_t payloadLen = static_cast(payload.length()); - - // Prepare header values in Network Byte Order - DmqHeader wireHeader = header; - wireHeader.SetLength(payloadLen); - wireHeader.Encode(m_sendBuffer); - - // Copy payload after header - if (payloadLen > 0) { - memcpy(m_sendBuffer + DmqHeader::HEADER_SIZE, payload.data(), payloadLen); - } - - size_t totalSize = DmqHeader::HEADER_SIZE + payloadLen; - - ssize_t sent = sendto(m_socket, m_sendBuffer, totalSize, 0, - (struct sockaddr*)&m_addr, sizeof(m_addr)); - - if (sent != (ssize_t)totalSize) return -1; - - return 0; - } - - virtual int Receive(xstringstream& is, DmqHeader& header) override - { - // m_recvMutex, not m_mutex: a Send() on another thread (e.g. a PUB socket - // that also drains its ACKs here) isn't held up for the receive timeout. - const std::lock_guard recvLock(m_recvMutex); - if (m_recvTransport != this) { - std::cerr << "Receive operation not allowed (Send only)." << std::endl; - return -1; - } - if (m_socket == -1) - return -1; - - sockaddr_in fromAddr; - socklen_t addrLen = sizeof(fromAddr); - // MSG_TRUNC: return the datagram's real length, so one larger than the - // buffer is detected and dropped rather than delivered cut short. - ssize_t size = recvfrom(m_socket, m_buffer, sizeof(m_buffer), MSG_TRUNC, - (struct sockaddr*)&fromAddr, &addrLen); - - if (size < 0) - { - if (errno == EWOULDBLOCK || errno == EAGAIN) - return RECEIVE_NO_DATA; // Timeout - return -1; - } - - if (size < static_cast(DmqHeader::HEADER_SIZE) || - size > static_cast(sizeof(m_buffer))) { - return -1; // runt, or truncated - } - - // 1. Read Header directly from m_buffer (Network Byte Order) - header.Decode(m_buffer); - - if (!header.IsValid()) - { - return -1; - } - - // 2. Write payload to provided stream. One datagram is one message, so - // the header length must match exactly; anything else is malformed and - // must not be delivered or ACKed. - uint16_t payloadSize = header.GetLength(); - if (payloadSize != static_cast(size) - DmqHeader::HEADER_SIZE) - return -1; - - if (payloadSize > 0) { - is.write(m_buffer + DmqHeader::HEADER_SIZE, payloadSize); - } - - // 3. Handle ACKs and Metadata - if (header.GetId() == dmq::ACK_REMOTE_ID) - { - if (m_transportMonitor) - m_transportMonitor->Remove(header.GetSeqNum()); - } - else if (m_sendTransport && m_type == Type::SUB) - { - // Send ACK using a small stack buffer to avoid any heap - DmqHeader ack(dmq::ACK_REMOTE_ID, header.GetSeqNum()); - char ackBuf[DmqHeader::HEADER_SIZE]; - ack.Encode(ackBuf); - - // Use the subscriber's m_addr which was set by recvfrom if m_type == SUB - sockaddr_in targetAddr = (m_type == Type::SUB) ? fromAddr : m_addr; - - sendto(m_socket, ackBuf, DmqHeader::HEADER_SIZE, 0, - (struct sockaddr*)&targetAddr, sizeof(targetAddr)); - } - - return 0; - } - - void SetTransportMonitor(ITransportMonitor* transportMonitor) - { - m_transportMonitor = transportMonitor; - } - - void SetSendTransport(ITransport* sendTransport) - { - m_sendTransport = sendTransport; - } - - void SetRecvTransport(ITransport* recvTransport) - { - m_recvTransport = recvTransport; - } - -private: - int m_socket = -1; - sockaddr_in m_addr{}; - Type m_type = Type::PUB; - - ITransport* m_sendTransport = nullptr; - ITransport* m_recvTransport = nullptr; - ITransportMonitor* m_transportMonitor = nullptr; - - /// @note UDP datagrams larger than the network MTU (typically 1500 bytes) will be - /// fragmented by the IP layer. If any fragment is lost, the entire message is - /// discarded. For maximum reliability, keep serialized messages under 1400 bytes. - /// Messages exceeding BUFFER_SIZE will be truncated and discarded by the OS. - static const int BUFFER_SIZE = 4096; - char m_buffer[BUFFER_SIZE] = { 0 }; - char m_sendBuffer[BUFFER_SIZE] = { 0 }; - dmq::RecursiveMutex m_mutex; ///< Socket open/close and Send() state - dmq::RecursiveMutex m_recvMutex; ///< Held by Receive(); taken before m_mutex -}; - -using UdpTransport = LinuxUdpTransport; - -} // namespace dmq::transport - -#endif // LINUX_UDP_TRANSPORT_H \ No newline at end of file diff --git a/DelegateMQ/port/transport/linux-udp/MulticastTransport.h b/DelegateMQ/port/transport/linux-udp/MulticastTransport.h deleted file mode 100644 index 002d13b..0000000 --- a/DelegateMQ/port/transport/linux-udp/MulticastTransport.h +++ /dev/null @@ -1,141 +0,0 @@ -#ifndef LINUX_MULTICAST_TRANSPORT_H -#define LINUX_MULTICAST_TRANSPORT_H - -#include "delegate/DelegateOpt.h" -#include "port/transport/common/ITransport.h" -#include "port/transport/common/DmqHeader.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace dmq::transport { - -/// @brief Linux Multicast UDP transport implementation for DelegateMQ. -class MulticastTransport : public ITransport -{ -public: - enum class Type { PUB, SUB }; - - MulticastTransport() = default; - ~MulticastTransport() { Close(); } - - int Create(Type type, const char* groupAddr, uint16_t port, const char* localInterface = "0.0.0.0") - { - dmq::LockGuard lock(m_mutex); - m_type = type; - m_socket = socket(AF_INET, SOCK_DGRAM, 0); - if (m_socket < 0) return -1; - - int reuse = 1; - setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)); - - // ALWAYS enable loopback for testing convenience - int loop = 1; - setsockopt(m_socket, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop)); - - memset(&m_addr, 0, sizeof(m_addr)); - m_addr.sin_family = AF_INET; - m_addr.sin_port = htons(port); - - if (type == Type::PUB) { - m_addr.sin_addr.s_addr = inet_addr(groupAddr); - - struct in_addr interface_addr; - interface_addr.s_addr = inet_addr(localInterface); - setsockopt(m_socket, IPPROTO_IP, IP_MULTICAST_IF, &interface_addr, sizeof(interface_addr)); - - int ttl = 3; - setsockopt(m_socket, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl)); - } - else { - m_addr.sin_addr.s_addr = INADDR_ANY; - if (bind(m_socket, (struct sockaddr*)&m_addr, sizeof(m_addr)) < 0) { Close(); return -1; } - - struct ip_mreq mreq; - mreq.imr_multiaddr.s_addr = inet_addr(groupAddr); - mreq.imr_interface.s_addr = inet_addr(localInterface); - if (setsockopt(m_socket, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) { - Close(); return -1; - } - - struct timeval timeout; - timeout.tv_sec = 1; - timeout.tv_usec = 0; - setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)); - } - return 0; - } - - void Close() { - dmq::LockGuard lock(m_mutex); - if (m_socket != -1) { - close(m_socket); - m_socket = -1; - } - } - - virtual int Send(xostringstream& os, const DmqHeader& header) override { - dmq::LockGuard lock(m_mutex); - if (m_type != Type::PUB) return -1; - auto payload = os.str(); - if (payload.length() > (BUFFER_SIZE - DmqHeader::HEADER_SIZE)) return -1; - DmqHeader headerCopy = header; - headerCopy.SetLength(static_cast(payload.length())); - - xostringstream ss(std::ios::in | std::ios::out | std::ios::binary); - char headerBuf[DmqHeader::HEADER_SIZE]; - headerCopy.Encode(headerBuf); - ss.write(headerBuf, DmqHeader::HEADER_SIZE); - ss.write(payload.data(), payload.size()); - - auto data = ss.str(); - sendto(m_socket, data.c_str(), data.size(), 0, (struct sockaddr*)&m_addr, sizeof(m_addr)); - return 0; - } - - virtual int Receive(xstringstream& is, DmqHeader& header) override { - dmq::LockGuard lock(m_mutex); - if (m_type != Type::SUB) return -1; - // MSG_TRUNC: return the datagram's real length, so one larger than the - // buffer is detected and dropped rather than delivered cut short. - ssize_t size = recvfrom(m_socket, m_buffer, sizeof(m_buffer), MSG_TRUNC, NULL, NULL); - if (size < 0) - return (errno == EAGAIN || errno == EWOULDBLOCK) ? RECEIVE_NO_DATA : -1; - - if (size < (ssize_t)DmqHeader::HEADER_SIZE) return -1; - if (size > (ssize_t)sizeof(m_buffer)) return -1; // truncated - - header.Decode(m_buffer); - - if (!header.IsValid()) { - // std::cerr << "[Multicast] Bad Marker: " << std::hex << header.GetMarker() << std::dec << std::endl; - return -1; - } - - // One datagram is one message: the header length must match exactly. - int payloadSize = static_cast(size) - static_cast(DmqHeader::HEADER_SIZE); - if (header.GetLength() != payloadSize) return -1; - is.write(m_buffer + DmqHeader::HEADER_SIZE, header.GetLength()); - return 0; - } - -private: - int m_socket = -1; - sockaddr_in m_addr{}; - Type m_type = Type::PUB; - static const int BUFFER_SIZE = 4096; - char m_buffer[BUFFER_SIZE] = { 0 }; - dmq::RecursiveMutex m_mutex; -}; - -} // namespace dmq::transport - -#endif diff --git a/DelegateMQ/port/transport/linux-uds/LinuxUdsTransport.h b/DelegateMQ/port/transport/linux-uds/LinuxUdsTransport.h deleted file mode 100644 index 8eca390..0000000 --- a/DelegateMQ/port/transport/linux-uds/LinuxUdsTransport.h +++ /dev/null @@ -1,350 +0,0 @@ -#ifndef LINUX_UDS_TRANSPORT_H -#define LINUX_UDS_TRANSPORT_H - -/// @file LinuxUdsTransport.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// @brief Linux Unix domain socket transport implementation for DelegateMQ. -/// -/// @details -/// Local inter-process communication over a Unix domain datagram socket -/// (`AF_UNIX`, `SOCK_DGRAM`). This is the Linux counterpart to -/// `Win32PipeTransport`: one transport instance is duplex, so a single -/// participant can both send and receive over it. -/// -/// Each endpoint is a filesystem path. Every instance binds its own local path -/// (so the peer can address it) and sends to the peer's path: -/// -/// @code -/// // Process A // Process B -/// t.Create(Type::SUB, "/tmp/a.sock", "/tmp/b.sock"); t.Create(Type::PUB, "/tmp/b.sock", "/tmp/a.sock"); -/// @endcode -/// -/// Key Features: -/// 1. **No start order**: datagram sockets have no connection. Either side may -/// start first; a Send() to a peer that isn't bound yet fails (returns -1) -/// and the next Send() after the peer binds succeeds. -/// 2. **Message boundaries**: one Send() is exactly one Receive(). -/// Linux Unix datagram sockets are reliable and ordered, so no ACK/retry -/// layer is used (same as `Win32PipeTransport`). -/// 3. **Non-blocking by default**: Receive() returns -1 immediately when no -/// datagram is waiting, matching `Win32PipeTransport`'s `PIPE_NOWAIT` mode. -/// SetRecvTimeout() makes Receive() block up to the given time instead. -/// Receive() does not hold the send lock while waiting, so a concurrent -/// Send() on the same instance is never held up by an idle read. -/// 4. **Stale paths**: a crashed process leaves its socket file behind. Create() -/// probes the local path first: a stale socket (nothing listening) is -/// unlinked and reused; a path a live process is still bound to makes -/// Create() fail rather than take it over. Close() unlinks the path again. -/// -/// @note Socket files are ordinary filesystem entries, so access is governed by -/// the directory's permissions. A world-writable directory such as `/tmp` lets -/// any local user send to the socket. Use a per-user directory such as -/// `$XDG_RUNTIME_DIR` when that matters. -/// -/// Type is kept for API parity with `Win32PipeTransport` (`SUB` = server end, -/// `PUB` = client end). Both ends are duplex. The one difference: a `SUB` -/// created with `peerPath == nullptr` replies to whoever sent it the most recent -/// datagram, instead of a fixed peer. -/// -/// @note This class is specific to Linux and uses POSIX socket APIs. - -#include "delegate/DelegateOpt.h" -#include "port/transport/common/ITransport.h" -#include "port/transport/common/DmqHeader.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace dmq::transport { - -/// @brief Linux Unix domain datagram socket transport. -class LinuxUdsTransport : public ITransport -{ - XALLOCATOR -public: - enum class Type - { - PUB, - SUB - }; - - LinuxUdsTransport() = default; - - ~LinuxUdsTransport() - { - Close(); - } - - /// Create the socket and bind it to localPath. - /// @param[in] type PUB (client end) or SUB (server end). Both are duplex. - /// @param[in] localPath This endpoint's socket path. Required. - /// @param[in] peerPath The other endpoint's socket path. Required for PUB; - /// optional for SUB (nullptr = reply to the most recent sender). - /// @return 0 on success, -1 on failure. - int Create(Type type, const char* localPath, const char* peerPath) - { - const std::lock_guard lock(m_mutex); - m_type = type; - - if (localPath == nullptr || (type == Type::PUB && peerPath == nullptr)) - { - std::cerr << "LinuxUdsTransport: missing socket path." << std::endl; - return -1; - } - - if (!MakeAddr(localPath, m_localAddr) || - (peerPath && !MakeAddr(peerPath, m_peerAddr))) - { - std::cerr << "LinuxUdsTransport: socket path too long (max " - << sizeof(m_localAddr.sun_path) - 1 << " chars)." << std::endl; - return -1; - } - m_fixedPeer = (peerPath != nullptr); - m_hasPeer = m_fixedPeer; - - m_socket = socket(AF_UNIX, SOCK_DGRAM, 0); - if (m_socket < 0) - { - std::cerr << "Socket creation failed: " << strerror(errno) << std::endl; - return -1; - } - - // A crashed run leaves the socket file behind, which makes bind() fail. - // Unlink it only if it is a stale socket; never steal a live one. - if (!ClearStalePath(m_localAddr)) - { - close(m_socket); - m_socket = -1; - return -1; - } - if (bind(m_socket, (struct sockaddr*)&m_localAddr, sizeof(m_localAddr)) < 0) - { - std::cerr << "Bind failed (" << m_localAddr.sun_path << "): " << strerror(errno) << std::endl; - close(m_socket); - m_socket = -1; - return -1; - } - m_bound = true; - return 0; - } - - void Close() - { - // Lock order matches Receive(): m_recvMutex, then m_mutex. Holding - // m_recvMutex means no Receive() is mid-wait on the socket we close - // (Close() waits at most one recv timeout for it to return). - const std::lock_guard recvLock(m_recvMutex); - const std::lock_guard lock(m_mutex); - if (m_socket != -1) - { - shutdown(m_socket, SHUT_RDWR); - close(m_socket); - m_socket = -1; - } - if (m_bound) - { - unlink(m_localAddr.sun_path); - m_bound = false; - } - } - - /// Make Receive() wait up to timeout for a datagram. 0 (default) = non-blocking. - void SetRecvTimeout(std::chrono::milliseconds timeout) - { - const std::lock_guard lock(m_mutex); - m_recvTimeout = timeout; - } - - virtual int Send(dmq::xostringstream& os, const DmqHeader& header) override - { - const std::lock_guard lock(m_mutex); - if (os.bad() || os.fail()) - return -1; - - if (m_socket == -1 || !m_hasPeer) - return -1; - - auto payload = os.str(); - if (payload.length() > (BUFFER_SIZE - DmqHeader::HEADER_SIZE)) { - std::cerr << "Error: Payload too large for static buffer." << std::endl; - return -1; - } - uint16_t payloadLen = static_cast(payload.length()); - - // Prepare header values in Network Byte Order - DmqHeader wireHeader = header; - wireHeader.SetLength(payloadLen); - wireHeader.Encode(m_sendBuffer); - - // Copy payload after header - if (payloadLen > 0) { - memcpy(m_sendBuffer + DmqHeader::HEADER_SIZE, payload.data(), payloadLen); - } - - size_t totalSize = DmqHeader::HEADER_SIZE + payloadLen; - - // MSG_DONTWAIT: if the peer isn't reading and its queue is full, fail - // this send rather than stall the caller. A peer that isn't bound yet - // fails with ENOENT/ECONNREFUSED. - ssize_t sent = sendto(m_socket, m_sendBuffer, totalSize, MSG_DONTWAIT, - (struct sockaddr*)&m_peerAddr, sizeof(m_peerAddr)); - - if (sent != (ssize_t)totalSize) - return -1; - - return 0; - } - - virtual int Receive(dmq::xstringstream& is, DmqHeader& header) override - { - // Receive-side state (m_buffer) is only touched here, under m_recvMutex. - // m_mutex is not held while waiting, so Send() is never blocked by an idle read. - // The socket copied below stays valid: Close() also takes m_recvMutex. - const std::lock_guard recvLock(m_recvMutex); - - int sock; - std::chrono::milliseconds timeout; - { - const std::lock_guard lock(m_mutex); - sock = m_socket; - timeout = m_recvTimeout; - } - if (sock == -1) - return -1; - - if (timeout.count() > 0) - { - pollfd pfd{ sock, POLLIN, 0 }; - int ready = poll(&pfd, 1, static_cast(timeout.count())); - if (ready == 0) - return RECEIVE_NO_DATA; - if (ready < 0) - return -1; - } - - sockaddr_un fromAddr{}; - socklen_t addrLen = sizeof(fromAddr); - // MSG_TRUNC: return the datagram's real length, so an oversized one is - // detected and dropped instead of being silently cut off. - ssize_t size = recvfrom(sock, m_buffer, sizeof(m_buffer), MSG_DONTWAIT | MSG_TRUNC, - (struct sockaddr*)&fromAddr, &addrLen); - - if (size < 0) - return (errno == EAGAIN || errno == EWOULDBLOCK) ? RECEIVE_NO_DATA : -1; - if (size < static_cast(DmqHeader::HEADER_SIZE)) - return -1; // runt datagram - if (size > static_cast(sizeof(m_buffer))) - return -1; // truncated: larger than the receive buffer - - // 1. Read Header directly from m_buffer (Network Byte Order) - header.Decode(m_buffer); - - if (!header.IsValid()) - return -1; - - // 2. Write payload to provided stream. One Send() is one datagram, so - // the header length must match exactly; anything else is malformed. - uint16_t payloadSize = header.GetLength(); - if (payloadSize != (size - DmqHeader::HEADER_SIZE)) - return -1; - - if (payloadSize > 0) { - is.write(m_buffer + DmqHeader::HEADER_SIZE, payloadSize); - } - - // 3. A SUB without a fixed peer replies to the most recent (bound) sender. - if (m_type == Type::SUB && addrLen > sizeof(sa_family_t)) - { - const std::lock_guard lock(m_mutex); - if (!m_fixedPeer) - { - m_peerAddr = fromAddr; - m_hasPeer = true; - } - } - - return 0; - } - -private: - /// Prepare addr's path for bind(). A connect() probe tells a stale socket - /// file (ECONNREFUSED: nothing bound) from a live one (connect succeeds). - /// Only a stale socket is unlinked; a live one, or anything that isn't a - /// socket, is left alone. - /// @return true if bind() may proceed. - static bool ClearStalePath(const sockaddr_un& addr) - { - // connect() also reports ECONNREFUSED for a regular file, so check the - // file type first. lstat(): a symlink is not followed or removed. - struct stat st{}; - if (lstat(addr.sun_path, &st) != 0) - return true; // nothing there - if (!S_ISSOCK(st.st_mode)) - return true; // not a socket: leave it; bind() fails and reports it - - int probe = socket(AF_UNIX, SOCK_DGRAM, 0); - if (probe < 0) - { - std::cerr << "Socket creation failed: " << strerror(errno) << std::endl; - return false; - } - int rc = connect(probe, (const struct sockaddr*)&addr, sizeof(addr)); - int err = errno; - close(probe); - - if (rc == 0) - { - std::cerr << "LinuxUdsTransport: " << addr.sun_path - << " is in use by another process." << std::endl; - return false; - } - if (err == ECONNREFUSED) - unlink(addr.sun_path); // stale socket file - // Any other error (e.g. EACCES): leave the file alone and let bind() - // fail and report it. - return true; - } - - static bool MakeAddr(const char* path, sockaddr_un& addr) - { - memset(&addr, 0, sizeof(addr)); - addr.sun_family = AF_UNIX; - if (strlen(path) >= sizeof(addr.sun_path)) - return false; - strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1); - return true; - } - - int m_socket = -1; - bool m_bound = false; - bool m_hasPeer = false; - bool m_fixedPeer = false; // peer given to Create(); never overwritten by Receive() - sockaddr_un m_localAddr{}; - sockaddr_un m_peerAddr{}; - Type m_type = Type::PUB; - std::chrono::milliseconds m_recvTimeout{ 0 }; - - /// Max datagram size. Linux Unix datagram sockets accept datagrams up to - /// the socket send buffer size (net.core.wmem_default, typically ~200 KB), - /// so this static buffer is the practical limit. - static const int BUFFER_SIZE = 65536; - char m_buffer[BUFFER_SIZE] = { 0 }; - char m_sendBuffer[BUFFER_SIZE] = { 0 }; - dmq::RecursiveMutex m_mutex; // socket state + send path - dmq::RecursiveMutex m_recvMutex; // receive path -}; - -} // namespace dmq::transport - -#endif // LINUX_UDS_TRANSPORT_H diff --git a/DelegateMQ/port/transport/mqtt/MqttTransport.h b/DelegateMQ/port/transport/mqtt/MqttTransport.h deleted file mode 100644 index a438d71..0000000 --- a/DelegateMQ/port/transport/mqtt/MqttTransport.h +++ /dev/null @@ -1,350 +0,0 @@ - -#ifndef MQTT_TRANSPORT_H -#define MQTT_TRANSPORT_H - -/// @file -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// Transport callable argument data to/from a remote using MQTT library. -/// https://github.com/eclipse-paho/paho.mqtt.c -/// -/// Carries DelegateMQ binary frames between DelegateMQ apps on one MQTT topic. -/// Other MQTT tools can't read these frames; to expose DataBus topics as -/// readable JSON instead, see tools/bridge/mqtt/MqttBridge. -/// -/// The broker defaults to a local one (tcp://localhost:1883, e.g. Mosquitto). -/// Pass a broker URI to Create() to use another. Never point real traffic at -/// a public test broker: anyone can read and publish on it. -/// -/// @code -/// MqttTransport t; -/// t.Create(MqttTransport::Type::PUB); // local broker, default topic -/// t.Create(MqttTransport::Type::SUB, "tcp://10.0.0.5:1883", "plant/dmq"); // explicit broker and topic -/// @endcode - -// Ensure network byte order functions are available -#if defined(_WIN32) || defined(_WIN64) - #include - #pragma comment(lib, "ws2_32.lib") -#else - #include -#endif - -#include "port/transport/common/ITransport.h" -#include "port/transport/common/ITransportMonitor.h" -#include "port/transport/common/DmqHeader.h" -#include "MQTTClient.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace dmq::transport { - -/// @brief MQTT transport example. -class MqttTransport : public ITransport -{ - XALLOCATOR -public: - enum class Type - { - PUB, - SUB - }; - - static constexpr const char* DEFAULT_ADDRESS = "tcp://localhost:1883"; - static constexpr const char* DEFAULT_TOPIC = "dmq/delegate"; - static constexpr int QOS = 1; - static constexpr long TIMEOUT_MS = 10000L; - - MqttTransport() = default; - - ~MqttTransport() - { - Close(); - } - - /// Connect to the broker. - /// @param[in] type PUB publishes to topic; SUB subscribes to it. - /// @param[in] address Broker URI, e.g. "tcp://localhost:1883". - /// @param[in] topic MQTT topic carrying the frames. Both ends must use the same one. - /// @param[in] clientId MQTT client ID. Must be unique on the broker: a second - /// client with the same ID disconnects the first. nullptr (default) - /// generates a random one ("dmq-pub-xxxxxxxx" / "dmq-sub-xxxxxxxx"). - /// @return 0 (MQTTCLIENT_SUCCESS) on success, otherwise a Paho error code. - int Create(Type type, const char* address = DEFAULT_ADDRESS, - const char* topic = DEFAULT_TOPIC, const char* clientId = nullptr) - { - const std::lock_guard lock(m_mutex); - int rc = EXIT_FAILURE; - if (address == nullptr || topic == nullptr || *topic == '\0') - return MQTTCLIENT_NULL_PARAMETER; - - m_topic = topic; - const std::string id = clientId ? std::string(clientId) : MakeClientId(type); - printf("MqttTransport: broker %s, topic %s, client %s\n", address, m_topic.c_str(), id.c_str()); - - { - std::lock_guard q_lock(m_queueMtx); - m_stop = false; - } - - MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer; - m_type = type; - if (m_type == Type::PUB) - { - if ((rc = MQTTClient_create(&m_client, address, id.c_str(), - MQTTCLIENT_PERSISTENCE_NONE, NULL)) != MQTTCLIENT_SUCCESS) - { - m_client = nullptr; - return rc; - } - - conn_opts.keepAliveInterval = 20; - conn_opts.cleansession = 1; - if ((rc = MQTTClient_connect(m_client, &conn_opts)) != MQTTCLIENT_SUCCESS) - { - MQTTClient_destroy(&m_client); - m_client = nullptr; - return rc; - } - } - else if (m_type == Type::SUB) - { - if ((rc = MQTTClient_create(&m_client, address, id.c_str(), - MQTTCLIENT_PERSISTENCE_NONE, NULL)) != MQTTCLIENT_SUCCESS) - { - m_client = nullptr; - return rc; - } - - // Register callbacks to populate internal queue - if ((rc = MQTTClient_setCallbacks(m_client, this, connlost, msgarrvd, delivered)) != MQTTCLIENT_SUCCESS) - { - MQTTClient_destroy(&m_client); - m_client = nullptr; - return rc; - } - - conn_opts.keepAliveInterval = 20; - conn_opts.cleansession = 1; - if ((rc = MQTTClient_connect(m_client, &conn_opts)) != MQTTCLIENT_SUCCESS) - { - MQTTClient_destroy(&m_client); - m_client = nullptr; - return rc; - } - - if ((rc = MQTTClient_subscribe(m_client, m_topic.c_str(), QOS)) != MQTTCLIENT_SUCCESS) - { - MQTTClient_disconnect(m_client, 1000); - MQTTClient_destroy(&m_client); - m_client = nullptr; - return rc; - } - } - return MQTTCLIENT_SUCCESS; - } - - void Close() - { - const std::lock_guard lock(m_mutex); - if (m_client) - { - if (m_type == Type::SUB) - { - MQTTClient_unsubscribe(m_client, m_topic.c_str()); - } - MQTTClient_disconnect(m_client, 1000); - MQTTClient_destroy(&m_client); - m_client = nullptr; - } - - // Wake up any blocked Receive - { - std::lock_guard q_lock(m_queueMtx); - m_stop = true; - } - m_queueCv.notify_all(); - } - - virtual int Send(xostringstream& os, const DmqHeader& header) override - { - const std::lock_guard lock(m_mutex); - if (os.bad() || os.fail() || !m_client) - return -1; - - // Get payload data without string copy if possible - auto payload = os.str(); - if (payload.length() > (BUFFER_SIZE - DmqHeader::HEADER_SIZE)) { - return -1; - } - uint16_t payloadLen = static_cast(payload.length()); - - // Prepare header values in Network Byte Order - DmqHeader wireHeader = header; - wireHeader.SetLength(payloadLen); - wireHeader.Encode(m_sendBuffer); - - if (payloadLen > 0) { - memcpy(m_sendBuffer + DmqHeader::HEADER_SIZE, payload.data(), payloadLen); - } - - size_t totalSize = DmqHeader::HEADER_SIZE + payloadLen; - - MQTTClient_message pubmsg = MQTTClient_message_initializer; - MQTTClient_deliveryToken token; - - pubmsg.payload = (void*)m_sendBuffer; - pubmsg.payloadlen = (int)totalSize; - pubmsg.qos = QOS; - pubmsg.retained = 0; - - int rc; - if ((rc = MQTTClient_publishMessage(m_client, m_topic.c_str(), &pubmsg, &token)) != MQTTCLIENT_SUCCESS) - { - return EXIT_FAILURE; - } - else - { - return EXIT_SUCCESS; - } - } - - virtual int Receive(xstringstream& is, DmqHeader& header) override - { - std::unique_lock q_lock(m_queueMtx); - - // Wait for data or stop signal - if (m_queueCv.wait_for(q_lock, m_recvTimeout, [this] { return !m_rxQueue.empty() || m_stop; })) - { - if (m_stop) return -1; - - if (m_rxQueue.empty()) return RECEIVE_NO_DATA; - - // Pop message - std::vector msg = std::move(m_rxQueue.front()); - m_rxQueue.pop(); - q_lock.unlock(); // Release queue lock before processing - - if (msg.size() < DmqHeader::HEADER_SIZE) return -1; - - // 1. Read Header (Network Byte Order) - header.Decode(msg.data()); - - if (!header.IsValid()) return -1; - - // 2. Write payload. One message per MQTT publish: the header length - // must match exactly. Anything else is malformed and must not be - // delivered (cut short) or ACKed. - uint16_t payloadSize = header.GetLength(); - if (payloadSize != msg.size() - DmqHeader::HEADER_SIZE) - return -1; - - if (payloadSize > 0) { - is.clear(); - is.str(""); - is.write(msg.data() + DmqHeader::HEADER_SIZE, payloadSize); - } - - // 3. ACK Logic - if (header.GetId() == dmq::ACK_REMOTE_ID) { - if (m_transportMonitor) m_transportMonitor->Remove(header.GetSeqNum()); - } - else if (m_transportMonitor) { - // Auto-ACK - xostringstream ss_ack; - DmqHeader ack; - ack.SetId(dmq::ACK_REMOTE_ID); - ack.SetSeqNum(header.GetSeqNum()); - Send(ss_ack, ack); - } - return 0; - } - - return RECEIVE_NO_DATA; // Timeout - } - - void SetTransportMonitor(ITransportMonitor* transportMonitor) - { - m_transportMonitor = transportMonitor; - } - - void SetRecvTimeout(std::chrono::milliseconds timeout) - { - m_recvTimeout = timeout; - } - -private: - /// Random client ID, so two apps (or two runs) never share one by accident. - static std::string MakeClientId(Type type) - { - static const char hex[] = "0123456789abcdef"; - std::random_device rd; - std::string id = (type == Type::PUB) ? "dmq-pub-" : "dmq-sub-"; - for (int i = 0; i < 8; ++i) - id += hex[rd() & 0xF]; - return id; - } - - static void delivered(void* context, MQTTClient_deliveryToken dt) - { - // printf("Message with token value %d delivery confirmed\n", dt); - } - - // Callback running on Paho Thread - static int msgarrvd(void* context, char* topicName, int topicLen, MQTTClient_message* message) - { - MqttTransport* instance = (MqttTransport*)context; - if (instance) - { - // Copy data to vector and push to queue - std::vector data; - data.resize(message->payloadlen); - std::memcpy(data.data(), message->payload, message->payloadlen); - - { - std::lock_guard lock(instance->m_queueMtx); - instance->m_rxQueue.push(std::move(data)); - } - instance->m_queueCv.notify_one(); - } - - MQTTClient_freeMessage(&message); - MQTTClient_free(topicName); - return 1; - } - - static void connlost(void* context, char* cause) - { - // printf("\nConnection lost\n"); - } - - MQTTClient m_client = nullptr; - std::string m_topic = DEFAULT_TOPIC; - ITransportMonitor* m_transportMonitor = nullptr; - Type m_type = Type::PUB; - - std::chrono::milliseconds m_recvTimeout = std::chrono::milliseconds(1000); - - // Thread-safe Queue for bridging Paho callback to ITransport::Receive - std::queue> m_rxQueue; - std::mutex m_queueMtx; - std::condition_variable m_queueCv; - bool m_stop = false; - - static const int BUFFER_SIZE = 4096; - char m_sendBuffer[BUFFER_SIZE] = { 0 }; - dmq::RecursiveMutex m_mutex; -}; - -} - -#endif // MQTT_TRANSPORT_H \ No newline at end of file diff --git a/DelegateMQ/port/transport/netx-udp/NetXUdpTransport.h b/DelegateMQ/port/transport/netx-udp/NetXUdpTransport.h deleted file mode 100644 index 351a4d0..0000000 --- a/DelegateMQ/port/transport/netx-udp/NetXUdpTransport.h +++ /dev/null @@ -1,345 +0,0 @@ -#ifndef NETX_UDP_TRANSPORT_H -#define NETX_UDP_TRANSPORT_H - -/// @file NetXUdpTransport.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief NetX (ThreadX) UDP transport implementation for DelegateMQ. -/// -/// @details -/// This class implements the ITransport interface using the Azure RTOS NetX (or NetX Duo) -/// network stack. It is designed for embedded targets running ThreadX. -/// -/// **Dependencies:** -/// * ThreadX (`tx_api.h`) -/// * NetX (`nx_api.h`) -/// * A valid `NX_IP` instance and `NX_PACKET_POOL` must be provided at construction. -/// -/// **Key Features:** -/// 1. **Direct Execution**: Executes network operations directly on the calling thread. -/// 2. **Thread Safety**: Uses a `TX_MUTEX` to protect the NetX socket. -/// 3. **Reliability**: Integrated with `TransportMonitor` for ACKs/Retries. -/// 4. **Robustness**: Validates packet allocation and append results to prevent corruption. - -#include "delegate/DelegateOpt.h" -#include "port/transport/common/ITransport.h" -#include "port/transport/common/DmqHeader.h" -#include "port/transport/common/ITransportMonitor.h" -#include "nx_api.h" - -#include -#include -#include - -namespace dmq::transport { - -class NetXUdpTransport : public ITransport -{ - XALLOCATOR -public: - enum class Type - { - PUB, - SUB - }; - - /// @brief Constructor - /// @param ip_ptr Pointer to the initialized NetX IP instance. - /// @param pool_ptr Pointer to the packet pool for allocating UDP packets. - NetXUdpTransport(NX_IP* ip_ptr, NX_PACKET_POOL* pool_ptr) - : m_ip(ip_ptr) - , m_pool(pool_ptr) - , m_sendTransport(this) - , m_recvTransport(this) - { - // Initialize mutexes for socket protection (No Inherit to detect deadlocks easier). - // m_recvMutex is held by Receive(); m_mutex by Send() and socket setup. - // Lock order: m_recvMutex, then m_mutex. - tx_mutex_create(&m_mutex, (CHAR*)"NetXTransportMutex", TX_NO_INHERIT); - tx_mutex_create(&m_recvMutex, (CHAR*)"NetXTransportRecvMutex", TX_NO_INHERIT); - memset(&m_socket, 0, sizeof(m_socket)); - } - - ~NetXUdpTransport() - { - Close(); - tx_mutex_delete(&m_recvMutex); - tx_mutex_delete(&m_mutex); - } - - /// @brief Initialize the UDP socket. - int Create(Type type, const char* addr_str, uint16_t port) - { - Close(); // a second Create() replaces the socket instead of leaking it - tx_mutex_get(&m_recvMutex, TX_WAIT_FOREVER); - tx_mutex_get(&m_mutex, TX_WAIT_FOREVER); - - m_type = type; - m_port = port; - - // Parse IP Address - m_targetIp = 0; - if (addr_str) { - uint32_t a, b, c, d; - if (std::sscanf(addr_str, "%u.%u.%u.%u", &a, &b, &c, &d) == 4) { - // Construct IP ULONG (Assumes NetX expects Host Byte Order for setup) - m_targetIp = (a << 24) | (b << 16) | (c << 8) | d; - } - } - - // Create the UDP Socket - UINT ret = nx_udp_socket_create(m_ip, &m_socket, (CHAR*)"DelegateMQ_Sock", - NX_IP_NORMAL, NX_FRAGMENT_OKAY, 0x80, 5); - if (ret != NX_SUCCESS) { - tx_mutex_put(&m_mutex); - tx_mutex_put(&m_recvMutex); - return -1; - } - - // Bind - if (type == Type::SUB) { - ret = nx_udp_socket_bind(&m_socket, port, NX_WAIT_FOREVER); - } else { - ret = nx_udp_socket_bind(&m_socket, NX_ANY_PORT, NX_WAIT_FOREVER); - } - - if (ret != NX_SUCCESS) { - nx_udp_socket_delete(&m_socket); - memset(&m_socket, 0, sizeof(m_socket)); - tx_mutex_put(&m_mutex); - tx_mutex_put(&m_recvMutex); - return -1; - } - - SetRecvTimeout(type == Type::PUB ? dmq::UDP_PUB_RECV_TIMEOUT : dmq::UDP_SUB_RECV_TIMEOUT); - - tx_mutex_put(&m_mutex); - tx_mutex_put(&m_recvMutex); - return 0; - } - - /// @details Waits for a Receive() in progress on another thread to return - /// (at most its receive timeout) first. - void Close() - { - tx_mutex_get(&m_recvMutex, TX_WAIT_FOREVER); - tx_mutex_get(&m_mutex, TX_WAIT_FOREVER); - - if (m_socket.nx_udp_socket_id != 0) - { - nx_udp_socket_unbind(&m_socket); - nx_udp_socket_delete(&m_socket); - memset(&m_socket, 0, sizeof(m_socket)); - } - - tx_mutex_put(&m_mutex); - tx_mutex_put(&m_recvMutex); - } - - void SetRecvTimeout(std::chrono::milliseconds timeout) - { - tx_mutex_get(&m_mutex, TX_WAIT_FOREVER); - // Convert ms to ThreadX ticks - m_recvTimeout = (ULONG)((timeout.count() * TX_TIMER_TICKS_PER_SECOND) / 1000); - if (m_recvTimeout == 0 && timeout.count() > 0) m_recvTimeout = 1; - tx_mutex_put(&m_mutex); - } - - virtual int Send(xostringstream& os, const DmqHeader& header) override - { - tx_mutex_get(&m_mutex, TX_WAIT_FOREVER); - - if (os.bad() || os.fail()) { - tx_mutex_put(&m_mutex); - return -1; - } - - // Block regular data on SUB socket (only ACKs allowed) - if (m_type == Type::SUB && header.GetId() != dmq::ACK_REMOTE_ID) { - tx_mutex_put(&m_mutex); - return -1; - } - - if (m_sendTransport != this) { - tx_mutex_put(&m_mutex); - return -1; - } - - auto payload = os.str(); - // The receiver's buffer (same DMQ_UDP_BUFFER_SIZE) must hold the datagram. - if (payload.length() > dmq::UDP_BUFFER_SIZE - DmqHeader::HEADER_SIZE) { - tx_mutex_put(&m_mutex); - return -1; - } - - // 1. Allocate NetX Packet - NX_PACKET* packet_ptr = nullptr; - UINT ret = nx_packet_allocate(m_pool, &packet_ptr, NX_UDP_PACKET, NX_NO_WAIT); - if (ret != NX_SUCCESS) { - tx_mutex_put(&m_mutex); - return -1; - } - - // 2. Prepare Header (Network Byte Order) - DmqHeader headerCopy = header; - headerCopy.SetLength(static_cast(payload.length())); - - UCHAR headerBuf[DmqHeader::HEADER_SIZE]; - headerCopy.Encode(headerBuf); - - // 3. Append Data (With Error Checks) - // Check return value of every append. If one fails, the packet is corrupted/partial. - if (nx_packet_data_append(packet_ptr, headerBuf, sizeof(headerBuf), m_pool, NX_NO_WAIT) != NX_SUCCESS) - goto cleanup_and_fail; - - if (nx_packet_data_append(packet_ptr, (VOID*)payload.data(), payload.size(), m_pool, NX_NO_WAIT) != NX_SUCCESS) - goto cleanup_and_fail; - - // 4. Send - // nx_udp_socket_send typically releases the packet on internal errors. - // However, if it fails due to binding issues (before driver), it might not. - ret = nx_udp_socket_send(&m_socket, packet_ptr, m_targetIp, m_port); - - if (ret != NX_SUCCESS) { - // Defensive release: Verify if your specific NetX version auto-releases on specific errors. - // Standard practice is often to release if send fails. - nx_packet_release(packet_ptr); - tx_mutex_put(&m_mutex); - return -1; - } - - tx_mutex_put(&m_mutex); - return 0; - - cleanup_and_fail: - nx_packet_release(packet_ptr); - tx_mutex_put(&m_mutex); - return -1; - } - - virtual int Receive(xstringstream& is, DmqHeader& header) override - { - // m_recvMutex, not m_mutex: a Send() on another thread isn't held up - // for the receive timeout. - tx_mutex_get(&m_recvMutex, TX_WAIT_FOREVER); - const int result = ReceiveLocked(is, header); - tx_mutex_put(&m_recvMutex); - return result; - } - - void SetTransportMonitor(ITransportMonitor* tm) { m_transportMonitor = tm; } - void SetSendTransport(ITransport* st) { m_sendTransport = st; } - void SetRecvTransport(ITransport* rt) { m_recvTransport = rt; } - -private: - /// Receive() body; caller holds m_recvMutex. - int ReceiveLocked(xstringstream& is, DmqHeader& header) - { - if (m_recvTransport != this || m_socket.nx_udp_socket_id == 0) { - return -1; - } - - NX_PACKET* packet_ptr = nullptr; - - // Use configured timeout - UINT ret = nx_udp_socket_receive(&m_socket, &packet_ptr, m_recvTimeout); - if (ret == NX_NO_PACKET) { - return RECEIVE_NO_DATA; - } - if (ret != NX_SUCCESS) { - return -1; - } - - // --- Extract Source Info for ACKs --- - ULONG srcIp = 0; - UINT srcPort = 0; - nx_udp_source_extract(packet_ptr, &srcIp, &srcPort); - - // Validate total length before attempting retrieve - if (packet_ptr->nx_packet_length > sizeof(m_recvBuffer)) { - nx_packet_release(packet_ptr); - return -1; // Packet too large for buffer - } - - // Retrieve copies data out of packet (handling chained packets if necessary) - ULONG bytesRead = 0; - ret = nx_packet_data_retrieve(packet_ptr, m_recvBuffer, &bytesRead); - nx_packet_release(packet_ptr); - - if (ret != NX_SUCCESS || bytesRead < DmqHeader::HEADER_SIZE) { - return -1; - } - - // Parse Header - header.Decode(m_recvBuffer); - if (!header.IsValid()) { - return -1; - } - - // One datagram is one message: the header length must match exactly. - // Anything else is malformed and must not be delivered or ACKed. - if (bytesRead != (ULONG)(DmqHeader::HEADER_SIZE + header.GetLength())) { - return -1; - } - - // A SUB replies to whoever sent the last valid message. Updated only - // now, after validation, and under m_mutex since Send() uses it. - if (m_type == Type::SUB) { - tx_mutex_get(&m_mutex, TX_WAIT_FOREVER); - m_targetIp = srcIp; - m_port = srcPort; - tx_mutex_put(&m_mutex); - } - - // Reset stream state before writing - is.clear(); - is.str(""); - - // Write Payload to stream - is.write((char*)(m_recvBuffer + DmqHeader::HEADER_SIZE), header.GetLength()); - - // --- ACK Logic --- - if (header.GetId() == dmq::ACK_REMOTE_ID) { - if (m_transportMonitor) m_transportMonitor->Remove(header.GetSeqNum()); - } - // ACK whenever a send path exists, whether or not this transport also - // tracks its own sends: a receive-only transport (e.g. NetworkNode's SUB) - // has no monitor but must still ACK the sender's RELIABLE messages. - else if (m_sendTransport) { - xostringstream ss_ack; - DmqHeader ack; - ack.SetId(dmq::ACK_REMOTE_ID); - ack.SetSeqNum(header.GetSeqNum()); - ack.SetLength(0); - m_sendTransport->Send(ss_ack, ack); // takes m_mutex; m_recvMutex is held: same lock order - } - - return 0; - } - - NX_IP* m_ip = nullptr; - NX_PACKET_POOL* m_pool = nullptr; - NX_UDP_SOCKET m_socket; - TX_MUTEX m_mutex; ///< Socket setup and Send() state (target address) - TX_MUTEX m_recvMutex; ///< Held by Receive(); taken before m_mutex - - /// Receive buffer (header + payload), DMQ_UDP_BUFFER_SIZE. A member, not a - /// stack array: thread stacks on these targets are small. - UCHAR m_recvBuffer[dmq::UDP_BUFFER_SIZE]; - - ULONG m_targetIp = 0; - UINT m_port = 0; - - Type m_type = Type::PUB; - - ULONG m_recvTimeout = 1; // Default 1 tick - - ITransport* m_sendTransport = nullptr; - ITransport* m_recvTransport = nullptr; - ITransportMonitor* m_transportMonitor = nullptr; -}; - -} - -#endif // NETX_UDP_TRANSPORT_H \ No newline at end of file diff --git a/DelegateMQ/port/transport/nng/NngTransport.h b/DelegateMQ/port/transport/nng/NngTransport.h deleted file mode 100644 index 05f3a63..0000000 --- a/DelegateMQ/port/transport/nng/NngTransport.h +++ /dev/null @@ -1,355 +0,0 @@ -#ifndef NNG_TRANSPORT_H -#define NNG_TRANSPORT_H - -/// @file NngTransport.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// @brief NNG transport implementation for DelegateMQ. -/// -/// @details -/// This class implements the ITransport interface using the NNG (Nanomsg Next Gen) -/// lightweight messaging library. It supports multiple scalability protocols including -/// PAIR (1-to-1 bidrectional) and PUB/SUB (1-to-many unidirectional). -/// -/// Key Features: -/// 1. **Thread Safety**: Uses a `dmq::RecursiveMutex` to protect the NNG socket, -/// allowing safe concurrent access from the Send and Receive threads (NNG sockets -/// are not inherently thread-safe). -/// 2. **Scalability Protocols**: flexible configuration for different topologies: -/// * `PAIR_CLIENT`/`PAIR_SERVER`: Exclusive 1-to-1 connection. -/// * `PUB`/`SUB`: Efficient distribution to multiple subscribers. -/// 3. **Non-Blocking**: Uses asynchronous messaging patterns provided by NNG. -/// 4. **Reliability**: Integrates with `TransportMonitor` to providing sequence tracking -/// and ACKs even over PUB/SUB (when a return channel is available). -/// -/// @note Requires the `libnng` library. - -// Add Windows Sockets headers for htons/ntohs -#if defined(_WIN32) || defined(_WIN64) - #include - #pragma comment(lib, "ws2_32.lib") -#else - #include -#endif - -#include "delegate/DelegateOpt.h" -#include "port/transport/common/ITransport.h" -#include "port/transport/common/ITransportMonitor.h" -#include "port/transport/common/DmqHeader.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace dmq::transport { - -/// @brief NNG transport class. -/// @details Logic now executes directly on the caller's thread, protected by a mutex -/// to prevent concurrent access to the underlying NNG socket. -class NngTransport : public ITransport -{ -public: - enum class Type - { - PAIR_CLIENT, - PAIR_SERVER, - PUB, - SUB - }; - - NngTransport() : m_sendTransport(this), m_recvTransport(this) - { - } - - ~NngTransport() - { - Destroy(); - } - - int Create(Type type, const char* addr) - { - std::lock_guard lock(m_mutex); - - // Initialize NNG context - m_type = type; - - int rc = 0; - if (m_type == Type::PAIR_CLIENT) - { - rc = nng_pair0_open(&m_nngSocket); - if (rc != 0) { - std::cerr << "Failed to open NNG pair client socket: " << nng_strerror(rc) << std::endl; - return rc; - } - rc = nng_dial(m_nngSocket, addr, nullptr, 0); - if (rc != 0) { - std::cerr << "Failed to dial address: " << nng_strerror(rc) << std::endl; - nng_close(m_nngSocket); - return rc; - } - // Set recv timeout to avoid blocking forever - nng_duration timeout = 100; // 100ms - nng_socket_set_ms(m_nngSocket, NNG_OPT_RECVTIMEO, timeout); - } - else if (m_type == Type::PAIR_SERVER) - { - rc = nng_pair0_open(&m_nngSocket); - if (rc != 0) { - std::cerr << "Failed to open NNG pair server socket: " << nng_strerror(rc) << std::endl; - return rc; - } - rc = nng_listen(m_nngSocket, addr, nullptr, 0); - if (rc != 0) { - std::cerr << "Failed to listen on address: " << nng_strerror(rc) << std::endl; - return rc; - } - // Set recv timeout - nng_duration timeout = 100; // 100ms - nng_socket_set_ms(m_nngSocket, NNG_OPT_RECVTIMEO, timeout); - } - else if (m_type == Type::PUB) - { - rc = nng_pub0_open(&m_nngSocket); - if (rc != 0) { - std::cerr << "Failed to open NNG PUB socket: " << nng_strerror(rc) << std::endl; - return rc; - } - rc = nng_listen(m_nngSocket, addr, nullptr, 0); - if (rc != 0) { - std::cerr << "Failed to listen on address: " << nng_strerror(rc) << std::endl; - return rc; - } - } - else if (m_type == Type::SUB) - { - rc = nng_sub0_open(&m_nngSocket); - if (rc != 0) { - std::cerr << "Failed to open NNG SUB socket: " << nng_strerror(rc) << std::endl; - return rc; - } - rc = nng_dial(m_nngSocket, addr, nullptr, 0); - if (rc != 0) { - std::cerr << "Failed to dial address: " << nng_strerror(rc) << std::endl; - nng_close(m_nngSocket); - return rc; - } - - // Subscribe to all messages - rc = nng_socket_set(m_nngSocket, NNG_OPT_SUB_SUBSCRIBE, "", 0); - if (rc != 0) { - std::cerr << "Failed to set subscription filter: " << nng_strerror(rc) << std::endl; - return rc; - } - - // Set recv timeout - nng_duration timeout = 100; // 100ms - nng_socket_set_ms(m_nngSocket, NNG_OPT_RECVTIMEO, timeout); - } - else - { - std::cerr << "Invalid socket type" << std::endl; - return 1; - } - - return 0; - } - - void Close() - { - std::lock_guard lock(m_mutex); - - // Close the socket - if (nng_socket_id(m_nngSocket) != 0) { - nng_close(m_nngSocket); - } - m_nngSocket = NNG_SOCKET_INITIALIZER; - } - - void SetRecvTimeout(std::chrono::milliseconds timeout) - { - std::lock_guard lock(m_mutex); - if (nng_socket_id(m_nngSocket) != 0) - { - nng_duration ms = static_cast(timeout.count()); - nng_socket_set_ms(m_nngSocket, NNG_OPT_RECVTIMEO, ms); - } - } - - void Destroy() - { - Close(); - // NNG doesn't require explicit context terminations like ZMQ - } - - virtual int Send(dmq::xostringstream& os, const DmqHeader& header) override - { - std::lock_guard lock(m_mutex); - - if (os.bad() || os.fail() || nng_socket_id(m_nngSocket) == 0) { - return -1; - } - - if (m_type == Type::SUB) { - return -1; - } - - if (m_sendTransport != this) { - return -1; - } - - // Get payload data without string copy if possible - auto payload = os.str(); - if (payload.length() > (BUFFER_SIZE - DmqHeader::HEADER_SIZE)) { - return -1; - } - uint16_t payloadLen = static_cast(payload.length()); - - // Prepare header values in Network Byte Order - DmqHeader wireHeader = header; - wireHeader.SetLength(payloadLen); - wireHeader.Encode(m_sendBuffer); - - if (payloadLen > 0) { - memcpy(m_sendBuffer + DmqHeader::HEADER_SIZE, payload.data(), payloadLen); - } - - size_t totalSize = DmqHeader::HEADER_SIZE + payloadLen; - - // Send data using NNG - // Use NNG_FLAG_NONBLOCK to prevent deadlocks if peer is gone - int err = nng_send(m_nngSocket, (void*)m_sendBuffer, totalSize, NNG_FLAG_NONBLOCK); - if (err != 0) - { - // NNG_EAGAIN means queue full (congestion), treat as error to trigger retry logic - return -1; - } - - return 0; - } - - virtual int Receive(xstringstream& is, DmqHeader& header) override { - // Lock Guard - std::lock_guard lock(m_mutex); - - if (nng_socket_id(m_nngSocket) == 0) { - return -1; - } - - if (m_type == Type::PUB) { - return -1; - } - - if (m_recvTransport != this) { - return -1; - } - - size_t size = sizeof(m_buffer); - - // Receive with 100ms timeout (set in Create) - int err = nng_recv(m_nngSocket, m_buffer, &size, 0); - if (err == NNG_ETIMEDOUT || err == NNG_EAGAIN) { - return RECEIVE_NO_DATA; - } - if (err != 0) { - return -1; - } - - if (size < DmqHeader::HEADER_SIZE) { - return -1; - } - - // Never trust a size beyond what the buffer holds. - if (size > sizeof(m_buffer)) { - return -1; - } - - // 1. Read Header (Network Byte Order) - header.Decode(m_buffer); - - if (!header.IsValid()) { - return -1; - } - - // 2. Write payload - // One message per NNG message: the header length must match exactly. Anything - // else is malformed and must not be delivered (cut short) or ACKed. - uint16_t payloadSize = header.GetLength(); - if (payloadSize != size - DmqHeader::HEADER_SIZE) - return -1; - - if (payloadSize > 0) { - is.clear(); - is.str(""); - is.write(m_buffer + DmqHeader::HEADER_SIZE, payloadSize); - } - - if (header.GetId() == dmq::ACK_REMOTE_ID) - { - // Receiver ack'ed message. Remove sequence number from monitor. - if (m_transportMonitor) - m_transportMonitor->Remove(header.GetSeqNum()); - } - else - { - // ACK whenever a send path exists, whether or not this transport also - // tracks its own sends: a receive-only transport (e.g. NetworkNode's SUB) - // has no monitor but must still ACK the sender's RELIABLE messages. - if (m_sendTransport) - { - // Send header with received seqNum as the ack message - dmq::xostringstream ss_ack; - DmqHeader ack; - ack.SetId(dmq::ACK_REMOTE_ID); - ack.SetSeqNum(header.GetSeqNum()); - - // Note: Recursive mutex allows Send() here - m_sendTransport->Send(ss_ack, ack); - } - } - - return 0; // Success - } - - // Set a transport monitor for checking message ack - void SetTransportMonitor(ITransportMonitor* transportMonitor) - { - m_transportMonitor = transportMonitor; - } - - // Set an alternative send transport - void SetSendTransport(ITransport* sendTransport) - { - m_sendTransport = sendTransport; - } - - // Set an alternative receive transport - void SetRecvTransport(ITransport* recvTransport) - { - m_recvTransport = recvTransport; - } - -private: - nng_socket m_nngSocket = NNG_SOCKET_INITIALIZER; - Type m_type = Type::PAIR_CLIENT; - - // Mutex to protect non-thread-safe socket - dmq::RecursiveMutex m_mutex; - - ITransport* m_sendTransport = nullptr; - ITransport* m_recvTransport = nullptr; - ITransportMonitor* m_transportMonitor = nullptr; - - static const int BUFFER_SIZE = 4096; - char m_buffer[BUFFER_SIZE] = {}; - char m_sendBuffer[BUFFER_SIZE] = {}; -}; - -} // namespace dmq::transport - -#endif diff --git a/DelegateMQ/port/transport/serial/SerialTransport.h b/DelegateMQ/port/transport/serial/SerialTransport.h deleted file mode 100644 index 80bde51..0000000 --- a/DelegateMQ/port/transport/serial/SerialTransport.h +++ /dev/null @@ -1,245 +0,0 @@ -#ifndef SERIAL_TRANSPORT_H -#define SERIAL_TRANSPORT_H - -/// @file SerialTransport.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// @brief Libserialport-based transport implementation for DelegateMQ. -/// -/// @details -/// This class implements the ITransport interface using the cross-platform `libserialport` -/// library. It provides a reliable, packet-based communication layer over RS-232/UART -/// serial links. -/// -/// Key Features: -/// 1. **Thread-Safe Access**: Uses a recursive mutex to serialize access to the -/// underlying serial port, allowing concurrent Send/Receive calls from different threads. -/// 2. **Data Framing**: Encapsulates delegate arguments in a binary-safe frame structure: -/// `[Header (10 bytes)] + [Payload (N bytes)] + [CRC16 (2 bytes)]`. -/// 3. **Data Integrity**: Automatically calculates and verifies a 16-bit CRC for every -/// packet to detect transmission errors common in serial communication. -/// 4. **Reliability**: Integrates with `TransportMonitor` to track sequence numbers and -/// support ACK-based reliability when paired with the `RetryMonitor`. -/// -/// @note This class requires `libserialport` to be linked. - -#include "libserialport.h" -#include "delegate/DelegateOpt.h" -#include "port/transport/common/ITransport.h" -#include "port/transport/common/DmqHeader.h" -#include "port/transport/common/ITransportMonitor.h" -#include "extras/util/crc16.h" - -#include -#include -#include -#include -#include -#include - -namespace dmq::transport { - -class SerialTransport : public ITransport -{ -public: - SerialTransport() : m_sendTransport(this), m_recvTransport(this) {} - - ~SerialTransport() { Close(); } - - int Create(const char* portName, int baudRate) - { - std::lock_guard recvLock(m_recvMutex); - std::lock_guard lock(m_mutex); - Close(); // a second Create() replaces the port instead of leaking it - sp_return ret = sp_get_port_by_name(portName, &m_port); - if (ret != SP_OK) { - std::cerr << "SerialTransport: Could not find port " << portName << std::endl; - return -1; - } - - ret = sp_open(m_port, SP_MODE_READ_WRITE); - if (ret != SP_OK) { - std::cerr << "SerialTransport: Could not open port " << portName << std::endl; - sp_free_port(m_port); - m_port = nullptr; - return -1; - } - - sp_set_baudrate(m_port, baudRate); - sp_set_bits(m_port, 8); - sp_set_parity(m_port, SP_PARITY_NONE); - sp_set_stopbits(m_port, 1); - sp_set_flowcontrol(m_port, SP_FLOWCONTROL_NONE); - return 0; - } - - /// @details Waits for a Receive() in progress on another thread to return - /// (at most about a second: its reads time out), so the port is never - /// freed under it. - void Close() - { - std::lock_guard recvLock(m_recvMutex); - std::lock_guard lock(m_mutex); - if (m_port) { - sp_close(m_port); - sp_free_port(m_port); - m_port = nullptr; - } - } - - virtual int Send(dmq::xostringstream& os, const DmqHeader& header) override - { - std::lock_guard lock(m_mutex); - if (!m_port) return -1; - - DmqHeader headerCopy = header; - dmq::xstring payload = os.str(); - if (payload.length() > UINT16_MAX) return -1; - headerCopy.SetLength(static_cast(payload.length())); - - dmq::xostringstream ss(std::ios::in | std::ios::out | std::ios::binary); - - // SERIALIZE HEADER (Big Endian) - char headerBuf[DmqHeader::HEADER_SIZE]; - headerCopy.Encode(headerBuf); - ss.write(headerBuf, DmqHeader::HEADER_SIZE); - - // Payload - ss.write(payload.data(), payload.size()); - - // CRC (big-endian) - dmq::xstring packetWithoutCrc = ss.str(); - uint16_t crc = dmq::util::Crc16CalcBlock((unsigned char*)packetWithoutCrc.c_str(), (int)packetWithoutCrc.length(), 0xFFFF); - const char crcBytes[2] = { static_cast(crc >> 8), static_cast(crc & 0xFF) }; - ss.write(crcBytes, sizeof(crcBytes)); - - dmq::xstring packetData = ss.str(); - - int result = sp_blocking_write(m_port, packetData.c_str(), packetData.length(), 1000); - if (result != (int)packetData.length()) return -1; - - return 0; - } - - virtual int Receive(dmq::xstringstream& is, DmqHeader& header) override - { - // Held for the whole read so Close() can't free m_port under it. Send() - // uses m_mutex, so it's never blocked by an idle read. - std::lock_guard recvLock(m_recvMutex); - if (!m_port) return -1; - if (m_recvTransport != this) return -1; - - char headerBuf[DmqHeader::HEADER_SIZE]; - - // 1. Sync Loop: both marker bytes, tracked with a sliding previous byte - // so a stray 0xAA right before a real marker (0xAA 0xAA 0x55) still - // syncs on the real one. - const uint8_t markerHigh = (uint8_t)(DmqHeader::MARKER >> 8); - const uint8_t markerLow = (uint8_t)(DmqHeader::MARKER & 0xFF); - uint8_t prev = 0; - while (true) { - // Waiting for a frame start: nothing arriving is "no data", not an - // error. After a 0xAA, give the next byte longer to arrive. - char b = 0; - int r = sp_blocking_read(m_port, &b, 1, prev == markerHigh ? 100 : 10); - if (r == 0) { - if (prev == markerHigh) { prev = 0; continue; } // lone 0xAA - return RECEIVE_NO_DATA; - } - if (r < 0) return -1; - - if (prev == markerHigh && (uint8_t)b == markerLow) { - headerBuf[0] = (char)markerHigh; - headerBuf[1] = (char)markerLow; - break; - } - prev = (uint8_t)b; - } - - // 2. Read Rest of Header - // INCREASED TIMEOUT: 1000ms (was 100ms) to allow OS latency - if (!ReadExact(headerBuf + 2, DmqHeader::HEADER_SIZE - 2, 1000)) - return -1; - - // 3. Deserialize - header.Decode(headerBuf); - - if (!header.IsValid()) return -1; - - // 4. Payload - uint16_t len = header.GetLength(); - if (len > 0) { - if (len > BUFFER_SIZE) return -1; - // INCREASED TIMEOUT: 1000ms - if (!ReadExact(m_buffer, len, 1000)) return -1; - is.write(m_buffer, len); - } - - // 5. CRC Check (big-endian) - unsigned char crcBytes[2] = {}; - // INCREASED TIMEOUT: 500ms - if (!ReadExact(reinterpret_cast(crcBytes), sizeof(crcBytes), 500)) return -1; - const uint16_t receivedCrc = static_cast((crcBytes[0] << 8) | crcBytes[1]); - - uint16_t calcCrc = dmq::util::Crc16CalcBlock((unsigned char*)headerBuf, DmqHeader::HEADER_SIZE, 0xFFFF); - if (len > 0) calcCrc = dmq::util::Crc16CalcBlock((unsigned char*)m_buffer, len, calcCrc); - - if (receivedCrc != calcCrc) { - std::cerr << "CRC Mismatch" << std::endl; - return -1; - } - - // 6. ACKs - if (header.GetId() == dmq::ACK_REMOTE_ID) { - if (m_transportMonitor) m_transportMonitor->Remove(header.GetSeqNum()); - } - else if (m_sendTransport) { - dmq::xostringstream ss_ack; - DmqHeader ack; - ack.SetId(dmq::ACK_REMOTE_ID); - ack.SetSeqNum(header.GetSeqNum()); - m_sendTransport->Send(ss_ack, ack); - } - return 0; - } - - void SetRecvTimeout(std::chrono::milliseconds timeout) - { - m_recvTimeout = timeout; - } - - void SetTransportMonitor(ITransportMonitor* tm) { m_transportMonitor = tm; } - void SetSendTransport(ITransport* st) { m_sendTransport = st; } - void SetRecvTransport(ITransport* rt) { m_recvTransport = rt; } - -private: - bool ReadExact(char* dest, size_t size, unsigned int timeoutMs) - { - size_t totalRead = 0; - // Keep attempting to read until we have 'size' bytes - while (totalRead < size) - { - if (!m_port) return false; - int ret = sp_blocking_read(m_port, dest + totalRead, size - totalRead, timeoutMs); - if (ret < 0) return false; // Error - if (ret == 0) return false; // Timeout - totalRead += ret; - } - return true; - } - - sp_port* m_port = nullptr; - std::recursive_mutex m_mutex; ///< Port open/close and Send() - std::recursive_mutex m_recvMutex; ///< Held by Receive(); Close() takes it first - ITransport* m_sendTransport = nullptr; - ITransport* m_recvTransport = nullptr; - ITransportMonitor* m_transportMonitor = nullptr; - std::chrono::milliseconds m_recvTimeout = std::chrono::milliseconds(2000); - static const int BUFFER_SIZE = 4096; - char m_buffer[BUFFER_SIZE] = { 0 }; -}; - -} // namespace dmq::transport - -#endif diff --git a/DelegateMQ/port/transport/stm32-uart/Stm32UartTransport.h b/DelegateMQ/port/transport/stm32-uart/Stm32UartTransport.h deleted file mode 100644 index 04ad3cf..0000000 --- a/DelegateMQ/port/transport/stm32-uart/Stm32UartTransport.h +++ /dev/null @@ -1,347 +0,0 @@ -#ifndef STM32_UART_TRANSPORT_H -#define STM32_UART_TRANSPORT_H - -/// @file Stm32UartTransport.h -/// @brief STM32 HAL UART transport implementation for DelegateMQ (FreeRTOS). -/// -/// @details -/// This class provides a robust, thread-safe transport layer for serial communication -/// on STM32 microcontrollers running FreeRTOS. -/// -/// **Key Architecture: Interrupt-Driven Ring Buffer** -/// Instead of polling the UART (which wastes CPU) or using blocking HAL calls -/// (which starve other FreeRTOS tasks), this implementation uses: -/// 1. **UART RX Interrupt:** Fires immediately when a byte arrives, pushing it into a `UartRingBuffer`. -/// 2. **Binary Semaphore:** The `Receive()` task sleeps on this semaphore. It is only woken up -/// by the ISR when data is actually available. -/// 3. **Recursive Mutex:** Protects the `Send()` function to ensure atomic packet transmission -/// even if multiple threads try to send simultaneously. -/// -/// **Data Integrity:** -/// * Implements strict `0xAA 0x55` framing synchronization. -/// * Calculates and verifies 16-bit CRC for every packet (sent big-endian, after -/// the payload). -/// * Sizes and timeouts come from DMQ_UART_* in DelegateMQConfig.h. -/// * Handles reliable delivery via `TransportMonitor` (ACKs/Retries). - -#include "stm32f4xx_hal.h" -#include "stm32f4xx_hal_uart.h" -#include "delegate/DelegateOpt.h" -#include "port/transport/common/DmqHeader.h" -#include "port/transport/common/ITransport.h" -#include "port/transport/common/ITransportMonitor.h" -#include "extras/util/crc16.h" - -// FreeRTOS Includes -#include "FreeRTOS.h" -#include "semphr.h" -#include "task.h" - -#include -#include - -namespace dmq::transport { - -// ---------------------------------------------------------------------------- -// Forward Declarations & Global Hook -// ---------------------------------------------------------------------------- -class Stm32UartTransport; - -} // namespace dmq::transport - -// Global pointer to the active transport instance. -// This is defined in main.cpp and used by the C-style HAL Interrupt Callback -// to route the hardware interrupt back into the C++ class. -extern dmq::transport::Stm32UartTransport* g_uartTransportInstance; - -namespace dmq::transport { - -// ============================================================================ -// UartRingBuffer -// ============================================================================ -/// @brief A lightweight, thread-safe (Single Producer / Single Consumer) Ring Buffer. -/// @tparam Size The size of the buffer in bytes. Must be large enough to hold -/// bursts of data (e.g., 1024 bytes) to prevent overrun. -template -class UartRingBuffer { -public: - /// Push a byte into the buffer (Called from ISR). - /// @return false if the buffer was full and the byte was dropped. - bool Put(uint8_t data) { - size_t next_head = (m_head + 1) % Size; - if (next_head == m_tail) return false; // Buffer Full - m_buffer[m_head] = data; - m_head = next_head; - return true; - } - - /// Pop a byte from the buffer (Called from Consumer Task). - bool Get(uint8_t& data) { - if (m_head == m_tail) return false; // Buffer Empty - data = m_buffer[m_tail]; - m_tail = (m_tail + 1) % Size; - return true; - } - - void Clear() { m_head = m_tail = 0; } - -private: - volatile uint8_t m_buffer[Size]; - volatile size_t m_head = 0; - volatile size_t m_tail = 0; -}; - -// ============================================================================ -// Stm32UartTransport Class -// ============================================================================ -class Stm32UartTransport : public ITransport -{ -public: - Stm32UartTransport() : m_huart(nullptr), m_sendTransport(this), m_recvTransport(this) {} - Stm32UartTransport(UART_HandleTypeDef* huart) : m_huart(huart), m_sendTransport(this), m_recvTransport(this) {} - - ~Stm32UartTransport() { - if (m_mutex) vSemaphoreDelete(m_mutex); - if (m_rxSemaphore) vSemaphoreDelete(m_rxSemaphore); - g_uartTransportInstance = nullptr; - } - - /// @brief Initialize the Transport and enable UART Interrupts. - /// @param huart Pointer to the HAL UART handle (e.g., &huart6). - /// @return 0 on success, -1 on failure. - int Create(UART_HandleTypeDef* huart) { - m_huart = huart; - g_uartTransportInstance = this; // Hook global pointer for ISR - - // Create OS primitives - if (!m_mutex) m_mutex = xSemaphoreCreateRecursiveMutex(); - if (!m_rxSemaphore) m_rxSemaphore = xSemaphoreCreateBinary(); - - if (!m_huart || !m_mutex || !m_rxSemaphore) return -1; - - // Clear potential hardware error flags from startup noise - __HAL_UART_CLEAR_OREFLAG(m_huart); - __HAL_UART_CLEAR_NEFLAG(m_huart); - __HAL_UART_CLEAR_FEFLAG(m_huart); - - // START RECEIVING: Enable RX Interrupt for the first byte. - // This kicks off the chain; subsequent bytes are re-armed in OnRxCplt. - if (HAL_UART_Receive_IT(m_huart, &m_rxByte, 1) != HAL_OK) return -1; - - return 0; - } - - virtual void Close() { - // Optional: Disable UART interrupts here if destroying the transport. - } - - // ------------------------------------------------------------------------ - // Send() Implementation - // ------------------------------------------------------------------------ - virtual int Send(dmq::xostringstream& os, const DmqHeader& header) override { - if (os.bad() || os.fail()) return -1; - if (!m_huart || !m_mutex) return -1; - - // CRITICAL SECTION: Protect UART TX hardware - if (xSemaphoreTakeRecursive(m_mutex, portMAX_DELAY) != pdTRUE) return -1; - - const uint32_t txTimeout = static_cast(dmq::UART_TX_TIMEOUT.count()); - - // 1. Prepare Packet Structure - dmq::xstring payload = os.str(); - if (payload.length() > BUFFER_SIZE) { // receiver's reassembly limit - xSemaphoreGiveRecursive(m_mutex); - return -1; - } - DmqHeader headerCopy = header; - headerCopy.SetLength((uint16_t)payload.length()); - - // Serialize Header (Network Byte Order) - uint8_t packet[DmqHeader::HEADER_SIZE]; - headerCopy.Encode(packet); - - // 2. Send Header - if (HAL_UART_Transmit(m_huart, packet, DmqHeader::HEADER_SIZE, txTimeout) != HAL_OK) { - xSemaphoreGiveRecursive(m_mutex); return -1; - } - - // 3. Send Payload - if (payload.length() > 0) { - if (HAL_UART_Transmit(m_huart, (uint8_t*)payload.data(), (uint16_t)payload.length(), txTimeout) != HAL_OK) { - xSemaphoreGiveRecursive(m_mutex); return -1; - } - } - - // 4. Calculate and Send CRC (Required for PC communication) - uint16_t crc = dmq::util::Crc16CalcBlock(packet, DmqHeader::HEADER_SIZE, 0xFFFF); - if (payload.length() > 0) crc = dmq::util::Crc16CalcBlock((uint8_t*)payload.data(), payload.length(), crc); - - const uint8_t crcBytes[2] = { static_cast(crc >> 8), static_cast(crc) }; // big-endian - if (HAL_UART_Transmit(m_huart, const_cast(crcBytes), 2, txTimeout) != HAL_OK) { - xSemaphoreGiveRecursive(m_mutex); return -1; - } - - xSemaphoreGiveRecursive(m_mutex); - return 0; - } - - // ------------------------------------------------------------------------ - // Receive() Implementation - // ------------------------------------------------------------------------ - virtual int Receive(dmq::xstringstream& is, DmqHeader& header) override { - if (m_recvTransport != this) return -1; - - uint8_t headerBuf[DmqHeader::HEADER_SIZE]; - const uint8_t markerHigh = (uint8_t)(DmqHeader::MARKER >> 8); - const uint8_t markerLow = (uint8_t)(DmqHeader::MARKER & 0xFF); - const TickType_t frameTimeout = pdMS_TO_TICKS(dmq::UART_FRAME_TIMEOUT.count()); - - // 1. Sync Loop: both marker bytes, so a stray 0xAA in other data doesn't - // start a frame. Waits indefinitely (sleeping on the semaphore while the - // ring buffer is empty) until a 0xAA arrives; only the byte after it - // must come within the frame timeout. Stray bytes followed by an idle - // line are discarded, not reported as an error. - uint8_t prev = 0; - while (true) { - uint8_t b = 0; - const TickType_t wait = (prev == markerHigh) ? frameTimeout : portMAX_DELAY; - if (!ReadByte(b, wait)) { - if (prev == markerHigh) { prev = 0; continue; } // lone 0xAA: keep syncing - return -1; - } - if (prev == markerHigh && b == markerLow) break; - prev = b; - } - headerBuf[0] = markerHigh; - headerBuf[1] = markerLow; - - // 2. Read Rest of Header. Each later byte must arrive within the frame - // timeout: a frame cut short by lost bytes is dropped instead of - // swallowing the start of the next one. - for (int i = 2; i < (int)DmqHeader::HEADER_SIZE; i++) { - if (!ReadByte(headerBuf[i], frameTimeout)) return -1; - } - - // Deserialize Header - header.Decode(headerBuf); - - if (!header.IsValid()) return -1; - - // 3. Read Payload - uint16_t len = header.GetLength(); - if (len > 0) { - if (len > BUFFER_SIZE) return -1; - for (int i = 0; i < len; i++) { - if (!ReadByte(m_tempRxBuffer[i], frameTimeout)) return -1; - } - is.clear(); is.str(""); is.write((char*)m_tempRxBuffer, len); - } - - // 4. Read & Verify CRC (big-endian) - uint8_t crcBytes[2]; - if (!ReadByte(crcBytes[0], frameTimeout)) return -1; - if (!ReadByte(crcBytes[1], frameTimeout)) return -1; - const uint16_t receivedCrc = static_cast((crcBytes[0] << 8) | crcBytes[1]); - - uint16_t calcCrc = dmq::util::Crc16CalcBlock(headerBuf, DmqHeader::HEADER_SIZE, 0xFFFF); - if (len > 0) calcCrc = dmq::util::Crc16CalcBlock(m_tempRxBuffer, len, calcCrc); - if (receivedCrc != calcCrc) return -1; - - // 5. Handle ACKs - if (header.GetId() == dmq::ACK_REMOTE_ID) { - if (m_transportMonitor) m_transportMonitor->Remove(header.GetSeqNum()); - } - // ACK whenever a send path exists, whether or not this transport also - // tracks its own sends: a receive-only transport (e.g. NetworkNode's SUB) - // has no monitor but must still ACK the sender's RELIABLE messages. - else if (m_sendTransport) { - // Auto-Reply with ACK - dmq::xostringstream ss; - DmqHeader ack; - ack.SetId(dmq::ACK_REMOTE_ID); - ack.SetSeqNum(header.GetSeqNum()); - m_sendTransport->Send(ss, ack); - } - return 0; - } - - // ------------------------------------------------------------------------ - // Interrupt Handler - // ------------------------------------------------------------------------ - /// @brief Called by HAL_UART_RxCpltCallback when a byte arrives. - void OnRxCplt() { - BaseType_t xHigherPriorityTaskWoken = pdFALSE; - - // 1. Push data to thread-safe buffer. A full buffer drops the byte (the - // frame then fails its CRC); count it so the app can see it happening. - if (!m_ringBuffer.Put(m_rxByte)) - m_rxOverflows.fetch_add(1, std::memory_order_relaxed); - - // 2. Wake up the Receive() task immediately - xSemaphoreGiveFromISR(m_rxSemaphore, &xHigherPriorityTaskWoken); - - // 3. Re-arm interrupt for the next byte - HAL_UART_Receive_IT(m_huart, &m_rxByte, 1); - - // 4. Context Switch if necessary - portYIELD_FROM_ISR(xHigherPriorityTaskWoken); - } - - /// @brief Called by HAL_UART_ErrorCallback. ISR-safe: no OS calls. - /// @details A blocking UART error (e.g. overrun) makes the HAL abort the - /// interrupt-driven receive, so no further bytes would ever arrive. Clear - /// the error flags and re-arm single-byte reception. For non-blocking - /// errors (noise/framing/parity) the HAL keeps receiving, RxState stays - /// busy, and re-arming is skipped. Any frame the error corrupted is - /// rejected by the CRC check in Receive(). - void OnRxError() { - if (!m_huart) return; - - __HAL_UART_CLEAR_OREFLAG(m_huart); - __HAL_UART_CLEAR_NEFLAG(m_huart); - __HAL_UART_CLEAR_FEFLAG(m_huart); - - if (m_huart->RxState == HAL_UART_STATE_READY) - HAL_UART_Receive_IT(m_huart, &m_rxByte, 1); - } - - void SetTransportMonitor(ITransportMonitor* tm) { m_transportMonitor = tm; } - void SetSendTransport(ITransport* st) { m_sendTransport = st; } - void SetRecvTransport(ITransport* rt) { m_recvTransport = rt; } - - /// @brief Received bytes dropped because the RX ring buffer was full. - /// Non-zero means DMQ_UART_RX_RING_SIZE is too small for the traffic, or - /// Receive() isn't called often enough. - uint32_t GetRxOverflowCount() const { return m_rxOverflows.load(std::memory_order_relaxed); } - -private: - /// @brief Read a byte from the Ring Buffer, sleeping on the RX semaphore - /// while it's empty. - /// @param timeout Most to wait for each wake-up (portMAX_DELAY = forever). - /// @return false if no byte arrived within the timeout. - bool ReadByte(uint8_t& out, TickType_t timeout) { - while (true) { - if (m_ringBuffer.Get(out)) return true; - if (xSemaphoreTake(m_rxSemaphore, timeout) != pdTRUE) return false; - } - } - - UART_HandleTypeDef* m_huart; - SemaphoreHandle_t m_mutex = nullptr; // Mutex for Send() - SemaphoreHandle_t m_rxSemaphore = nullptr; // Semaphore for Receive() blocking - - uint8_t m_rxByte; // Temp byte for HAL ISR - UartRingBuffer m_ringBuffer; - std::atomic m_rxOverflows{ 0 }; - - static constexpr size_t BUFFER_SIZE = dmq::UART_MAX_PAYLOAD; - uint8_t m_tempRxBuffer[BUFFER_SIZE]; // Payload reassembly buffer - - ITransport* m_sendTransport; - ITransport* m_recvTransport; - ITransportMonitor* m_transportMonitor = nullptr; -}; - -} // namespace dmq::transport - -#endif // STM32_UART_TRANSPORT_H diff --git a/DelegateMQ/port/transport/win32-pipe/Win32PipeTransport.h b/DelegateMQ/port/transport/win32-pipe/Win32PipeTransport.h deleted file mode 100644 index f739ca6..0000000 --- a/DelegateMQ/port/transport/win32-pipe/Win32PipeTransport.h +++ /dev/null @@ -1,225 +0,0 @@ -#ifndef WIN32_PIPE_TRANSPORT_H -#define WIN32_PIPE_TRANSPORT_H - -/// @file -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// Transport callable argument data to/from a remote using Win32 data pipe. - -#if !defined(_WIN32) && !defined(_WIN64) - #error This code must be compiled as a Win32 or Win64 application. -#endif - -// Include Winsock for htons/ntohs consistency -#include -#pragma comment(lib, "ws2_32.lib") - -#include "port/transport/common/ITransport.h" -#include "port/transport/common/DmqHeader.h" -#include -#include -#include -#include -#include - -namespace dmq::transport { - -/// @brief Win32 data pipe transport example. -class Win32PipeTransport : public ITransport -{ -public: - enum class Type - { - PUB, - SUB - }; - - Win32PipeTransport() = default; - - ~Win32PipeTransport() - { - Close(); - } - - int Create(Type type, LPCSTR pipeName) - { - const std::lock_guard lock(m_mutex); - m_type = type; - if (type == Type::PUB) - { - // Connect to an existing pipe (Client) - m_hPipe = CreateFile( - pipeName, // pipe name - GENERIC_READ | // read and write access - GENERIC_WRITE, - 0, // no sharing - NULL, // default security attributes - OPEN_EXISTING, // opens existing pipe - 0, // default attributes - NULL); // no template file - - // A client handle opens in byte-read, blocking mode. Match the server's - // message-read, non-blocking mode so a duplex client can Receive(): one - // ReadFile returns exactly one message, and an idle read doesn't block - // (while holding m_mutex) a concurrent Send(). - if (m_hPipe != INVALID_HANDLE_VALUE) - { - DWORD mode = PIPE_READMODE_MESSAGE | PIPE_NOWAIT; - if (!SetNamedPipeHandleState(m_hPipe, &mode, NULL, NULL)) - { - CloseHandle(m_hPipe); - m_hPipe = INVALID_HANDLE_VALUE; - } - } - } - else if (type == Type::SUB) - { - // Create named pipe (Server) - m_hPipe = CreateNamedPipe( - pipeName, // pipe name - PIPE_ACCESS_DUPLEX, // read/write access - PIPE_TYPE_MESSAGE | // message type pipe - PIPE_READMODE_MESSAGE | // message-read mode - PIPE_NOWAIT, // non-blocking mode - PIPE_UNLIMITED_INSTANCES, // max. instances - BUFFER_SIZE, // output buffer size - BUFFER_SIZE, // input buffer size - 0, // client time-out - NULL); // default security attribute - } - - if (m_hPipe == INVALID_HANDLE_VALUE) - { - // DWORD dwError = GetLastError(); - // std::cout << "Create pipe failed: " << dwError << std::endl; - return -1; - } - return 0; - } - - void Close() - { - const std::lock_guard lock(m_mutex); - if (m_hPipe != INVALID_HANDLE_VALUE) - { - // DisconnectNamedPipe is a server (SUB) only API; skip for client (PUB) - if (m_type == Type::SUB) - DisconnectNamedPipe(m_hPipe); - CloseHandle(m_hPipe); - m_hPipe = INVALID_HANDLE_VALUE; - } - } - - void SetRecvTimeout(std::chrono::milliseconds timeout) - { - const std::lock_guard lock(m_mutex); - // Named pipes on Windows use different mechanisms for timeouts - // than sockets (e.g. SetCommTimeouts for serial or ReadFile with OVERLAPPED). - // Since this transport currently uses PIPE_NOWAIT, we'll just store it. - m_recvTimeout = timeout; - } - - virtual int Send(dmq::xostringstream& os, const DmqHeader& header) override - { - const std::lock_guard lock(m_mutex); - if (os.bad() || os.fail()) - return -1; - - if (m_hPipe == INVALID_HANDLE_VALUE) return -1; - - // Get payload data without string copy if possible - auto payload = os.str(); - if (payload.length() > (BUFFER_SIZE - DmqHeader::HEADER_SIZE)) { - std::cerr << "Error: Payload too large for static buffer." << std::endl; - return -1; - } - uint16_t payloadLen = static_cast(payload.length()); - - // Prepare header values in Network Byte Order - DmqHeader wireHeader = header; - wireHeader.SetLength(payloadLen); - wireHeader.Encode(m_sendBuffer); - - // Copy payload after header - if (payloadLen > 0) { - memcpy(m_sendBuffer + DmqHeader::HEADER_SIZE, payload.data(), payloadLen); - } - - DWORD totalSize = static_cast(DmqHeader::HEADER_SIZE + payloadLen); - DWORD sentLen = 0; - BOOL success = WriteFile(m_hPipe, m_sendBuffer, totalSize, &sentLen, NULL); - - if (!success || sentLen != totalSize) - return -1; - - return 0; - } - - virtual int Receive(dmq::xstringstream& is, DmqHeader& header) override - { - const std::lock_guard lock(m_mutex); - if (m_hPipe == INVALID_HANDLE_VALUE) return -1; - - // Check/Accept connection (server only; ConnectNamedPipe is a server API) - // Note: In non-blocking mode (PIPE_NOWAIT), this returns false immediately - // if connected, or error if already connected. - if (m_type == Type::SUB) - { - BOOL connected = ConnectNamedPipe(m_hPipe, NULL) ? - TRUE : (GetLastError() == ERROR_PIPE_CONNECTED); - - // If not connected yet, we can't read. - if (connected == FALSE && GetLastError() == ERROR_NO_DATA) { - return RECEIVE_NO_DATA; - } - } - - DWORD size = 0; - BOOL success = ReadFile(m_hPipe, m_buffer, BUFFER_SIZE, &size, NULL); - - if (success == FALSE) { - // PIPE_NOWAIT: no message waiting, or no client connected yet. - const DWORD err = GetLastError(); - if (err == ERROR_NO_DATA || err == ERROR_PIPE_LISTENING) - return RECEIVE_NO_DATA; - return -1; // includes ERROR_MORE_DATA: message larger than the buffer - } - if (size < DmqHeader::HEADER_SIZE) - return -1; - - // 1. Read Header directly from m_buffer (Network Byte Order) - header.Decode(m_buffer); - - if (!header.IsValid()) { - return -1; - } - - // 2. Write payload to provided stream. Message-mode pipe: one message - // per read, so the header length must match exactly. - uint16_t payloadSize = header.GetLength(); - if (payloadSize != size - DmqHeader::HEADER_SIZE) - return -1; - - if (payloadSize > 0) { - is.write(m_buffer + DmqHeader::HEADER_SIZE, payloadSize); - } - - return 0; - } - -private: - // Increase buffer to Max Packet Size (64KB) to avoid truncation - static const int BUFFER_SIZE = 65536; - char m_buffer[BUFFER_SIZE] = { 0 }; - char m_sendBuffer[BUFFER_SIZE] = { 0 }; - - Type m_type = Type::PUB; - HANDLE m_hPipe = INVALID_HANDLE_VALUE; - std::chrono::milliseconds m_recvTimeout = std::chrono::milliseconds(2000); - dmq::RecursiveMutex m_mutex; -}; - -} // namespace dmq::transport - -#endif diff --git a/DelegateMQ/port/transport/win32-tcp/Win32TcpTransport.h b/DelegateMQ/port/transport/win32-tcp/Win32TcpTransport.h deleted file mode 100644 index 12dc55c..0000000 --- a/DelegateMQ/port/transport/win32-tcp/Win32TcpTransport.h +++ /dev/null @@ -1,398 +0,0 @@ -#ifndef WIN32_TCP_TRANSPORT_H -#define WIN32_TCP_TRANSPORT_H - -/// @file Win32TcpTransport.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// @brief Win32 TCP transport implementation for DelegateMQ. -/// -/// @details -/// This class implements the ITransport interface using Windows Sockets (Winsock2). -/// It supports both CLIENT and SERVER modes for transmitting serialized delegate data. -/// In SERVER mode, it supports multiple simultaneous client connections and broadcasts -/// outgoing messages to all connected participants. -/// -/// Key Features: -/// 1. **Direct I/O**: Executes socket operations directly on the calling thread, -/// relying on OS-level thread safety to avoid deadlocks. -/// 2. **Reliability Support**: Integrates with `TransportMonitor` to track sequence -/// numbers and acknowledge (ACK) receipts. -/// 3. **Non-Blocking I/O**: Utilizes `select()` in the receive loop to prevent -/// thread blocking when no data is available, facilitating clean shutdowns. -/// 4. **Multi-Client Multiplexing**: SERVER mode manages a list of clients and -/// polls them for data using `select()`. -/// 5. **Socket Management**: Use WinsockConnect class in main() for `WSAStartup` and -/// socket creation/cleanup. - -#if !defined(_WIN32) && !defined(_WIN64) -#error This code must be compiled as a Win32 or Win64 application. -#endif - -#include -#include -#pragma comment(lib, "ws2_32.lib") - -#include "port/transport/common/ITransport.h" -#include "port/transport/common/ITransportMonitor.h" -#include "port/transport/common/DmqHeader.h" -#include -#include -#include -#include -#include -#include -#include -#include - -namespace dmq::transport { - -/// @brief A TCP transport implementation for Win32 using Winsock. -class Win32TcpTransport : public ITransport -{ - XALLOCATOR -public: - enum class Type - { - SERVER, - CLIENT - }; - - Win32TcpTransport() : m_sendTransport(this), m_recvTransport(this) - { - } - - ~Win32TcpTransport() - { - Close(); - } - - /// @brief Create a TCP transport. - /// @param type SERVER or CLIENT. - /// @param addr The IP address string. - /// @param port The TCP port. - /// @return 0 on success, -1 on failure. - int Create(Type type, LPCSTR addr, USHORT port) - { - Close(); // a second Create() replaces the sockets instead of leaking them - m_type = type; - sockaddr_in service; - service.sin_family = AF_INET; - service.sin_port = htons(port); - inet_pton(AF_INET, addr, &service.sin_addr); - - if (type == Type::SERVER) - { - m_listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); - if (m_listenSocket == INVALID_SOCKET) return -1; - - // Allow address reuse to facilitate quick restarts during development - int opt = 1; - setsockopt(m_listenSocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&opt, sizeof(opt)); - - if (bind(m_listenSocket, (SOCKADDR*)&service, sizeof(service)) == SOCKET_ERROR) - { - std::cerr << "Win32TcpTransport: Bind failed: " << WSAGetLastError() << std::endl; - Close(); - return -1; - } - - if (listen(m_listenSocket, SOMAXCONN) == SOCKET_ERROR) { - std::cerr << "Win32TcpTransport: Listen failed." << std::endl; - Close(); - return -1; - } - std::cout << "Win32TcpTransport: Server listening on " << port << "..." << std::endl; - } - else if (type == Type::CLIENT) - { - m_clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); - if (connect(m_clientSocket, (SOCKADDR*)&service, sizeof(service)) == SOCKET_ERROR) - { - // Silent fail for clients to support polling/retries in application layer - closesocket(m_clientSocket); - m_clientSocket = INVALID_SOCKET; - return -1; - } - std::cout << "Win32TcpTransport: Client connected to " << addr << ":" << port << std::endl; - - DWORD timeout = 2000; - setsockopt(m_clientSocket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof(timeout)); - } - - return 0; - } - - /// @brief Close all sockets and clean up. - void Close() - { - // m_mutex: Receive() may close the client socket on another thread - const std::lock_guard lock(m_mutex); - - // Close Client Socket - if (m_clientSocket != INVALID_SOCKET) { - shutdown(m_clientSocket, SD_BOTH); - closesocket(m_clientSocket); - m_clientSocket = INVALID_SOCKET; - } - - // Close all server-accepted clients - { - for (auto s : m_serverClients) { - shutdown(s, SD_BOTH); - closesocket(s); - } - m_serverClients.clear(); - } - - // Close Listen Socket - if (m_listenSocket != INVALID_SOCKET) { - closesocket(m_listenSocket); - m_listenSocket = INVALID_SOCKET; - } - } - - /// @brief Set the receive timeout for all active sockets. - void SetRecvTimeout(std::chrono::milliseconds timeout) - { - m_recvTimeoutMs = static_cast(timeout.count()); - if (m_clientSocket != INVALID_SOCKET) - { - setsockopt(m_clientSocket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&m_recvTimeoutMs, sizeof(m_recvTimeoutMs)); - } - - const std::lock_guard lock(m_mutex); - for (auto s : m_serverClients) { - setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (const char*)&m_recvTimeoutMs, sizeof(m_recvTimeoutMs)); - } - } - - /// @brief Send data over the TCP link. - /// @details In SERVER mode, this broadcasts to all connected clients. - virtual int Send(dmq::xostringstream& os, const DmqHeader& header) override - { - // m_mutex guards m_sendBuffer and keeps frames from different threads - // (including ACKs sent by Receive()) from interleaving on the stream. - const std::lock_guard lock(m_mutex); - if (m_type == Type::CLIENT) { - return SendToSocket(m_clientSocket, os, header); - } else { - int lastErr = 0; - for (auto s : m_serverClients) { - if (SendToSocket(s, os, header) != 0) lastErr = -1; - } - return lastErr; - } - } - - /// @brief Receive data from the TCP link. - virtual int Receive(dmq::xstringstream& is, DmqHeader& header) override - { - if (m_type == Type::SERVER) { - return ReceiveServer(is, header); - } else { - if (m_clientSocket == INVALID_SOCKET) { - // The connection was dropped (see below). Wait out one receive - // timeout before reporting it again, so a caller polling in a - // tight loop (RemoteDispatcher's receive thread) doesn't spin. - std::this_thread::sleep_for(std::chrono::milliseconds(m_recvTimeoutMs)); - return -1; - } - int result = ReceiveSocket(m_clientSocket, is, header); - if (result == -2) { - // Disconnected, or the stream lost framing (bad header, partial - // frame). Either way nothing more on it can be trusted. Close it: - // a shut-down but still open socket stays readable at EOF, so the - // next select() would return at once and the caller would spin. - const std::lock_guard lock(m_mutex); - if (m_clientSocket != INVALID_SOCKET) { - shutdown(m_clientSocket, SD_BOTH); - closesocket(m_clientSocket); - m_clientSocket = INVALID_SOCKET; - } - } - return result; - } - } - - void SetTransportMonitor(ITransportMonitor* tm) { m_transportMonitor = tm; } - void SetSendTransport(ITransport* st) { m_sendTransport = st; } - void SetRecvTransport(ITransport* rt) { m_recvTransport = rt; } - -private: - /// @brief Internal helper to send to a specific socket. - int SendToSocket(SOCKET s, dmq::xostringstream& os, const DmqHeader& header) { - if (s == INVALID_SOCKET) return -1; - - // Get payload data without string copy if possible - auto payload = os.str(); - if (payload.length() > (BUFFER_SIZE - DmqHeader::HEADER_SIZE)) { - std::cerr << "Error: Payload too large for static buffer." << std::endl; - return -1; - } - uint16_t payloadLen = static_cast(payload.length()); - - // Prepare header values in Network Byte Order - DmqHeader wireHeader = header; - wireHeader.SetLength(payloadLen); - wireHeader.Encode(m_sendBuffer); - - // Copy payload after header - if (payloadLen > 0) { - memcpy(m_sendBuffer + DmqHeader::HEADER_SIZE, payload.data(), payloadLen); - } - - int totalSize = DmqHeader::HEADER_SIZE + payloadLen; - const char* ptr = m_sendBuffer; - int remaining = totalSize; - - while (remaining > 0) - { - int sent = send(s, ptr, remaining, 0); - if (sent == SOCKET_ERROR) return -1; - ptr += sent; - remaining -= sent; - } - - return 0; - } - - /// @brief Internal helper to handle server-side multiplexing. - int ReceiveServer(dmq::xstringstream& is, DmqHeader& header) { - // 1. Lazy Accept: Check for new client connections - TIMEVAL tv = { 0, 1000 }; // 1ms poll - fd_set fds; - FD_ZERO(&fds); - FD_SET(m_listenSocket, &fds); - - if (select(0, &fds, NULL, NULL, &tv) > 0) { - SOCKET client = accept(m_listenSocket, NULL, NULL); - if (client != INVALID_SOCKET) { - std::cout << "Win32TcpTransport: Accepted client connection." << std::endl; - setsockopt(client, SOL_SOCKET, SO_RCVTIMEO, (const char*)&m_recvTimeoutMs, sizeof(m_recvTimeoutMs)); - const std::lock_guard lock(m_mutex); - m_serverClients.push_back(client); - } - } - - // 2. Poll all connected clients for data - fd_set readfds; - FD_ZERO(&readfds); - { - const std::lock_guard lock(m_mutex); - if (m_serverClients.empty()) return RECEIVE_NO_DATA; - for (auto s : m_serverClients) { - FD_SET(s, &readfds); - } - } - - tv.tv_usec = 1000; // 1ms poll - if (select(0, &readfds, NULL, NULL, &tv) > 0) { - const std::lock_guard lock(m_mutex); - for (auto it = m_serverClients.begin(); it != m_serverClients.end(); ) { - if (FD_ISSET(*it, &readfds)) { - int result = ReceiveSocket(*it, is, header); - if (result == -2) { // Disconnected, or lost framing (bad header) - std::cout << "Win32TcpTransport: Client disconnected." << std::endl; - closesocket(*it); - it = m_serverClients.erase(it); - continue; - } - return result; - } - ++it; - } - } - return RECEIVE_NO_DATA; - } - - /// @brief Internal helper to read from a specific socket and parse DMQ protocol. - int ReceiveSocket(SOCKET s, dmq::xstringstream& is, DmqHeader& header) { - if (s == INVALID_SOCKET) return -1; - - // Poll check to prevent blocking if no data is waiting - fd_set readfds; - FD_ZERO(&readfds); - FD_SET(s, &readfds); - TIMEVAL tv = { 0, 1000 }; - int ready = select(0, &readfds, NULL, NULL, &tv); - if (ready == 0) return RECEIVE_NO_DATA; - if (ready < 0) return -1; - - // 1. Read Header - char headerBuf[DmqHeader::HEADER_SIZE]; - if (!ReadExact(s, headerBuf, DmqHeader::HEADER_SIZE)) return -2; // Disconnected - - // Parse Header (Convert Network -> Host) - header.Decode(headerBuf); - - // A stream has no resync point: after a bad header (or a payload we - // can't hold and so can't skip), the next bytes aren't a header either. - // Report it like a disconnect (-2) so the connection is dropped. - if (!header.IsValid()) return -2; - - // 2. Read Payload - uint16_t payloadSize = header.GetLength(); - if (payloadSize > 0) - { - if (payloadSize > BUFFER_SIZE) return -2; - if (!ReadExact(s, m_recvBuffer, payloadSize)) return -2; - is.write(m_recvBuffer, payloadSize); - } - - // 3. Handle Acknowledgment - if (header.GetId() == dmq::ACK_REMOTE_ID) { - if (m_transportMonitor) m_transportMonitor->Remove(header.GetSeqNum()); - } - // ACK whenever a send path exists, whether or not this transport also - // tracks its own sends: a receive-only transport (e.g. NetworkNode's SUB) - // has no monitor but must still ACK the sender's RELIABLE messages. - else if (m_sendTransport) { - // Send ACK using a small stack buffer - DmqHeader ack(dmq::ACK_REMOTE_ID, header.GetSeqNum()); - char ackBuf[DmqHeader::HEADER_SIZE]; - ack.Encode(ackBuf); - - const std::lock_guard lock(m_mutex); // don't interleave with Send() - const char* ptr = ackBuf; - int remaining = static_cast(DmqHeader::HEADER_SIZE); - while (remaining > 0) { - int sent = send(s, ptr, remaining, 0); - if (sent == SOCKET_ERROR || sent == 0) break; - ptr += sent; - remaining -= sent; - } - } - return 0; - } - - /// @brief Read exactly 'size' bytes from the socket. - bool ReadExact(SOCKET s, char* dest, int size) - { - int total = 0; - while (total < size) { - int r = recv(s, dest + total, size - total, 0); - if (r <= 0) return false; - total += r; - } - return true; - } - - SOCKET m_listenSocket = INVALID_SOCKET; - SOCKET m_clientSocket = INVALID_SOCKET; - std::vector m_serverClients; - static const int BUFFER_SIZE = 4096; - char m_recvBuffer[BUFFER_SIZE] = { 0 }; - char m_sendBuffer[BUFFER_SIZE] = { 0 }; - DWORD m_recvTimeoutMs = 2000; - Type m_type = Type::SERVER; - - ITransport* m_sendTransport = nullptr; - ITransport* m_recvTransport = nullptr; - ITransportMonitor* m_transportMonitor = nullptr; - dmq::RecursiveMutex m_mutex; -}; - -} // namespace dmq::transport - -#endif diff --git a/DelegateMQ/port/transport/win32-udp/MulticastTransport.h b/DelegateMQ/port/transport/win32-udp/MulticastTransport.h deleted file mode 100644 index 15a81b4..0000000 --- a/DelegateMQ/port/transport/win32-udp/MulticastTransport.h +++ /dev/null @@ -1,148 +0,0 @@ -#ifndef WIN32_MULTICAST_TRANSPORT_H -#define WIN32_MULTICAST_TRANSPORT_H - -#if !defined(_WIN32) && !defined(_WIN64) -#error This code must be compiled as a Win32 or Win64 application. -#endif - -#include -#include -#pragma comment(lib, "ws2_32.lib") - -#include "delegate/DelegateOpt.h" -#include "port/transport/common/ITransport.h" -#include "port/transport/common/DmqHeader.h" -#include -#include -#include -#include - -namespace dmq::transport { - -class MulticastTransport : public ITransport -{ - XALLOCATOR -public: - enum class Type { PUB, SUB }; - - MulticastTransport() = default; - ~MulticastTransport() { Close(); } - - int Create(Type type, LPCSTR groupAddr, USHORT port, LPCSTR localInterface = "0.0.0.0") - { - dmq::LockGuard lock(m_mutex); - m_type = type; - m_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); - if (m_socket == INVALID_SOCKET) return -1; - - int reuse = 1; - setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(reuse)); - - int loop = 1; - setsockopt(m_socket, IPPROTO_IP, IP_MULTICAST_LOOP, (const char*)&loop, sizeof(loop)); - - if (type == Type::PUB) { - m_addr.sin_family = AF_INET; - m_addr.sin_port = htons(port); - inet_pton(AF_INET, groupAddr, &m_addr.sin_addr); - - // Disable loopback so we don't receive our own packets - loop = 0; - setsockopt(m_socket, IPPROTO_IP, IP_MULTICAST_LOOP, (const char*)&loop, sizeof(loop)); - - in_addr localAddr; - inet_pton(AF_INET, localInterface, &localAddr); - setsockopt(m_socket, IPPROTO_IP, IP_MULTICAST_IF, (const char*)&localAddr, sizeof(localAddr)); - - std::cout << "[Multicast] Created PUB on " << localInterface << ", Group: " << groupAddr << ":" << port << std::endl; - } - else { - m_addr.sin_family = AF_INET; - m_addr.sin_port = htons(port); - m_addr.sin_addr.s_addr = INADDR_ANY; - - if (::bind(m_socket, (sockaddr*)&m_addr, sizeof(m_addr)) == SOCKET_ERROR) { Close(); return -1; } - - ip_mreq mreq; - inet_pton(AF_INET, groupAddr, &mreq.imr_multiaddr); - inet_pton(AF_INET, localInterface, &mreq.imr_interface); - if (setsockopt(m_socket, IPPROTO_IP, IP_ADD_MEMBERSHIP, (const char*)&mreq, sizeof(mreq)) == SOCKET_ERROR) { - std::cerr << "[Multicast] Join Failed: " << WSAGetLastError() << std::endl; - Close(); return -1; - } - - DWORD timeout = 1000; - setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof(timeout)); - std::cout << "[Multicast] Created SUB on " << localInterface << ", Group: " << groupAddr << ":" << port << std::endl; - } - return 0; - } - - void Close() { - dmq::LockGuard lock(m_mutex); - if (m_socket != INVALID_SOCKET) { - closesocket(m_socket); - m_socket = INVALID_SOCKET; - } - } - - virtual int Send(dmq::xostringstream& os, const DmqHeader& header) override { - dmq::LockGuard lock(m_mutex); - if (m_type != Type::PUB) return -1; - auto payload = os.str(); - if (payload.length() > (BUFFER_SIZE - DmqHeader::HEADER_SIZE)) return -1; - DmqHeader headerCopy = header; - headerCopy.SetLength(static_cast(payload.length())); - - dmq::xostringstream ss(std::ios::in | std::ios::out | std::ios::binary); - char headerBuf[DmqHeader::HEADER_SIZE]; - headerCopy.Encode(headerBuf); - ss.write(headerBuf, DmqHeader::HEADER_SIZE); - ss.write(payload.data(), payload.size()); - - auto fullData = ss.str(); - int err = sendto(m_socket, fullData.data(), (int)fullData.length(), 0, (sockaddr*)&m_addr, sizeof(m_addr)); - - if (err != SOCKET_ERROR) { - // std::cout << "[Multicast] Sent " << fullData.length() << " bytes" << std::endl; - return 0; - } - return -1; - } - - virtual int Receive(dmq::xstringstream& is, DmqHeader& header) override { - dmq::LockGuard lock(m_mutex); - if (m_type != Type::SUB) return -1; - int addrLen = sizeof(m_addr); - int size = recvfrom(m_socket, m_buffer, sizeof(m_buffer), 0, (sockaddr*)&m_addr, &addrLen); - - if (size == SOCKET_ERROR) { - const int err = WSAGetLastError(); - // WSAEMSGSIZE (datagram larger than the buffer) stays an error - return (err == WSAETIMEDOUT || err == WSAEWOULDBLOCK) ? RECEIVE_NO_DATA : -1; - } - if (size < (int)DmqHeader::HEADER_SIZE) return -1; - - header.Decode(m_buffer); - - if (!header.IsValid()) return -1; - - // One datagram is one message: the header length must match exactly. - int payloadSize = size - static_cast(DmqHeader::HEADER_SIZE); - if (header.GetLength() != payloadSize) return -1; - is.write(m_buffer + DmqHeader::HEADER_SIZE, header.GetLength()); - return 0; - } - -private: - SOCKET m_socket = INVALID_SOCKET; - sockaddr_in m_addr{}; - Type m_type = Type::PUB; - static const int BUFFER_SIZE = 4096; - char m_buffer[BUFFER_SIZE] = { 0 }; - dmq::RecursiveMutex m_mutex; -}; - -} // namespace dmq::transport - -#endif diff --git a/DelegateMQ/port/transport/win32-udp/Win32UdpTransport.h b/DelegateMQ/port/transport/win32-udp/Win32UdpTransport.h deleted file mode 100644 index bd2b1ae..0000000 --- a/DelegateMQ/port/transport/win32-udp/Win32UdpTransport.h +++ /dev/null @@ -1,312 +0,0 @@ -#ifndef WIN32_UDP_TRANSPORT_H -#define WIN32_UDP_TRANSPORT_H - -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// @brief Win32 UDP transport implementation for DelegateMQ. -/// -/// @details -/// This class implements the ITransport interface using Windows Sockets (Winsock2) -/// for connectionless UDP communication. It supports two modes: PUB (Publisher/Sender) -/// and SUB (Subscriber/Receiver). -/// -/// Key Features: -/// 1. **Message Oriented**: Transmits discrete packets containing serialized delegate -/// arguments and framing headers. -/// 2. **Reliability Support**: Integrates with `TransportMonitor` to track outgoing -/// sequence numbers and process incoming ACKs to detect packet loss. -/// 3. **Socket Management**: Use WinsockConnect class in main() for `WSAStartup` and -/// socket creation/cleanup. -/// -/// @note This implementation uses blocking sockets with timeouts (`SO_RCVTIMEO`) to -/// prevent indefinite blocking during receive operations. - -#if !defined(_WIN32) && !defined(_WIN64) -#error This code must be compiled as a Win32 or Win64 application. -#endif - -#include -#include -#pragma comment(lib, "ws2_32.lib") // Link with Winsock library - -#include "port/transport/common/ITransport.h" -#include "port/transport/common/ITransportMonitor.h" -#include "port/transport/common/DmqHeader.h" -#include -#include -#include -#include - -namespace dmq::transport { - -/// @brief Win32 UDP transport example. -class Win32UdpTransport : public ITransport -{ - XALLOCATOR -public: - enum class Type - { - PUB, - SUB - }; - - Win32UdpTransport() : m_sendTransport(this), m_recvTransport(this) - { - } - - ~Win32UdpTransport() - { - Close(); - } - - int Create(Type type, LPCSTR addr, USHORT port) - { - const std::lock_guard recvLock(m_recvMutex); - const std::lock_guard lock(m_mutex); - Close(); // a second Create() replaces the socket instead of leaking it - m_type = type; - - // Create a UDP socket - m_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); - if (m_socket == INVALID_SOCKET) - { - std::cerr << "Socket creation failed." << std::endl; - return -1; - } - - if (type == Type::PUB) - { - // Set up the server address structure - m_addr.sin_family = AF_INET; - m_addr.sin_port = htons(port); // Convert port to network byte order - - // Convert IP address string to binary form - if (inet_pton(AF_INET, addr, &m_addr.sin_addr) != 1) - { - std::cerr << "Invalid IP address format: " << addr << std::endl; - Close(); - return -1; - } - - DWORD timeout = 2; - setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof(timeout)); - } - else if (type == Type::SUB) - { - // Set up the server address structure - m_addr.sin_family = AF_INET; - m_addr.sin_port = htons(port); // Convert port to network byte order - m_addr.sin_addr.s_addr = INADDR_ANY; // Bind to all available interfaces - - // Bind the socket to the address and port - int err = ::bind(m_socket, (sockaddr*)&m_addr, sizeof(m_addr)); - if (err == SOCKET_ERROR) - { - int wsaErr = WSAGetLastError(); - std::cerr << "Win32UdpTransport: Bind failed on port " << port << ". Error: " << wsaErr << std::endl; - Close(); - return -1; - } - - // Set a 2-second receive timeout - DWORD timeout = 2000; // 2000 milliseconds = 2 seconds - err = setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof(timeout)); - if (err == SOCKET_ERROR) - { - std::cerr << "setsockopt(SO_RCVTIMEO) failed: " << WSAGetLastError() << std::endl; - Close(); - return -1; - } - } - - return 0; - } - - /// @details Waits for a Receive() in progress on another thread to return - /// (at most its receive timeout) before closing, so the socket is never - /// closed under it. - void Close() - { - const std::lock_guard recvLock(m_recvMutex); - const std::lock_guard lock(m_mutex); - if (m_socket != INVALID_SOCKET) - { - closesocket(m_socket); - m_socket = INVALID_SOCKET; - } - } - - void SetRecvTimeout(std::chrono::milliseconds timeout) - { - const std::lock_guard lock(m_mutex); - if (m_socket != INVALID_SOCKET) - { - DWORD ms = static_cast(timeout.count()); - setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&ms, sizeof(ms)); - } - } - - virtual int Send(dmq::xostringstream& os, const DmqHeader& header) override - { - const std::lock_guard lock(m_mutex); - if (os.bad() || os.fail()) { - std::cout << "Error: xostringstream is in a bad state!" << std::endl; - return -1; - } - - if (m_type == Type::SUB && header.GetId() != dmq::ACK_REMOTE_ID) { - std::cout << "Error: Cannot send (non-ACK) on SUB socket!" << std::endl; - return -1; - } - - if (m_sendTransport != this) { - std::cout << "Error: This transport used for receive only!" << std::endl; - return -1; - } - - // Get payload data without string copy if possible - auto payload = os.str(); - if (payload.length() > (BUFFER_SIZE - DmqHeader::HEADER_SIZE)) { - std::cerr << "Error: Payload too large for static buffer." << std::endl; - return -1; - } - uint16_t payloadLen = static_cast(payload.length()); - - // Prepare header values in Network Byte Order - DmqHeader wireHeader = header; - wireHeader.SetLength(payloadLen); - wireHeader.Encode(m_sendBuffer); - - // Copy payload after header - if (payloadLen > 0) { - memcpy(m_sendBuffer + DmqHeader::HEADER_SIZE, payload.data(), payloadLen); - } - - int totalSize = DmqHeader::HEADER_SIZE + payloadLen; - - int err = sendto(m_socket, m_sendBuffer, totalSize, 0, (sockaddr*)&m_addr, sizeof(m_addr)); - - if (err == SOCKET_ERROR) { - std::cerr << "Win32UdpTransport: ERROR - sendto failed with " << WSAGetLastError() << std::endl; - } - - return (err == SOCKET_ERROR) ? -1 : 0; - } - - virtual int Receive(dmq::xstringstream& is, DmqHeader& header) override - { - // m_recvMutex, not m_mutex: a Send() on another thread (e.g. a PUB socket - // that also drains its ACKs here) isn't held up for the receive timeout. - const std::lock_guard recvLock(m_recvMutex); - if (m_recvTransport != this) { - std::cout << "Error: This transport used for send only!" << std::endl; - return -1; - } - if (m_socket == INVALID_SOCKET) - return -1; - - sockaddr_in fromAddr{}; - int addrLen = sizeof(fromAddr); - int size = recvfrom(m_socket, m_buffer, sizeof(m_buffer), 0, (sockaddr*)&fromAddr, &addrLen); - if (size == SOCKET_ERROR) - { - const int err = WSAGetLastError(); - if (err == WSAETIMEDOUT || err == WSAEWOULDBLOCK) - return RECEIVE_NO_DATA; - return -1; // includes WSAEMSGSIZE: datagram larger than the buffer - } - if (size < static_cast(DmqHeader::HEADER_SIZE)) - { - return -1; - } - - // 1. Read Header directly from m_buffer (Network Byte Order) - header.Decode(m_buffer); - - if (!header.IsValid()) { - return -1; - } - - // 2. Write payload to provided stream. One datagram is one message, so - // the header length must match exactly; anything else is malformed and - // must not be delivered or ACKed. - uint16_t payloadSize = header.GetLength(); - if (payloadSize != static_cast(size) - DmqHeader::HEADER_SIZE) - return -1; - - // A SUB replies to whoever sent the last valid message. Updated only - // now, after validation: a failed or stray read must not change it. - if (m_type == Type::SUB) - { - const std::lock_guard lock(m_mutex); - m_addr = fromAddr; - } - - if (payloadSize > 0) { - is.write(m_buffer + DmqHeader::HEADER_SIZE, payloadSize); - } - - // 3. Handle Acknowledgment - if (header.GetId() == dmq::ACK_REMOTE_ID) - { - if (m_transportMonitor) - m_transportMonitor->Remove(header.GetSeqNum()); - } - else if (m_sendTransport && m_type == Type::SUB) - { - // Send ACK using a small stack buffer to avoid any heap - DmqHeader ack(dmq::ACK_REMOTE_ID, header.GetSeqNum()); - char ackBuf[DmqHeader::HEADER_SIZE]; - ack.Encode(ackBuf); - - sockaddr_in targetAddr = (m_type == Type::SUB) ? fromAddr : m_addr; - sendto(m_socket, ackBuf, static_cast(DmqHeader::HEADER_SIZE), 0, (sockaddr*)&targetAddr, sizeof(targetAddr)); - } - - return 0; - } - - void SetTransportMonitor(ITransportMonitor* transportMonitor) - { - m_transportMonitor = transportMonitor; - } - - void SetSendTransport(ITransport* sendTransport) - { - m_sendTransport = sendTransport; - } - - void SetRecvTransport(ITransport* recvTransport) - { - m_recvTransport = recvTransport; - } - - -private: - SOCKET m_socket = INVALID_SOCKET; - sockaddr_in m_addr{}; - - Type m_type = Type::PUB; - - ITransport* m_sendTransport = nullptr; - ITransport* m_recvTransport = nullptr; - ITransportMonitor* m_transportMonitor = nullptr; - - /// @note UDP datagrams larger than the network MTU (typically 1500 bytes) will be - /// fragmented by the IP layer. If any fragment is lost, the entire message is - /// discarded. For maximum reliability, keep serialized messages under 1400 bytes. - /// Messages exceeding BUFFER_SIZE will be truncated and discarded by the OS. - static const int BUFFER_SIZE = 4096; - char m_buffer[BUFFER_SIZE] = { 0 }; - char m_sendBuffer[BUFFER_SIZE] = { 0 }; - dmq::RecursiveMutex m_mutex; ///< Socket open/close and Send() state (m_addr) - dmq::RecursiveMutex m_recvMutex; ///< Held by Receive(); taken before m_mutex -}; - -using UdpTransport = Win32UdpTransport; - -} // namespace dmq::transport - - -#endif \ No newline at end of file diff --git a/DelegateMQ/port/transport/zephyr-udp/ZephyrUdpTransport.h b/DelegateMQ/port/transport/zephyr-udp/ZephyrUdpTransport.h deleted file mode 100644 index b56e4a0..0000000 --- a/DelegateMQ/port/transport/zephyr-udp/ZephyrUdpTransport.h +++ /dev/null @@ -1,338 +0,0 @@ -#ifndef ZEPHYR_UDP_TRANSPORT_H -#define ZEPHYR_UDP_TRANSPORT_H - -/// @file ZephyrUdpTransport.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief Zephyr RTOS UDP transport implementation for DelegateMQ. -/// -/// @details -/// This class implements the ITransport interface using the Zephyr Networking Subsystem -/// (BSD Socket API). It is designed for embedded targets running Zephyr RTOS. -/// -/// **Prerequisites:** -/// * Enable BSD Sockets: `CONFIG_NET_SOCKETS=y` -/// * Enable IPv4: `CONFIG_NET_IPV4=y` -/// * A network interface: on `native_sim` the loopback interface -/// (`CONFIG_NET_LOOPBACK=y`, needs `CONFIG_NET_DRIVERS=y`) is enough for -/// same-process testing with no host-side setup -- see -/// `example/sample-projects/zephyr-udp-serializer/prj.conf`. A real -/// target instead needs its actual link-layer driver (Ethernet, Wi-Fi, etc.). -/// -/// This file calls the `zsock_*`-prefixed socket functions (`zsock_socket()`, -/// `zsock_bind()`, `zsock_sendto()`, etc.) rather than the unprefixed BSD -/// names. Getting the unprefixed names requires `CONFIG_POSIX_API=y`, which -/// replaces large parts of the standard header set (``, -/// pthread types, ...) with Zephyr's own POSIX compatibility layer -- -/// something that collides with the *host's* C++ standard library headers -/// when building for `native_sim` (which links against the host's real -/// libstdc++), and is unnecessary weight on a real target that has no such -/// conflict. `CONFIG_NET_SOCKETS_POSIX_NAMES`, an older, narrower way to get -/// just the unprefixed socket names without the rest of `CONFIG_POSIX_API`, -/// was deprecated in Zephyr 3.7 and removed -- `zsock_*` is the current, -/// portable choice regardless of target. -/// -/// **Key Features:** -/// 1. **Direct Execution**: Executes network operations directly on the calling thread, -/// avoiding context switch overhead and preventing deadlocks. -/// 2. **Zero-Copy Friendly**: Uses the standard BSD API which Zephyr optimizes internally. -/// 3. **Reliability**: Fully integrated with `TransportMonitor` for ACKs/Retries. -/// 4. **Endianness**: Uses `htons`/`ntohs` for standard network byte order compatibility. - -#include "delegate/DelegateOpt.h" -#include "port/transport/common/ITransport.h" -#include "port/transport/common/DmqHeader.h" -#include "port/transport/common/ITransportMonitor.h" - -#include -#include - -#include -#include -#include -#include - -namespace dmq::transport { - -class ZephyrUdpTransport : public ITransport -{ -public: - enum class Type - { - PUB, - SUB - }; - - ZephyrUdpTransport() : m_sendTransport(this), m_recvTransport(this) - { - } - - ~ZephyrUdpTransport() - { - Close(); - } - - int Create(Type type, const char* addr, uint16_t port) - { - const dmq::LockGuard recvLock(m_recvMutex); - const dmq::LockGuard lock(m_mutex); - Close(); // a second Create() replaces the socket instead of leaking it - m_type = type; - - // Create UDP socket. zsock_* (not the bare BSD names) so this - // compiles without CONFIG_POSIX_API -- see the class doc comment. - m_socket = zsock_socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); - if (m_socket < 0) - { - // printk("Socket creation failed: %d\n", errno); - return -1; - } - - memset(&m_addr, 0, sizeof(m_addr)); - m_addr.sin_family = AF_INET; - m_addr.sin_port = htons(port); - - if (type == Type::PUB) - { - if (zsock_inet_pton(AF_INET, addr, &m_addr.sin_addr) != 1) - { - // printk("Invalid IP address format.\n"); - Close(); - return -1; - } - - // Short timeout so polling this socket for ACKs doesn't hang. - struct timeval timeout = ToTimeval(dmq::UDP_PUB_RECV_TIMEOUT); - - if (zsock_setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) < 0) - { - // printk("setsockopt(SO_RCVTIMEO) failed\n"); - Close(); - return -1; - } - } - else if (type == Type::SUB) - { - m_addr.sin_addr.s_addr = INADDR_ANY; - - if (zsock_bind(m_socket, (struct sockaddr*)&m_addr, sizeof(m_addr)) < 0) - { - // printk("Bind failed: %d\n", errno); - Close(); - return -1; - } - - // Receive timeout, so the receive thread can check for exit - struct timeval timeout = ToTimeval(dmq::UDP_SUB_RECV_TIMEOUT); - - if (zsock_setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) < 0) - { - // printk("setsockopt(SO_RCVTIMEO) failed\n"); - Close(); - return -1; - } - } - - return 0; - } - - /// @details Waits for a Receive() in progress on another thread to return - /// (at most its receive timeout) before closing, so the socket is never - /// closed under it. - void Close() - { - const dmq::LockGuard recvLock(m_recvMutex); - const dmq::LockGuard lock(m_mutex); - if (m_socket >= 0) - { - // Receive() has returned (m_recvMutex is held), so nothing is blocked on it - zsock_shutdown(m_socket, ZSOCK_SHUT_RDWR); - zsock_close(m_socket); - m_socket = -1; - } - } - - void SetRecvTimeout(std::chrono::milliseconds timeout) - { - const dmq::LockGuard lock(m_mutex); - if (m_socket >= 0) - { - struct timeval tv; - tv.tv_sec = timeout.count() / 1000; - tv.tv_usec = (timeout.count() % 1000) * 1000; - zsock_setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); - } - } - - virtual int Send(xostringstream& os, const DmqHeader& header) override - { - const dmq::LockGuard lock(m_mutex); - if (os.bad() || os.fail() || m_socket < 0) { - return -1; - } - - // Allow ACKs on SUB sockets. Block only regular data. - if (m_type == Type::SUB && header.GetId() != dmq::ACK_REMOTE_ID) { - return -1; - } - - if (m_sendTransport != this) { - return -1; - } - - // Get payload and set length on the copy - auto payload = os.str(); - if (payload.length() > (BUFFER_SIZE - DmqHeader::HEADER_SIZE)) { - return -1; - } - uint16_t payloadLen = static_cast(payload.length()); - - // Convert to Network Byte Order (Big Endian) - DmqHeader wireHeader = header; - wireHeader.SetLength(payloadLen); - wireHeader.Encode(m_sendBuffer); - - if (payloadLen > 0) { - memcpy(m_sendBuffer + DmqHeader::HEADER_SIZE, payload.data(), payloadLen); - } - - size_t totalSize = DmqHeader::HEADER_SIZE + payloadLen; - - ssize_t sent = zsock_sendto(m_socket, m_sendBuffer, totalSize, 0, - (struct sockaddr*)&m_addr, sizeof(m_addr)); - if (sent != (ssize_t)totalSize) return -1; - - return 0; - } - - virtual int Receive(xstringstream& is, DmqHeader& header) override - { - // m_recvMutex, not m_mutex: a Send() on another thread (e.g. a PUB socket - // that also drains its ACKs here) isn't held up for the receive timeout. - const dmq::LockGuard recvLock(m_recvMutex); - if (m_recvTransport != this || m_socket < 0) { - return -1; - } - - sockaddr_in fromAddr; - socklen_t addrLen = sizeof(fromAddr); - - ssize_t size = zsock_recvfrom(m_socket, m_buffer, sizeof(m_buffer), 0, - (struct sockaddr*)&fromAddr, &addrLen); - - if (size < 0) - { - // Zephyr uses standard errno values - if (errno == EWOULDBLOCK || errno == EAGAIN) - return RECEIVE_NO_DATA; - - return -1; - } - - if (static_cast(size) < DmqHeader::HEADER_SIZE) { - return -1; - } - - // 1. Read Header (Network Byte Order) - header.Decode(m_buffer); - - if (!header.IsValid()) - { - return -1; // Invalid marker - } - - // 2. Extract Payload. One datagram is one message, so the header length - // must match exactly; anything else (including a datagram cut short by - // the buffer) is malformed and must not be delivered or ACKed. - uint16_t payloadSize = header.GetLength(); - if (payloadSize != static_cast(size) - DmqHeader::HEADER_SIZE) - return -1; - - // Update m_addr to the sender's address so we can ACK back. Only after - // validation, and under m_mutex since Send() uses it. - if (m_type == Type::SUB) { - const dmq::LockGuard lock(m_mutex); - m_addr = fromAddr; - } - - if (payloadSize > 0) { - is.clear(); - is.str(""); - is.write(m_buffer + DmqHeader::HEADER_SIZE, payloadSize); - } - - if (header.GetId() == dmq::ACK_REMOTE_ID) - { - if (m_transportMonitor) - m_transportMonitor->Remove(header.GetSeqNum()); - } - // ACK whenever a send path exists, whether or not this transport also - // tracks its own sends: a receive-only transport (e.g. NetworkNode's SUB) - // has no monitor but must still ACK the sender's RELIABLE messages. - else if (m_sendTransport) - { - // Send ACK back using Send logic (recursive mutex handles it) - xostringstream ss_ack; - DmqHeader ack; - ack.SetId(dmq::ACK_REMOTE_ID); - ack.SetSeqNum(header.GetSeqNum()); - ack.SetLength(0); - m_sendTransport->Send(ss_ack, ack); - } - - return 0; - } - - void SetTransportMonitor(ITransportMonitor* transportMonitor) - { - m_transportMonitor = transportMonitor; - } - - void SetSendTransport(ITransport* sendTransport) - { - m_sendTransport = sendTransport; - } - - void SetRecvTransport(ITransport* recvTransport) - { - m_recvTransport = recvTransport; - } - -private: - int m_socket = -1; - sockaddr_in m_addr{}; - Type m_type = Type::PUB; - - ITransport* m_sendTransport = nullptr; - ITransport* m_recvTransport = nullptr; - ITransportMonitor* m_transportMonitor = nullptr; - - static struct timeval ToTimeval(std::chrono::milliseconds ms) - { - struct timeval tv; - tv.tv_sec = static_cast(ms.count() / 1000); - tv.tv_usec = static_cast((ms.count() % 1000) * 1000); - return tv; - } - - // Datagram buffer (header + payload): DMQ_UDP_BUFFER_SIZE, default the - // 1500-byte Ethernet MTU. - static constexpr size_t BUFFER_SIZE = dmq::UDP_BUFFER_SIZE; - char m_buffer[BUFFER_SIZE] = { 0 }; - char m_sendBuffer[BUFFER_SIZE] = { 0 }; - dmq::RecursiveMutex m_mutex; ///< Socket open/close and Send() state (m_addr) - dmq::RecursiveMutex m_recvMutex; ///< Held by Receive(); taken before m_mutex -}; - -/// @brief Backward-compatible name: application code (e.g. the sender.h/ -/// receiver.h pattern shared by every *-udp-serializer sample) references -/// dmq::transport::UdpTransport generically and stays portable across -/// whichever DMQ_TRANSPORT_* was selected at compile time, the same way -/// dmq::os::Thread works across DMQ_THREAD_* -- see LinuxUdpTransport.h/ -/// Win32UdpTransport.h for the other two ports that already do this. -using UdpTransport = ZephyrUdpTransport; - -} - -#endif // ZEPHYR_UDP_TRANSPORT_H \ No newline at end of file diff --git a/DelegateMQ/port/transport/zeromq/ZeroMqTransport.h b/DelegateMQ/port/transport/zeromq/ZeroMqTransport.h deleted file mode 100644 index 1f6079c..0000000 --- a/DelegateMQ/port/transport/zeromq/ZeroMqTransport.h +++ /dev/null @@ -1,344 +0,0 @@ -#ifndef ZEROMQ_TRANSPORT_H -#define ZEROMQ_TRANSPORT_H - -/// @file ZeroMqTransport.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// @brief ZeroMQ transport implementation for DelegateMQ. -/// -/// @details -/// This class implements the ITransport interface using the ZeroMQ high-performance -/// asynchronous messaging library. It supports multiple patterns including PAIR (1-to-1) -/// and PUB/SUB (1-to-many). -/// -/// Key Features: -/// 1. **Thread Safety**: Uses a `dmq::RecursiveMutex` to protect the ZeroMQ socket, -/// allowing safe concurrent access from the Send and Receive threads (ZeroMQ sockets -/// are not inherently thread-safe). -/// 2. **Flexible Patterns**: Supports both bidirectional (PAIR) and unidirectional (PUB/SUB) -/// communication topologies. -/// 3. **Non-Blocking**: Configures `ZMQ_RCVTIMEO` and `ZMQ_DONTWAIT` to ensure the -/// transport remains responsive and never blocks the application indefinitely. -/// 4. **Reliability**: Integrates with `TransportMonitor` to provide sequence tracking -/// and ACKs even over PUB/SUB (when a return channel is available). -/// -/// @note Requires the `libzmq` library. - -// Add Windows Sockets headers for htons/ntohs -#if defined(_WIN32) || defined(_WIN64) - #include - #pragma comment(lib, "ws2_32.lib") -#else - #include -#endif - -#include "delegate/DelegateOpt.h" -#include "port/transport/common/ITransport.h" -#include "port/transport/common/DmqHeader.h" -#include "port/transport/common/ITransportMonitor.h" -#include -#include -#include -#include -#include -#include -#include // For std::cout/cerr - -namespace dmq::transport { - -/// @brief ZeroMQ transport class. -/// @details Logic now executes directly on the caller's thread, protected by a mutex -/// to prevent concurrent access to the underlying ZeroMQ socket. -class ZeroMqTransport : public ITransport -{ -public: - enum class Type - { - PAIR_CLIENT, - PAIR_SERVER, - PUB, - SUB - }; - - ZeroMqTransport() : m_sendTransport(this), m_recvTransport(this) - { - } - - ~ZeroMqTransport() - { - Destroy(); - } - - int Create(Type type, const char* addr) - { - std::lock_guard lock(m_mutex); - - if (m_zmqContext == nullptr) { - m_zmqContext = zmq_ctx_new(); - } - - m_type = type; - - if (m_type == Type::PAIR_CLIENT) - { - // Create a PAIR socket and connect the client to the server address - m_zmq = zmq_socket(m_zmqContext, ZMQ_PAIR); - int rc = zmq_connect(m_zmq, addr); - if (rc != 0) { - // perror is less useful on Windows for ZMQ specific errors, but ok for console - perror("zmq_connect failed"); - zmq_close(m_zmq); - return 1; - } - - // Set the receive timeout to 100 milliseconds - int timeout = 100; // 100mS - zmq_setsockopt(m_zmq, ZMQ_RCVTIMEO, &timeout, sizeof(timeout)); - } - else if (m_type == Type::PAIR_SERVER) - { - // Create a PAIR socket and bind the server to an address - m_zmq = zmq_socket(m_zmqContext, ZMQ_PAIR); - int rc = zmq_bind(m_zmq, addr); - if (rc != 0) { - perror("zmq_bind failed"); - return 1; - } - - // Set the receive timeout to 100 milliseconds - int timeout = 100; // 100mS - zmq_setsockopt(m_zmq, ZMQ_RCVTIMEO, &timeout, sizeof(timeout)); - } - else if (m_type == Type::PUB) - { - // Create a PUB socket - m_zmq = zmq_socket(m_zmqContext, ZMQ_PUB); - int rc = zmq_bind(m_zmq, addr); - if (rc != 0) { - perror("zmq_bind failed"); - return 1; - } - } - else if (m_type == Type::SUB) - { - // Create a SUB socket - m_zmq = zmq_socket(m_zmqContext, ZMQ_SUB); - int rc = zmq_connect(m_zmq, addr); - if (rc != 0) { - perror("zmq_connect failed"); - zmq_close(m_zmq); - return 1; - } - - // Subscribe to all messages - zmq_setsockopt(m_zmq, ZMQ_SUBSCRIBE, "", 0); - - // Set the receive timeout to 100 milliseconds - int timeout = 100; // 100mS - zmq_setsockopt(m_zmq, ZMQ_RCVTIMEO, &timeout, sizeof(timeout)); - } - else - { - // Handle other types, if needed - perror("Invalid socket type"); - return 1; - } - return 0; - } - - void Close() - { - std::lock_guard lock(m_mutex); - - // Close the subscriber socket and context - if (m_zmq) { - // Linger 0 ensures close doesn't block waiting for unsent messages - int linger = 0; - zmq_setsockopt(m_zmq, ZMQ_LINGER, &linger, sizeof(linger)); - zmq_close(m_zmq); - m_zmq = nullptr; - } - } - - void SetRecvTimeout(std::chrono::milliseconds timeout) - { - std::lock_guard lock(m_mutex); - if (m_zmq) - { - int ms = static_cast(timeout.count()); - zmq_setsockopt(m_zmq, ZMQ_RCVTIMEO, &ms, sizeof(ms)); - } - } - - void Destroy() - { - Close(); - - // Context termination is thread-safe in ZMQ - if (m_zmqContext) { - zmq_ctx_term(m_zmqContext); - m_zmqContext = nullptr; - } - } - - virtual int Send(dmq::xostringstream& os, const DmqHeader& header) override - { - std::lock_guard lock(m_mutex); - - if (os.bad() || os.fail() || m_zmq == nullptr) { - return -1; - } - - if (m_type == Type::SUB) { - return -1; - } - - if (m_sendTransport != this) { - return -1; - } - - // Get payload data without string copy if possible - auto payload = os.str(); - if (payload.length() > (BUFFER_SIZE - DmqHeader::HEADER_SIZE)) { - return -1; - } - uint16_t payloadLen = static_cast(payload.length()); - - // Prepare header values in Network Byte Order - DmqHeader wireHeader = header; - wireHeader.SetLength(payloadLen); - wireHeader.Encode(m_sendBuffer); - - if (payloadLen > 0) { - memcpy(m_sendBuffer + DmqHeader::HEADER_SIZE, payload.data(), payloadLen); - } - - size_t totalSize = DmqHeader::HEADER_SIZE + payloadLen; - - // Send data using ZeroMQ - int err = zmq_send(m_zmq, m_sendBuffer, totalSize, ZMQ_DONTWAIT); - if (err == -1) - { - // EAGAIN is common if queue is full - return -1; - } - - return 0; - } - - virtual int Receive(dmq::xstringstream& is, DmqHeader& header) override - { - std::lock_guard lock(m_mutex); - - if (m_zmq == nullptr) { - return -1; - } - - if (m_type == Type::PUB) { - return -1; - } - - if (m_recvTransport != this) { - return -1; - } - - int size = zmq_recv(m_zmq, m_buffer, BUFFER_SIZE, 0); - if (size == -1) { - return (zmq_errno() == EAGAIN) ? RECEIVE_NO_DATA : -1; // EAGAIN: ZMQ_RCVTIMEO expired - } - - // zmq_recv() truncates a message longer than the buffer but returns its - // full length. Drop it: only BUFFER_SIZE bytes were stored. - if (size > BUFFER_SIZE) { - return -1; - } - - if (size < DmqHeader::HEADER_SIZE) { - return -1; - } - - // 1. Read Header (Network Byte Order) - header.Decode(m_buffer); - - if (!header.IsValid()) { - return -1; - } - - // 2. Write payload - // One message per ZeroMQ message: the header length must match exactly. Anything - // else is malformed and must not be delivered (cut short) or ACKed. - uint16_t payloadSize = header.GetLength(); - if (payloadSize != static_cast(size) - DmqHeader::HEADER_SIZE) - return -1; - - if (payloadSize > 0) { - is.clear(); - is.str(""); - is.write(m_buffer + DmqHeader::HEADER_SIZE, payloadSize); - } - - if (header.GetId() == dmq::ACK_REMOTE_ID) - { - // Receiver ack'ed message. Remove sequence number from monitor. - if (m_transportMonitor) - m_transportMonitor->Remove(header.GetSeqNum()); - } - else - { - // ACK whenever a send path exists, whether or not this transport also - // tracks its own sends: a receive-only transport (e.g. NetworkNode's SUB) - // has no monitor but must still ACK the sender's RELIABLE messages. - if (m_sendTransport) - { - // Send header with received seqNum as the ack message - dmq::xostringstream ss_ack; - DmqHeader ack; - ack.SetId(dmq::ACK_REMOTE_ID); - ack.SetSeqNum(header.GetSeqNum()); - - // Note: Recursive mutex allows Send() here - m_sendTransport->Send(ss_ack, ack); - } - } - - return 0; // Success - } - - // Set a transport monitor for checking message ack - void SetTransportMonitor(ITransportMonitor* transportMonitor) - { - m_transportMonitor = transportMonitor; - } - - // Set an alternative send transport - void SetSendTransport(ITransport* sendTransport) - { - m_sendTransport = sendTransport; - } - - // Set an alternative receive transport - void SetRecvTransport(ITransport* recvTransport) - { - m_recvTransport = recvTransport; - } - -private: - void* m_zmqContext = nullptr; - void* m_zmq = nullptr; - Type m_type = Type::PAIR_CLIENT; - - dmq::RecursiveMutex m_mutex; - - ITransport* m_sendTransport = nullptr; - ITransport* m_recvTransport = nullptr; - ITransportMonitor* m_transportMonitor = nullptr; - - static const int BUFFER_SIZE = 4096; - char m_buffer[BUFFER_SIZE] = {}; - char m_sendBuffer[BUFFER_SIZE] = {}; -}; - -} // namespace dmq::transport - -#endif diff --git a/HTTP/CMakeLists.txt b/HTTP/CMakeLists.txt index 2640462..b7998e4 100644 --- a/HTTP/CMakeLists.txt +++ b/HTTP/CMakeLists.txt @@ -10,6 +10,9 @@ target_include_directories(HttpLib PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}") # libcurl is a public dependency — consumers of HttpLib also need the headers/libs target_link_libraries(HttpLib PUBLIC CURL::libcurl) +# async_http.h includes DelegateMQ.h +target_link_libraries(HttpLib PUBLIC DelegateMQ::DelegateMQ) + # Add /bigobj flag for MSVC if (MSVC) target_compile_options(HttpLib PRIVATE /bigobj) diff --git a/README.md b/README.md index c759fbe..95b21ee 100644 --- a/README.md +++ b/README.md @@ -194,16 +194,22 @@ For high-concurrency scenarios requiring many simultaneous requests to the same # Getting Started -[CMake](https://cmake.org/) is used to create the project build files on any Windows or Linux machine. [libcurl](https://curl.se/libcurl/) must be available on the system. +[CMake](https://cmake.org/) 3.16 or newer is used to create the project build files on any Windows or Linux machine. [libcurl](https://curl.se/libcurl/) must be available on the system. 1. Clone the repository. 2. Install libcurl (via [vcpkg](https://vcpkg.io/) or a system package manager). 3. From the repository root, run one of the following CMake commands: ``` - cmake -B Build . - cmake -B Build . -DCMAKE_TOOLCHAIN_FILE=/scripts/buildsystems/vcpkg.cmake + cmake -B build . + cmake -B build . -DCMAKE_TOOLCHAIN_FILE=/scripts/buildsystems/vcpkg.cmake ``` -4. Build and run the project within the `Build` directory. +4. Build and run the project within the `build` directory. + +[DelegateMQ](https://github.com/DelegateMQ/DelegateMQ) is fetched from GitHub by CMake's `FetchContent` when CMake configures, at the release tag set by `DMQ_GIT_TAG` in `CMakeLists.txt` (currently `v2.4.1`), and the code links the `DelegateMQ::DelegateMQ` target. Options: + +* Another release: `cmake -B build . -DDMQ_GIT_TAG=` +* A local DelegateMQ checkout instead of GitHub: `-DFETCHCONTENT_SOURCE_DIR_DELEGATEMQ=` +* No network after the first configure: `-DFETCHCONTENT_FULLY_DISCONNECTED=ON` # Delegate Quick Start