Merged
feat(mcp): mcp support macos #350
zhuyutong888Add on 29 days ago
feat(mcp): mcp support macos #350
Merged
Total: 20 files changed+778-89
| @@ -17,6 +17,30 @@ option(MCP_WITH_HTTP "Build HTTP client transport components" ON) | |||
| 17 | 17 | ||
| 18 | add_compile_definitions(MCP_WITH_HTTP=$<BOOL:${MCP_WITH_HTTP}>) | 18 | add_compile_definitions(MCP_WITH_HTTP=$<BOOL:${MCP_WITH_HTTP}>) |
| 19 | 19 | ||
| 20 | +# On macOS, Homebrew installs some dependencies (OpenSSL, curl, ...) as keg-only, | ||
| 21 | +# so they are not on the default search path. Prepend their prefixes so that | ||
| 22 | +# find_package/find_library can locate them without manual OPENSSL_ROOT_DIR. | ||
| 23 | +if(APPLE) | ||
| 24 | + find_program(MCP_BREW_EXECUTABLE brew) | ||
| 25 | + if(MCP_BREW_EXECUTABLE) | ||
| 26 | + set(_mcp_brew_prefixes "") | ||
| 27 | + foreach(_mcp_brew_pkg openssl@3 openssl curl libevent nlohmann-json) | ||
| 28 | + execute_process( | ||
| 29 | + COMMAND ${MCP_BREW_EXECUTABLE} --prefix ${_mcp_brew_pkg} | ||
| 30 | + OUTPUT_VARIABLE _mcp_brew_prefix | ||
| 31 | + OUTPUT_STRIP_TRAILING_WHITESPACE | ||
| 32 | + ERROR_QUIET) | ||
| 33 | + if(_mcp_brew_prefix AND EXISTS "${_mcp_brew_prefix}") | ||
| 34 | + list(APPEND _mcp_brew_prefixes "${_mcp_brew_prefix}") | ||
| 35 | + endif() | ||
| 36 | + endforeach() | ||
| 37 | + if(_mcp_brew_prefixes) | ||
| 38 | + list(REMOVE_DUPLICATES _mcp_brew_prefixes) | ||
| 39 | + list(PREPEND CMAKE_PREFIX_PATH ${_mcp_brew_prefixes}) | ||
| 40 | + endif() | ||
| 41 | + endif() | ||
| 42 | +endif() | ||
| 43 | + | ||
| 20 | include(third_party/third_party.cmake) | 44 | include(third_party/third_party.cmake) |
| 21 | 45 | ||
| 22 | find_package(OpenSSL REQUIRED) | 46 | find_package(OpenSSL REQUIRED) |
| @@ -48,12 +72,28 @@ set(CMAKE_CXX_FLAGS_MINSIZEREL "-Os -DNDEBUG") | |||
| 48 | set(CMAKE_FLAGS_ASAN | 72 | set(CMAKE_FLAGS_ASAN |
| 49 | -fsanitize=address | 73 | -fsanitize=address |
| 50 | -fsanitize-recover=address | 74 | -fsanitize-recover=address |
| 51 | - -fsanitize=leak | ||
| 52 | -fno-omit-frame-pointer | 75 | -fno-omit-frame-pointer |
| 53 | ) | 76 | ) |
| 54 | 77 | ||
| 78 | +# LeakSanitizer is not supported by AppleClang, so enable it only elsewhere. | ||
| 79 | +if(NOT APPLE) | ||
| 80 | + list(APPEND CMAKE_FLAGS_ASAN -fsanitize=leak) | ||
| 81 | +endif() | ||
| 82 | + | ||
| 55 | # Common compiler flags | 83 | # Common compiler flags |
| 56 | -add_compile_options(-Wall -Werror -Wno-error=unused-variable -Wfloat-equal -Wtrampolines -fno-strict-aliasing -fstack-protector-strong) | 84 | +# Warnings are errors on every platform. Do not add directory-wide -Wno-* |
| 85 | +# switches here: every source (and its subdirectories) is built under this | ||
| 86 | +# directory, so an exemption would also hide the same warning in new code. If a | ||
| 87 | +# pre-existing site needs one, scope it to that source file, e.g. | ||
| 88 | +# set_source_files_properties(<file> PROPERTIES COMPILE_OPTIONS | ||
| 89 | +# "$<$<CXX_COMPILER_ID:AppleClang,Clang>:-Wno-...>") | ||
| 90 | +# or to the specific target that compiles it. | ||
| 91 | +if(APPLE) | ||
| 92 | + add_compile_options(-Wall -Werror -Wno-error=unused-variable -Wfloat-equal | ||
| 93 | + -fno-strict-aliasing -fstack-protector-strong) | ||
| 94 | +else() | ||
| 95 | + add_compile_options(-Wall -Werror -Wno-error=unused-variable -Wfloat-equal -Wtrampolines -fno-strict-aliasing -fstack-protector-strong) | ||
| 96 | +endif() | ||
| 57 | 97 | ||
| 58 | if (ASAN STREQUAL "enable") | 98 | if (ASAN STREQUAL "enable") |
| 59 | if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") | 99 | if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") |
| @@ -65,10 +105,14 @@ if (ASAN STREQUAL "enable") | |||
| 65 | endif() | 105 | endif() |
| 66 | 106 | ||
| 67 | # Linker flags for security hardening | 107 | # Linker flags for security hardening |
| 68 | -set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-z,noexecstack,-z,relro,-z,now -rdynamic -pie") | 108 | +if(APPLE) |
| 69 | -set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,-z,noexecstack,-z,relro,-z,now -rdynamic") | 109 | + set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-pie") |
| 110 | +else() | ||
| 111 | + set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-z,noexecstack,-z,relro,-z,now -rdynamic -pie") | ||
| 112 | + set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,-z,noexecstack,-z,relro,-z,now -rdynamic") | ||
| 113 | +endif() | ||
| 70 | 114 | ||
| 71 | -if(CMAKE_BUILD_TYPE STREQUAL "Release") | 115 | +if(CMAKE_BUILD_TYPE STREQUAL "Release" AND NOT APPLE) |
| 72 | set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -s") | 116 | set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -s") |
| 73 | set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -s") | 117 | set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -s") |
| 74 | endif() | 118 | endif() |
| @@ -85,6 +85,11 @@ EulerOS / openEuler 上 `nlohmann_json` 包名可能为 `nlohmann-json-devel` | |||
| 85 | brew install cmake openssl curl libevent nlohmann-json | 85 | brew install cmake openssl curl libevent nlohmann-json |
| 86 | ``` | 86 | ``` |
| 87 | 87 | ||
| 88 | +> **conda/Anaconda 环境注意**:若当前 shell 激活了 conda(`CONDA_PREFIX` 非空),其自带的 | ||
| 89 | +> OpenSSL/curl/libevent/nlohmann_json 等可能被 CMake 抢先选中,导致链接错误或 undefined | ||
| 90 | +> symbols。构建前请 `conda deactivate`(含 base),并删除 `build/` 后重新配置(CMake 会把 | ||
| 91 | +> 已找到的路径缓存进 `build/CMakeCache.txt`,不删缓存不生效)。 | ||
| 92 | + | ||
| 88 | ### Arch Linux(手动) | 93 | ### Arch Linux(手动) |
| 89 | 94 | ||
| 90 | ```bash | 95 | ```bash |
| @@ -6,10 +6,10 @@ endif() | |||
| 6 | 6 | ||
| 7 | get_filename_component(MCP_SDK_ROOT "${MCP_SDK_ROOT}" ABSOLUTE) | 7 | get_filename_component(MCP_SDK_ROOT "${MCP_SDK_ROOT}" ABSOLUTE) |
| 8 | 8 | ||
| 9 | -set(MCP_EXAMPLE_LIB "${MCP_SDK_ROOT}/output/lib/libmcp.so") | 9 | +set(MCP_EXAMPLE_LIB "${MCP_SDK_ROOT}/output/lib/libmcp${CMAKE_SHARED_LIBRARY_SUFFIX}") |
| 10 | if(NOT EXISTS "${MCP_EXAMPLE_LIB}") | 10 | if(NOT EXISTS "${MCP_EXAMPLE_LIB}") |
| 11 | message(FATAL_ERROR | 11 | message(FATAL_ERROR |
| 12 | - "libmcp.so not found at ${MCP_EXAMPLE_LIB}. Build the SDK first: ./scripts/build.sh" | 12 | + "libmcp${CMAKE_SHARED_LIBRARY_SUFFIX} not found at ${MCP_EXAMPLE_LIB}. Build the SDK first: ./scripts/build.sh" |
| 13 | ) | 13 | ) |
| 14 | endif() | 14 | endif() |
| 15 | 15 | ||
| @@ -56,4 +56,8 @@ endif() | |||
| 56 | function(mcp_link_example_dependencies target) | 56 | function(mcp_link_example_dependencies target) |
| 57 | target_include_directories(${target} PRIVATE "${MCP_SDK_ROOT}/include/mcp") | 57 | target_include_directories(${target} PRIVATE "${MCP_SDK_ROOT}/include/mcp") |
| 58 | target_link_libraries(${target} PRIVATE "${MCP_EXAMPLE_LIB}" ${MCP_EXAMPLE_NLOHMANN_TARGET}) | 58 | target_link_libraries(${target} PRIVATE "${MCP_EXAMPLE_LIB}" ${MCP_EXAMPLE_NLOHMANN_TARGET}) |
| 59 | + # Let the example find the shared library at runtime without DYLD/LD env setup. | ||
| 60 | + set_target_properties(${target} PROPERTIES | ||
| 61 | + BUILD_RPATH "${MCP_SDK_ROOT}/output/lib" | ||
| 62 | + ) | ||
| 59 | endfunction() | 63 | endfunction() |
| @@ -35,7 +35,12 @@ SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd) | |||
| 35 | 35 | ||
| 36 | cd "$SCRIPT_DIR" | 36 | cd "$SCRIPT_DIR" |
| 37 | 37 | ||
| 38 | -LIB_PATH="${SCRIPT_DIR}/../../output/lib/libmcp.so" | 38 | +if [ "$(uname -s)" = "Darwin" ]; then |
| 39 | + LIB_EXT="dylib" | ||
| 40 | +else | ||
| 41 | + LIB_EXT="so" | ||
| 42 | +fi | ||
| 43 | +LIB_PATH="${SCRIPT_DIR}/../../output/lib/libmcp.${LIB_EXT}" | ||
| 39 | if [ ! -f "$LIB_PATH" ]; then | 44 | if [ ! -f "$LIB_PATH" ]; then |
| 40 | echo "Error: MCP library not found at $LIB_PATH" | 45 | echo "Error: MCP library not found at $LIB_PATH" |
| 41 | echo "Please build the main project first using: cd ../../ && bash scripts/build.sh" | 46 | echo "Please build the main project first using: cd ../../ && bash scripts/build.sh" |
| @@ -8,11 +8,12 @@ | |||
| 8 | #include <stddef.h> | 8 | #include <stddef.h> |
| 9 | #include <stdint.h> | 9 | #include <stdint.h> |
| 10 | #include <string.h> | 10 | #include <string.h> |
| 11 | -#include <sys/syscall.h> | ||
| 12 | #include <sys/types.h> | 11 | #include <sys/types.h> |
| 13 | #include <time.h> | 12 | #include <time.h> |
| 14 | #include <unistd.h> | 13 | #include <unistd.h> |
| 15 | 14 | ||
| 15 | +#include "platform_compat.h" | ||
| 16 | + | ||
| 16 | #include <iomanip> | 17 | #include <iomanip> |
| 17 | #include <sstream> | 18 | #include <sstream> |
| 18 | #include <string> | 19 | #include <string> |
| @@ -62,6 +63,12 @@ static inline void GetCurrentTimeStamp(std::string& timestamp) | |||
| 62 | timestamp = oss.str(); | 63 | timestamp = oss.str(); |
| 63 | } | 64 | } |
| 64 | 65 | ||
| 66 | +// Get the current OS thread id in a platform-portable way. | ||
| 67 | +static inline long long McpGetCurrentThreadId() | ||
| 68 | +{ | ||
| 69 | + return static_cast<long long>(Mcp::Platform::GetThreadId()); | ||
| 70 | +} | ||
| 71 | + | ||
| 65 | namespace Mcp::Log { | 72 | namespace Mcp::Log { |
| 66 | 73 | ||
| 67 | // Internal helper to reduce macro lines and handle C++ string formatting | 74 | // Internal helper to reduce macro lines and handle C++ string formatting |
| @@ -81,7 +88,7 @@ inline void LogInternal(MCP_LOG_LEVEL level, const char* file, const char* func, | |||
| 81 | const char* filename = strrchr(file, '/'); | 88 | const char* filename = strrchr(file, '/'); |
| 82 | filename = filename ? filename + 1 : file; | 89 | filename = filename ? filename + 1 : file; |
| 83 | 90 | ||
| 84 | - std::string prefix = "[" + timestamp + "] [" + std::to_string(syscall(SYS_gettid)) + "] [" + | 91 | + std::string prefix = "[" + timestamp + "] [" + std::to_string(McpGetCurrentThreadId()) + "] [" + |
| 85 | std::string(GetLogLevelName(level)) + "] " + std::string(filename) + "::" + | 92 | std::string(GetLogLevelName(level)) + "] " + std::string(filename) + "::" + |
| 86 | std::string(func) + ":[" + std::to_string(line) + "] "; | 93 | std::string(func) + ":[" + std::to_string(line) + "] "; |
| 87 | 94 | ||
| @@ -0,0 +1,382 @@ | |||
| 1 | +/* | ||
| 2 | + * Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved. | ||
| 3 | + */ | ||
| 4 | +#ifndef MCP_PLATFORM_COMPAT_H | ||
| 5 | +#define MCP_PLATFORM_COMPAT_H | ||
| 6 | + | ||
| 7 | +#include <errno.h> | ||
| 8 | +#include <fcntl.h> | ||
| 9 | +#include <netinet/in.h> | ||
| 10 | +#include <netinet/tcp.h> | ||
| 11 | +#include <pthread.h> | ||
| 12 | +#include <stdint.h> | ||
| 13 | +#include <sys/socket.h> | ||
| 14 | +#include <type_traits> | ||
| 15 | +#include <unistd.h> | ||
| 16 | + | ||
| 17 | +#include <atomic> | ||
| 18 | +#include <string> | ||
| 19 | + | ||
| 20 | +#if defined(__linux__) | ||
| 21 | +#include <sys/eventfd.h> | ||
| 22 | +#include <sys/syscall.h> | ||
| 23 | +#endif | ||
| 24 | + | ||
| 25 | +namespace Mcp::Platform { | ||
| 26 | + | ||
| 27 | +// Converts a pthread handle into a uint64_t tag for log correlation. The | ||
| 28 | +// pthread_t type is a pointer on some platforms and an integer of varying | ||
| 29 | +// width on others (e.g. illumos uses unsigned int); dispatch on the actual | ||
| 30 | +// representation so the fallback compiles on any of them. | ||
| 31 | +template <typename T> | ||
| 32 | +inline uint64_t PthreadToTag(const T& value) | ||
| 33 | +{ | ||
| 34 | + static_assert(std::is_integral_v<T> || std::is_pointer_v<T>, | ||
| 35 | + "Unsupported pthread_t representation on this platform; extend the " | ||
| 36 | + "GetThreadId fallback for it."); | ||
| 37 | + if constexpr (std::is_pointer_v<T>) { | ||
| 38 | + return static_cast<uint64_t>(reinterpret_cast<uintptr_t>(value)); | ||
| 39 | + } else { | ||
| 40 | + return static_cast<uint64_t>(value); | ||
| 41 | + } | ||
| 42 | +} | ||
| 43 | + | ||
| 44 | +// pthread_setname_np accepts at most 15 characters plus the terminating '\0'. | ||
| 45 | +constexpr size_t THREAD_NAME_MAX_LEN = 15; | ||
| 46 | +// A pipe provides exactly two fds: the read end and the write end. | ||
| 47 | +constexpr int PIPE_FD_COUNT = 2; | ||
| 48 | +// Drain buffer used to read wake records out of the notify pipe. | ||
| 49 | +constexpr size_t NOTIFY_DRAIN_BUF_SIZE = 64; | ||
| 50 | + | ||
| 51 | +/** | ||
| 52 | + * @brief Get the current OS thread id, matching what platform tooling reports. | ||
| 53 | + * @return Kernel thread id (Linux `gettid`, macOS 64-bit global thread id). | ||
| 54 | + */ | ||
| 55 | +inline uint64_t GetThreadId() | ||
| 56 | +{ | ||
| 57 | +#if defined(__linux__) | ||
| 58 | + return static_cast<uint64_t>(syscall(SYS_gettid)); | ||
| 59 | +#elif defined(__APPLE__) | ||
| 60 | + uint64_t tid = 0; | ||
| 61 | + pthread_threadid_np(nullptr, &tid); | ||
| 62 | + return tid; | ||
| 63 | +#else | ||
| 64 | + // No kernel tid API here: use the pthread handle as a per-thread tag so | ||
| 65 | + // at least threads within one process remain distinguishable in logs. | ||
| 66 | + return PthreadToTag(pthread_self()); | ||
| 67 | +#endif | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | +/** | ||
| 71 | + * @brief Set the name of the current thread (max 15 characters + '\0'). | ||
| 72 | + * @param name Thread name; longer names are truncated before being set. | ||
| 73 | + */ | ||
| 74 | +inline void SetCurrentThreadName(const std::string& name) | ||
| 75 | +{ | ||
| 76 | + const std::string truncatedName = name.substr(0, THREAD_NAME_MAX_LEN); | ||
| 77 | +#if defined(__APPLE__) | ||
| 78 | + (void)pthread_setname_np(truncatedName.c_str()); | ||
| 79 | +#else | ||
| 80 | + (void)pthread_setname_np(pthread_self(), truncatedName.c_str()); | ||
| 81 | +#endif | ||
| 82 | +} | ||
| 83 | + | ||
| 84 | +/** | ||
| 85 | + * @brief Set the TCP keepalive idle time (seconds). Linux uses TCP_KEEPIDLE, | ||
| 86 | + * macOS exposes the same knob as TCP_KEEPALIVE. | ||
| 87 | + * @return setsockopt result; 0 on success. | ||
| 88 | + */ | ||
| 89 | +inline int SetKeepAliveIdle(int fd, int sec) | ||
| 90 | +{ | ||
| 91 | +#if defined(__APPLE__) | ||
| 92 | + return ::setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &sec, sizeof(sec)); | ||
| 93 | +#else | ||
| 94 | + return ::setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &sec, sizeof(sec)); | ||
| 95 | +#endif | ||
| 96 | +} | ||
| 97 | + | ||
| 98 | +/** | ||
| 99 | + * @brief Set the TCP keepalive retransmit interval (seconds). | ||
| 100 | + * Silently no-ops (returns 0) on platforms without the option. | ||
| 101 | + * @return setsockopt result; 0 on success. | ||
| 102 | + */ | ||
| 103 | +inline int SetKeepAliveIntvl(int fd, int sec) | ||
| 104 | +{ | ||
| 105 | +#if defined(TCP_KEEPINTVL) | ||
| 106 | + return ::setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, &sec, sizeof(sec)); | ||
| 107 | +#else | ||
| 108 | + (void)fd; | ||
| 109 | + (void)sec; | ||
| 110 | + return 0; | ||
| 111 | +#endif | ||
| 112 | +} | ||
| 113 | + | ||
| 114 | +/** | ||
| 115 | + * @brief Set the TCP keepalive probe count. | ||
| 116 | + * Silently no-ops (returns 0) on platforms without the option. | ||
| 117 | + * @return setsockopt result; 0 on success. | ||
| 118 | + */ | ||
| 119 | +inline int SetKeepAliveCnt(int fd, int cnt) | ||
| 120 | +{ | ||
| 121 | +#if defined(TCP_KEEPCNT) | ||
| 122 | + return ::setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT, &cnt, sizeof(cnt)); | ||
| 123 | +#else | ||
| 124 | + (void)fd; | ||
| 125 | + (void)cnt; | ||
| 126 | + return 0; | ||
| 127 | +#endif | ||
| 128 | +} | ||
| 129 | + | ||
| 130 | +/** | ||
| 131 | + * @brief Cross-platform event notification channel backing EventSystem alerting. | ||
| 132 | + * Linux: a single eventfd whose counter carries the accumulated value. | ||
| 133 | + * Other platforms (e.g. macOS): a non-blocking pipe plus a software | ||
| 134 | + * counter; a wake record is written only on the empty->non-empty edge so | ||
| 135 | + * the "coalescing counter" semantics match the eventfd path. | ||
| 136 | + * | ||
| 137 | + * @note CONTRACT: both fds are ALWAYS created non-blocking by | ||
| 138 | + * CreateNotifyChannel(), and NotifyChannelNotify() relies on that: the | ||
| 139 | + * write must never block, because callers may hold the EventSystem mutex. | ||
| 140 | + * Do not assign externally created blocking fds into this struct. | ||
| 141 | + */ | ||
| 142 | +struct NotifyChannel { | ||
| 143 | + int readFd{-1}; | ||
| 144 | + int writeFd{-1}; | ||
| 145 | + std::atomic<uint64_t> counter{0}; | ||
| 146 | +}; | ||
| 147 | + | ||
| 148 | +/** | ||
| 149 | + * @brief Create the notification channel fds (non-blocking + close-on-exec). | ||
| 150 | + * @param[out] ch Channel to initialize. | ||
| 151 | + * @return 0 on success; -1 on failure (channel left untouched). | ||
| 152 | + */ | ||
| 153 | +inline int CreateNotifyChannel(NotifyChannel& ch) | ||
| 154 | +{ | ||
| 155 | +#if defined(__linux__) | ||
| 156 | + const int efd = ::eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC); | ||
| 157 | + if (efd < 0) { | ||
| 158 | + return -1; | ||
| 159 | + } | ||
| 160 | + ch.readFd = efd; | ||
| 161 | + ch.writeFd = efd; | ||
| 162 | + ch.counter.store(0, std::memory_order_relaxed); | ||
| 163 | + return 0; | ||
| 164 | +#else | ||
| 165 | + int pipeFds[PIPE_FD_COUNT] = {-1, -1}; | ||
| 166 | + if (::pipe(pipeFds) != 0) { | ||
| 167 | + return -1; | ||
| 168 | + } | ||
| 169 | + for (int i = 0; i < PIPE_FD_COUNT; ++i) { | ||
| 170 | + const int statusFlags = ::fcntl(pipeFds[i], F_GETFL, 0); | ||
| 171 | + if (statusFlags < 0 || ::fcntl(pipeFds[i], F_SETFL, statusFlags | O_NONBLOCK) < 0 || | ||
| 172 | + ::fcntl(pipeFds[i], F_SETFD, FD_CLOEXEC) < 0) { | ||
| 173 | + ::close(pipeFds[0]); | ||
| 174 | + ::close(pipeFds[1]); | ||
| 175 | + return -1; | ||
| 176 | + } | ||
| 177 | + } | ||
| 178 | + ch.readFd = pipeFds[0]; | ||
| 179 | + ch.writeFd = pipeFds[1]; | ||
| 180 | + ch.counter.store(0, std::memory_order_relaxed); | ||
| 181 | + return 0; | ||
| 182 | +#endif | ||
| 183 | +} | ||
| 184 | + | ||
| 185 | +/** | ||
| 186 | + * @brief Close both ends of the channel; safe on already-valid/empty channels. | ||
| 187 | + * @param[in,out] ch Channel to close; fds are reset to -1. | ||
| 188 | + */ | ||
| 189 | +inline void CloseNotifyChannel(NotifyChannel& ch) | ||
| 190 | +{ | ||
| 191 | + if (ch.writeFd >= 0 && ch.writeFd != ch.readFd) { | ||
| 192 | + ::close(ch.writeFd); | ||
| 193 | + } | ||
| 194 | + if (ch.readFd >= 0) { | ||
| 195 | + ::close(ch.readFd); | ||
| 196 | + } | ||
| 197 | + ch.readFd = -1; | ||
| 198 | + ch.writeFd = -1; | ||
| 199 | +} | ||
| 200 | + | ||
| 201 | +/** | ||
| 202 | + * @brief Raw 8-byte eventfd write (Linux baseline semantics). | ||
| 203 | + * @return true on a complete write; false on error (EAGAIN included). | ||
| 204 | + */ | ||
| 205 | +inline bool WriteChannelFdRaw(int fd, uint64_t value) | ||
| 206 | +{ | ||
| 207 | +#if defined(__linux__) | ||
| 208 | + const uint64_t val = value; | ||
| 209 | + while (true) { | ||
| 210 | + const ssize_t written = ::write(fd, &val, sizeof(val)); | ||
| 211 | + if (written == static_cast<ssize_t>(sizeof(val))) { | ||
| 212 | + return true; | ||
| 213 | + } | ||
| 214 | + if (written < 0) { | ||
| 215 | + if (errno == EINTR) { | ||
| 216 | + continue; | ||
| 217 | + } | ||
| 218 | + return false; | ||
| 219 | + } | ||
| 220 | + return false; | ||
| 221 | + } | ||
| 222 | +#else | ||
| 223 | + (void)fd; | ||
| 224 | + (void)value; | ||
| 225 | + return false; | ||
| 226 | +#endif | ||
| 227 | +} | ||
| 228 | + | ||
| 229 | +/** | ||
| 230 | + * @brief Increment the notification counter and provide a wake record. | ||
| 231 | + * @return true when the increment is committed (a full pipe still counts as | ||
| 232 | + * success: a wake record is already pending); false otherwise. | ||
| 233 | + * @note Callers must serialize Notify against Read for the same channel. | ||
| 234 | + */ | ||
| 235 | +inline bool NotifyChannelNotify(NotifyChannel& ch, uint64_t value) | ||
| 236 | +{ | ||
| 237 | +#if defined(__linux__) | ||
| 238 | + return WriteChannelFdRaw(ch.writeFd, value); | ||
| 239 | +#else | ||
| 240 | + // eventfd parity: a zero increment is a successful no-op. | ||
| 241 | + if (value == 0) { | ||
| 242 | + return true; | ||
| 243 | + } | ||
| 244 | + | ||
| 245 | + // Same counter bound as eventfd; reject invalid increments before the | ||
| 246 | + // subtraction below can underflow. | ||
| 247 | + constexpr uint64_t MAX_COUNTER = UINT64_MAX - 1; | ||
| 248 | + if (value > MAX_COUNTER) { | ||
| 249 | + return false; | ||
| 250 | + } | ||
| 251 | + | ||
| 252 | + uint64_t current = ch.counter.load(std::memory_order_relaxed); | ||
| 253 | + while (current <= MAX_COUNTER - value) { | ||
| 254 | + if (ch.counter.compare_exchange_weak( | ||
| 255 | + current, current + value, | ||
| 256 | + std::memory_order_acq_rel, std::memory_order_relaxed)) { | ||
| 257 | + break; | ||
| 258 | + } | ||
| 259 | + } | ||
| 260 | + if (current > MAX_COUNTER - value) { | ||
| 261 | + return false; | ||
| 262 | + } | ||
| 263 | + if (current > 0) { | ||
| 264 | + // Coalesce into the pending wake record. | ||
| 265 | + return true; | ||
| 266 | + } | ||
| 267 | + | ||
| 268 | + // Only the empty->non-empty edge writes a wake byte, so the pipe holds at | ||
| 269 | + // most one byte and a drain needs at most two reads. Keep this invariant. | ||
| 270 | + const uint8_t wakeByte = 1; | ||
| 271 | + while (true) { | ||
| 272 | + const ssize_t written = ::write(ch.writeFd, &wakeByte, sizeof(wakeByte)); | ||
| 273 | + if (written == static_cast<ssize_t>(sizeof(wakeByte))) { | ||
| 274 | + return true; | ||
| 275 | + } | ||
| 276 | + if (written < 0) { | ||
| 277 | + if (errno == EINTR) { | ||
| 278 | + continue; | ||
| 279 | + } | ||
| 280 | + if (errno == EAGAIN || errno == EWOULDBLOCK) { | ||
| 281 | + // Count committed and a wake record is pending: deliverable. | ||
| 282 | + return true; | ||
| 283 | + } | ||
| 284 | + // Undeliverable: roll back the committed increment. | ||
| 285 | + ch.counter.fetch_sub(value, std::memory_order_acq_rel); | ||
| 286 | + return false; | ||
| 287 | + } | ||
| 288 | + ch.counter.fetch_sub(value, std::memory_order_acq_rel); | ||
| 289 | + return false; | ||
| 290 | + } | ||
| 291 | +#endif | ||
| 292 | +} | ||
| 293 | + | ||
| 294 | +/** | ||
| 295 | + * @brief Read the accumulated counter value from the channel and reset it. | ||
| 296 | + * Linux reads the eventfd; pipe reads drain the wake records and then | ||
| 297 | + * return the software counter. | ||
| 298 | + * @return true and @p outValue set on success; false when empty / on error. | ||
| 299 | + */ | ||
| 300 | +inline bool NotifyChannelRead(NotifyChannel& ch, int readFd, uint64_t& outValue) | ||
| 301 | +{ | ||
| 302 | +#if defined(__linux__) | ||
| 303 | + uint64_t val = 0; | ||
| 304 | + while (true) { | ||
| 305 | + const ssize_t rd = ::read(readFd, &val, sizeof(val)); | ||
| 306 | + if (rd == static_cast<ssize_t>(sizeof(val))) { | ||
| 307 | + outValue = val; | ||
| 308 | + return true; | ||
| 309 | + } | ||
| 310 | + if (rd < 0) { | ||
| 311 | + if (errno == EINTR) { | ||
| 312 | + continue; | ||
| 313 | + } | ||
| 314 | + return false; | ||
| 315 | + } | ||
| 316 | + return false; | ||
| 317 | + } | ||
| 318 | +#else | ||
| 319 | + // At most one wake byte is pending (see NotifyChannelNotify); in the | ||
| 320 | + // normal path (EINTR retries aside) this loop reads at most twice. | ||
| 321 | + uint8_t buffer[NOTIFY_DRAIN_BUF_SIZE]; | ||
| 322 | + while (true) { | ||
| 323 | + const ssize_t rd = ::read(readFd, buffer, sizeof(buffer)); | ||
| 324 | + if (rd > 0) { | ||
| 325 | + continue; | ||
| 326 | + } | ||
| 327 | + if (rd < 0) { | ||
| 328 | + if (errno == EINTR) { | ||
| 329 | + continue; | ||
| 330 | + } | ||
| 331 | + if (errno == EAGAIN || errno == EWOULDBLOCK) { | ||
| 332 | + break; | ||
| 333 | + } | ||
| 334 | + return false; | ||
| 335 | + } | ||
| 336 | + break; | ||
| 337 | + } | ||
| 338 | + | ||
| 339 | + const uint64_t count = ch.counter.exchange(0, std::memory_order_acq_rel); | ||
| 340 | + if (count == 0) { | ||
| 341 | + errno = EAGAIN; | ||
| 342 | + return false; | ||
| 343 | + } | ||
| 344 | + | ||
| 345 | + outValue = count; | ||
| 346 | + return true; | ||
| 347 | +#endif | ||
| 348 | +} | ||
| 349 | + | ||
| 350 | +/** | ||
| 351 | + * @brief Fallback raw read for fds without a registered notify channel. | ||
| 352 | + * Linux keeps the legacy 8-byte read semantics; other platforms do not | ||
| 353 | + * support it (always false), matching previous behavior. | ||
| 354 | + * @return true and @p outValue set on success; false otherwise. | ||
| 355 | + */ | ||
| 356 | +inline bool ReadChannelFdRaw(int fd, uint64_t& outValue) | ||
| 357 | +{ | ||
| 358 | +#if defined(__linux__) | ||
| 359 | + uint64_t val = 0; | ||
| 360 | + while (true) { | ||
| 361 | + const ssize_t rd = ::read(fd, &val, sizeof(val)); | ||
| 362 | + if (rd == static_cast<ssize_t>(sizeof(val))) { | ||
| 363 | + outValue = val; | ||
| 364 | + return true; | ||
| 365 | + } | ||
| 366 | + if (rd < 0) { | ||
| 367 | + if (errno == EINTR) { | ||
| 368 | + continue; | ||
| 369 | + } | ||
| 370 | + return false; | ||
| 371 | + } | ||
| 372 | + return false; | ||
| 373 | + } | ||
| 374 | +#else | ||
| 375 | + (void)fd; | ||
| 376 | + (void)outValue; | ||
| 377 | + return false; | ||
| 378 | +#endif | ||
| 379 | +} | ||
| 380 | + | ||
| 381 | +} // namespace Mcp::Platform | ||
| 382 | +#endif | ||
| @@ -144,8 +144,14 @@ if [[ ${WITH_ASAN} -eq 1 ]]; then | |||
| 144 | CMAKE_ARGS+=("-DASAN=enable") | 144 | CMAKE_ARGS+=("-DASAN=enable") |
| 145 | fi | 145 | fi |
| 146 | 146 | ||
| 147 | -# Determine optimal job count for Linux (CPU cores + 1, but max 8 to avoid memory issues) | 147 | +# Determine optimal job count (CPU cores + 1, but max 8 to avoid memory issues) |
| 148 | -CPU_CORES=$(nproc) | 148 | +if command -v nproc >/dev/null 2>&1; then |
| 149 | + CPU_CORES=$(nproc) | ||
| 150 | +elif command -v sysctl >/dev/null 2>&1; then | ||
| 151 | + CPU_CORES=$(sysctl -n hw.ncpu) | ||
| 152 | +else | ||
| 153 | + CPU_CORES=4 | ||
| 154 | +fi | ||
| 149 | OPTIMAL_JOBS=$((CPU_CORES + 1)) | 155 | OPTIMAL_JOBS=$((CPU_CORES + 1)) |
| 150 | if [[ ${OPTIMAL_JOBS} -gt 8 ]]; then | 156 | if [[ ${OPTIMAL_JOBS} -gt 8 ]]; then |
| 151 | OPTIMAL_JOBS=8 | 157 | OPTIMAL_JOBS=8 |
| @@ -12,7 +12,10 @@ set -euo pipefail | |||
| 12 | echo "==> Checking system dependencies for mcp_cpp..." | 12 | echo "==> Checking system dependencies for mcp_cpp..." |
| 13 | 13 | ||
| 14 | # Detect OS type | 14 | # Detect OS type |
| 15 | -if [ -f /etc/os-release ]; then | 15 | +if [ "$(uname -s)" = "Darwin" ]; then |
| 16 | + OS="macos" | ||
| 17 | + OS_VERSION="$(sw_vers -productVersion 2>/dev/null || echo unknown)" | ||
| 18 | +elif [ -f /etc/os-release ]; then | ||
| 16 | . /etc/os-release | 19 | . /etc/os-release |
| 17 | OS=$ID | 20 | OS=$ID |
| 18 | OS_VERSION=$VERSION_ID | 21 | OS_VERSION=$VERSION_ID |
| @@ -48,6 +51,8 @@ check_yum_package() { | |||
| 48 | install_dependencies() { | 51 | install_dependencies() { |
| 49 | local need_curl=0 | 52 | local need_curl=0 |
| 50 | local need_openssl=0 | 53 | local need_openssl=0 |
| 54 | + local need_libevent=0 | ||
| 55 | + local need_json=0 | ||
| 51 | 56 | ||
| 52 | # Check dependencies (both runtime lib and development packages) | 57 | # Check dependencies (both runtime lib and development packages) |
| 53 | case "$OS" in | 58 | case "$OS" in |
| @@ -136,6 +141,39 @@ install_dependencies() { | |||
| 136 | fi | 141 | fi |
| 137 | ;; | 142 | ;; |
| 138 | 143 | ||
| 144 | + macos) | ||
| 145 | + if ! command_exists brew; then | ||
| 146 | + echo " - Homebrew: NOT FOUND (see https://brew.sh)" | ||
| 147 | + need_curl=1 | ||
| 148 | + need_openssl=1 | ||
| 149 | + else | ||
| 150 | + if brew list --versions curl >/dev/null 2>&1; then | ||
| 151 | + echo " - curl: OK" | ||
| 152 | + else | ||
| 153 | + echo " - curl: NOT FOUND" | ||
| 154 | + need_curl=1 | ||
| 155 | + fi | ||
| 156 | + if brew list --versions openssl@3 >/dev/null 2>&1 || brew list --versions openssl >/dev/null 2>&1; then | ||
| 157 | + echo " - openssl: OK" | ||
| 158 | + else | ||
| 159 | + echo " - openssl: NOT FOUND" | ||
| 160 | + need_openssl=1 | ||
| 161 | + fi | ||
| 162 | + if brew list --versions libevent >/dev/null 2>&1; then | ||
| 163 | + echo " - libevent: OK" | ||
| 164 | + else | ||
| 165 | + echo " - libevent: NOT FOUND" | ||
| 166 | + need_libevent=1 | ||
| 167 | + fi | ||
| 168 | + if brew list --versions nlohmann-json >/dev/null 2>&1; then | ||
| 169 | + echo " - nlohmann_json: OK" | ||
| 170 | + else | ||
| 171 | + echo " - nlohmann_json: NOT FOUND" | ||
| 172 | + need_json=1 | ||
| 173 | + fi | ||
| 174 | + fi | ||
| 175 | + ;; | ||
| 176 | + | ||
| 139 | *) | 177 | *) |
| 140 | # Fallback: check for header files | 178 | # Fallback: check for header files |
| 141 | if command_exists curl-config; then | 179 | if command_exists curl-config; then |
| @@ -155,7 +193,7 @@ install_dependencies() { | |||
| 155 | esac | 193 | esac |
| 156 | 194 | ||
| 157 | # If all dependencies are present, exit | 195 | # If all dependencies are present, exit |
| 158 | - if [ $need_curl -eq 0 ] && [ $need_openssl -eq 0 ]; then | 196 | + if [ $need_curl -eq 0 ] && [ $need_openssl -eq 0 ] && [ $need_libevent -eq 0 ] && [ $need_json -eq 0 ]; then |
| 159 | echo "==> All dependencies are already installed!" | 197 | echo "==> All dependencies are already installed!" |
| 160 | return 0 | 198 | return 0 |
| 161 | fi | 199 | fi |
| @@ -215,6 +253,25 @@ install_dependencies() { | |||
| 215 | fi | 253 | fi |
| 216 | ;; | 254 | ;; |
| 217 | 255 | ||
| 256 | + macos) | ||
| 257 | + echo "Detected macOS system" | ||
| 258 | + | ||
| 259 | + if ! command_exists brew; then | ||
| 260 | + echo "Error: Homebrew is required on macOS (see https://brew.sh)" >&2 | ||
| 261 | + exit 1 | ||
| 262 | + fi | ||
| 263 | + | ||
| 264 | + local pkgs=() | ||
| 265 | + [ $need_curl -eq 1 ] && pkgs+=(curl) | ||
| 266 | + [ $need_openssl -eq 1 ] && pkgs+=(openssl@3) | ||
| 267 | + [ $need_libevent -eq 1 ] && pkgs+=(libevent) | ||
| 268 | + [ $need_json -eq 1 ] && pkgs+=(nlohmann-json) | ||
| 269 | + if [ ${#pkgs[@]} -gt 0 ]; then | ||
| 270 | + echo "Installing (Homebrew): ${pkgs[*]}" | ||
| 271 | + brew install "${pkgs[@]}" | ||
| 272 | + fi | ||
| 273 | + ;; | ||
| 274 | + | ||
| 218 | *) | 275 | *) |
| 219 | echo "Error: Unsupported OS: $OS" | 276 | echo "Error: Unsupported OS: $OS" |
| 220 | echo "Please install libcurl-devel and openssl manually" | 277 | echo "Please install libcurl-devel and openssl manually" |
| @@ -232,6 +289,45 @@ install_dependencies | |||
| 232 | # Verify installation | 289 | # Verify installation |
| 233 | echo "" | 290 | echo "" |
| 234 | echo "==> Verifying installation..." | 291 | echo "==> Verifying installation..." |
| 292 | +if [ "$OS" = "macos" ]; then | ||
| 293 | + ok=1 | ||
| 294 | + if ! command_exists brew; then | ||
| 295 | + echo "✗ Homebrew is missing." >&2 | ||
| 296 | + ok=0 | ||
| 297 | + fi | ||
| 298 | + # Same package checks as the install step above, so a partially failed | ||
| 299 | + # install is reported here instead of failing later at CMake configure. | ||
| 300 | + if brew list --versions openssl@3 >/dev/null 2>&1 || brew list --versions openssl >/dev/null 2>&1; then | ||
| 301 | + echo " - openssl: OK" | ||
| 302 | + else | ||
| 303 | + echo "✗ openssl is missing (brew install openssl@3)" >&2 | ||
| 304 | + ok=0 | ||
| 305 | + fi | ||
| 306 | + if brew list --versions curl >/dev/null 2>&1; then | ||
| 307 | + echo " - curl: OK" | ||
| 308 | + else | ||
| 309 | + echo "✗ curl is missing (brew install curl)" >&2 | ||
| 310 | + ok=0 | ||
| 311 | + fi | ||
| 312 | + if brew list --versions libevent >/dev/null 2>&1; then | ||
| 313 | + echo " - libevent: OK" | ||
| 314 | + else | ||
| 315 | + echo "✗ libevent is missing (brew install libevent)" >&2 | ||
| 316 | + ok=0 | ||
| 317 | + fi | ||
| 318 | + if brew list --versions nlohmann-json >/dev/null 2>&1; then | ||
| 319 | + echo " - nlohmann_json: OK" | ||
| 320 | + else | ||
| 321 | + echo "✗ nlohmann_json is missing (brew install nlohmann-json)" >&2 | ||
| 322 | + ok=0 | ||
| 323 | + fi | ||
| 324 | + if [ "${ok}" -eq 1 ]; then | ||
| 325 | + echo "✓ Dependencies verified (Homebrew)." | ||
| 326 | + exit 0 | ||
| 327 | + fi | ||
| 328 | + echo "✗ Some dependencies are still missing. Please check the errors above." >&2 | ||
| 329 | + exit 1 | ||
| 330 | +fi | ||
| 235 | if command_exists curl-config && command_exists openssl; then | 331 | if command_exists curl-config && command_exists openssl; then |
| 236 | echo "✓ All dependencies verified successfully!" | 332 | echo "✓ All dependencies verified successfully!" |
| 237 | exit 0 | 333 | exit 0 |
| @@ -115,7 +115,7 @@ public: | |||
| 115 | /** Send notifications/progress to the server (MCP progress tracking). progressToken is string or int64_t. */ | 115 | /** Send notifications/progress to the server (MCP progress tracking). progressToken is string or int64_t. */ |
| 116 | void SendProgressNotification(ProgressToken progressToken, double progress, | 116 | void SendProgressNotification(ProgressToken progressToken, double progress, |
| 117 | std::optional<double> total = std::nullopt, | 117 | std::optional<double> total = std::nullopt, |
| 118 | - const std::optional<std::string>& message = std::nullopt); | 118 | + const std::optional<std::string>& message = std::nullopt) override; |
| 119 | 119 | ||
| 120 | protected: | 120 | protected: |
| 121 | /** | 121 | /** |
| @@ -4,8 +4,6 @@ | |||
| 4 | 4 | ||
| 5 | #include "http_client_service.h" | 5 | #include "http_client_service.h" |
| 6 | 6 | ||
| 7 | -#include <sys/syscall.h> | ||
| 8 | - | ||
| 9 | #include <algorithm> | 7 | #include <algorithm> |
| 10 | #include <cstring> | 8 | #include <cstring> |
| 11 | #include <queue> | 9 | #include <queue> |
| @@ -5,8 +5,6 @@ | |||
| 5 | #include "event_system.h" | 5 | #include "event_system.h" |
| 6 | 6 | ||
| 7 | #include <event2/util.h> | 7 | #include <event2/util.h> |
| 8 | -#include <fcntl.h> | ||
| 9 | -#include <sys/eventfd.h> | ||
| 10 | #include <unistd.h> | 8 | #include <unistd.h> |
| 11 | 9 | ||
| 12 | #include <atomic> | 10 | #include <atomic> |
| @@ -19,6 +17,7 @@ | |||
| 19 | 17 | ||
| 20 | #include "mcp_log.h" | 18 | #include "mcp_log.h" |
| 21 | #include "shared/thread_utils.h" | 19 | #include "shared/thread_utils.h" |
| 20 | +#include "platform_compat.h" | ||
| 22 | 21 | ||
| 23 | namespace Mcp { | 22 | namespace Mcp { |
| 24 | 23 | ||
| @@ -27,6 +26,7 @@ using EventMask = std::underlying_type_t<EventType>; | |||
| 27 | constexpr long MS_PER_SECOND = 1000; | 26 | constexpr long MS_PER_SECOND = 1000; |
| 28 | constexpr long US_PER_MS = 1000; | 27 | constexpr long US_PER_MS = 1000; |
| 29 | 28 | ||
| 29 | + | ||
| 30 | // Translate the internal EventType bitmask into libevent flags. | 30 | // Translate the internal EventType bitmask into libevent flags. |
| 31 | short ToLibeventFlags(EventType events) | 31 | short ToLibeventFlags(EventType events) |
| 32 | { | 32 | { |
| @@ -93,6 +93,7 @@ struct EventSystem::Impl { | |||
| 93 | std::unique_ptr<event, decltype(&event_free)> handle{nullptr, &event_free}; | 93 | std::unique_ptr<event, decltype(&event_free)> handle{nullptr, &event_free}; |
| 94 | short flags{0}; | 94 | short flags{0}; |
| 95 | bool persistent{false}; | 95 | bool persistent{false}; |
| 96 | + Platform::NotifyChannel notifyChannel; | ||
| 96 | 97 | ||
| 97 | static void eventCallbackAdapter(evutil_socket_t eventFd, short events, void* arg) | 98 | static void eventCallbackAdapter(evutil_socket_t eventFd, short events, void* arg) |
| 98 | { | 99 | { |
| @@ -133,6 +134,9 @@ struct EventSystem::Impl { | |||
| 133 | bool enableThreadSupport{false}; | 134 | bool enableThreadSupport{false}; |
| 134 | std::atomic<int> nextEventId{1}; | 135 | std::atomic<int> nextEventId{1}; |
| 135 | std::unordered_map<int, std::unique_ptr<EventData>> events; | 136 | std::unordered_map<int, std::unique_ptr<EventData>> events; |
| 137 | + // Notify-channel events indexed by their registered read fd (guarded by the | ||
| 138 | + // EventSystem mutex). Keeps ReadEventFd O(1) without exposing raw pointers. | ||
| 139 | + std::unordered_map<int, EventData*> notifyEventsByFd; | ||
| 136 | std::thread eventThread; | 140 | std::thread eventThread; |
| 137 | }; | 141 | }; |
| 138 | 142 | ||
| @@ -149,6 +153,7 @@ EventSystem::~EventSystem() | |||
| 149 | { | 153 | { |
| 150 | std::lock_guard<std::mutex> lock(mutex_); | 154 | std::lock_guard<std::mutex> lock(mutex_); |
| 151 | events.swap(impl_->events); | 155 | events.swap(impl_->events); |
| 156 | + impl_->notifyEventsByFd.clear(); | ||
| 152 | } | 157 | } |
| 153 | 158 | ||
| 154 | for (auto& entry : events) { | 159 | for (auto& entry : events) { |
| @@ -156,6 +161,11 @@ EventSystem::~EventSystem() | |||
| 156 | event_del(entry.second->handle.get()); | 161 | event_del(entry.second->handle.get()); |
| 157 | entry.second->handle.reset(); | 162 | entry.second->handle.reset(); |
| 158 | } | 163 | } |
| 164 | + // Only fds created by CreateNotifyEventId are owned here. Fds passed to | ||
| 165 | + // AddEvent stay owned by their callers and must never be closed by us. | ||
| 166 | + if (entry.second != nullptr) { | ||
| 167 | + Platform::CloseNotifyChannel(entry.second->notifyChannel); | ||
| 168 | + } | ||
| 159 | } | 169 | } |
| 160 | 170 | ||
| 161 | if (event_base_ != nullptr) { | 171 | if (event_base_ != nullptr) { |
| @@ -266,76 +276,83 @@ int EventSystem::CreateNotifyEventId(EventCallback callback, void* arg, bool per | |||
| 266 | return -1; | 276 | return -1; |
| 267 | } | 277 | } |
| 268 | 278 | ||
| 269 | - // Create an eventfd with non-blocking and close-on-exec flags. | 279 | + Platform::NotifyChannel channel; |
| 270 | - int efd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC); | 280 | + if (Platform::CreateNotifyChannel(channel) != 0) { |
| 271 | - if (efd < 0) { | 281 | + MCP_LOG(MCP_LOG_LEVEL_ERROR, "Create notify channel failed."); |
| 272 | - MCP_LOG(MCP_LOG_LEVEL_ERROR, "Create eventfd failed."); | ||
| 273 | return -1; | 282 | return -1; |
| 274 | } | 283 | } |
| 275 | 284 | ||
| 276 | - // Register the eventfd for read events. Make it persistent by default unless caller says otherwise. | 285 | + // Register the read end for read events. Make it persistent by default unless caller says otherwise. |
| 277 | EventType type = EventType::READ; | 286 | EventType type = EventType::READ; |
| 278 | if (persist) { | 287 | if (persist) { |
| 279 | type = static_cast<EventType>(static_cast<int>(type) | static_cast<int>(EventType::PERSIST)); | 288 | type = static_cast<EventType>(static_cast<int>(type) | static_cast<int>(EventType::PERSIST)); |
| 280 | } | 289 | } |
| 281 | 290 | ||
| 282 | - int eventId = AddEvent(efd, type, std::move(callback), arg, 0); | 291 | + int eventId = AddEvent(channel.readFd, type, std::move(callback), arg, 0); |
| 283 | if (eventId < 0) { | 292 | if (eventId < 0) { |
| 284 | - MCP_LOG(MCP_LOG_LEVEL_ERROR, "Failed to add eventFd to the event system."); | 293 | + MCP_LOG(MCP_LOG_LEVEL_ERROR, "Failed to add notify fd to the event system."); |
| 285 | - ::close(efd); | 294 | + Platform::CloseNotifyChannel(channel); |
| 286 | return -1; | 295 | return -1; |
| 287 | } | 296 | } |
| 288 | 297 | ||
| 298 | + { | ||
| 299 | + std::lock_guard<std::mutex> lock(mutex_); | ||
| 300 | + auto it = impl_->events.find(eventId); | ||
| 301 | + if (it != impl_->events.end() && it->second != nullptr) { | ||
| 302 | + it->second->notifyChannel.readFd = channel.readFd; | ||
| 303 | + it->second->notifyChannel.writeFd = channel.writeFd; | ||
| 304 | + impl_->notifyEventsByFd[channel.readFd] = it->second.get(); | ||
| 305 | + } | ||
| 306 | + } | ||
| 307 | + | ||
| 289 | return eventId; | 308 | return eventId; |
| 290 | } | 309 | } |
| 291 | 310 | ||
| 292 | bool EventSystem::NotifyEventId(int eventId, uint64_t increment) | 311 | bool EventSystem::NotifyEventId(int eventId, uint64_t increment) |
| 293 | { | 312 | { |
| 294 | - // Use eventfd write to increment the counter atomically. | 313 | +#if defined(__linux__) |
| 295 | - ssize_t written = 0; | 314 | + // Baseline: resolve the fd under the mutex, write outside it. |
| 296 | - const uint64_t val = increment; | 315 | + int eventFd = -1; |
| 297 | - | 316 | + { |
| 298 | - int eventFd = ToEventFd(eventId); | 317 | + std::lock_guard<std::mutex> lock(mutex_); |
| 299 | - if (eventFd == -1) { | 318 | + auto it = impl_->events.find(eventId); |
| 319 | + if (it == impl_->events.end() || it->second == nullptr) { | ||
| 320 | + MCP_LOG(MCP_LOG_LEVEL_ERROR, "The eventId not found."); | ||
| 321 | + return false; | ||
| 322 | + } | ||
| 323 | + eventFd = it->second->fd; | ||
| 324 | + } | ||
| 325 | + return Platform::WriteChannelFdRaw(eventFd, increment); | ||
| 326 | +#else | ||
| 327 | + // macOS: the channel may be closed concurrently, so write under the lock. | ||
| 328 | + std::lock_guard<std::mutex> lock(mutex_); | ||
| 329 | + auto it = impl_->events.find(eventId); | ||
| 330 | + if (it == impl_->events.end() || it->second == nullptr) { | ||
| 300 | MCP_LOG(MCP_LOG_LEVEL_ERROR, "The eventId not found."); | 331 | MCP_LOG(MCP_LOG_LEVEL_ERROR, "The eventId not found."); |
| 301 | return false; | 332 | return false; |
| 302 | } | 333 | } |
| 303 | - while (true) { | 334 | + |
| 304 | - written = ::write(eventFd, &val, sizeof(val)); | 335 | + return Platform::NotifyChannelNotify(it->second->notifyChannel, increment); |
【review】并发设计。NotifyEventId 改为在持有 mutex_ 的情况下调用 NotifyChannelNotify,后者在管道模式下会执行 ::write 系统调用。这使原本「锁内取 fd、锁外写」的路径变成了持锁执行 I/O,而 NotifyEventId 在每次请求分发时都会调用,与事件线程上的 ReadEventFd 形成同一把锁上的竞争。当前正确性依赖「写端必为非阻塞」这一隐含前提,一旦将来有人绕过 CreateNotifyChannel 构造 NotifyChannel 或误配 fd,就会在持锁期间无限等待,连带阻塞 RemoveEvent 与整个事件系统。建议锁内只拷贝 writeFd 等必要状态,释放锁后再执行写;若保持现状,请在结构体或函数注释中显式声明「writeFd 必须为非阻塞」,把隐含前提变成显式契约。 ![]() ![]() | |||
| 305 | - if (written == static_cast<ssize_t>(sizeof(val))) { | 336 | +#endif |
| 306 | - return true; | ||
| 307 | - } | ||
| 308 | - if (written < 0) { | ||
| 309 | - if (errno == EINTR) { | ||
| 310 | - continue; // retry | ||
| 311 | - } | ||
| 312 | - // EAGAIN/EWOULDBLOCK means the fd would block; treat as failure for notify. | ||
| 313 | - return false; | ||
| 314 | - } | ||
| 315 | - // Partial write, treat as failure. | ||
| 316 | - return false; | ||
| 317 | - } | ||
| 318 | } | 337 | } |
| 319 | 338 | ||
| 320 | bool EventSystem::ReadEventFd(int fd, uint64_t& outValue) | 339 | bool EventSystem::ReadEventFd(int fd, uint64_t& outValue) |
| 321 | { | 340 | { |
| 322 | - uint64_t val = 0; | 341 | +#if defined(__linux__) |
| 323 | - ssize_t rd = 0; | 342 | + // Baseline: plain eventfd read without the lock or a map lookup. |
| 324 | - while (true) { | 343 | + return Platform::ReadChannelFdRaw(fd, outValue); |
| 325 | - rd = ::read(fd, &val, sizeof(val)); | 344 | +#else |
| 326 | - if (rd == static_cast<ssize_t>(sizeof(val))) { | 345 | + // Keep the lookup and the read inside the lock: no raw EventData pointer |
| 327 | - outValue = val; | 346 | + // escapes the critical section, so a concurrent RemoveEvent/destruction |
| 328 | - return true; | 347 | + // cannot invalidate it. |
| 329 | - } | 348 | + std::lock_guard<std::mutex> lock(mutex_); |
| 330 | - if (rd < 0) { | 349 | + auto it = impl_->notifyEventsByFd.find(fd); |
| 331 | - if (errno == EINTR) { | 350 | + if (it != impl_->notifyEventsByFd.end() && it->second != nullptr) { |
| 332 | - continue; // retry | 351 | + return Platform::NotifyChannelRead(it->second->notifyChannel, fd, outValue); |
| 333 | - } | ||
| 334 | - return false; | ||
| 335 | - } | ||
| 336 | - // Partial read or EOF | ||
| 337 | - return false; | ||
| 338 | } | 352 | } |
| 353 | + | ||
| 354 | + return Platform::ReadChannelFdRaw(fd, outValue); | ||
| 355 | +#endif | ||
| 339 | } | 356 | } |
| 340 | 357 | ||
| 341 | bool EventSystem::CloseNotifyEventId(int eventId) | 358 | bool EventSystem::CloseNotifyEventId(int eventId) |
| @@ -366,6 +383,9 @@ bool EventSystem::RemoveEventInternal(int eventId, bool closeFd) | |||
| 366 | } | 383 | } |
| 367 | data = std::move(it->second); | 384 | data = std::move(it->second); |
| 368 | impl_->events.erase(it); | 385 | impl_->events.erase(it); |
| 386 | + if (data != nullptr && data->notifyChannel.readFd >= 0) { | ||
| 387 | + impl_->notifyEventsByFd.erase(data->fd); | ||
| 388 | + } | ||
| 369 | } | 389 | } |
| 370 | 390 | ||
| 371 | if (data != nullptr && data->handle != nullptr) { | 391 | if (data != nullptr && data->handle != nullptr) { |
| @@ -373,8 +393,13 @@ bool EventSystem::RemoveEventInternal(int eventId, bool closeFd) | |||
| 373 | data->handle.reset(); | 393 | data->handle.reset(); |
| 374 | } | 394 | } |
| 375 | 395 | ||
| 376 | - if (closeFd && data != nullptr && data->fd >= 0) { | 396 | + if (closeFd && data != nullptr) { |
| 377 | - ::close(data->fd); | 397 | + if (data->notifyChannel.readFd >= 0) { |
| 398 | + Platform::CloseNotifyChannel(data->notifyChannel); | ||
| 399 | + data->fd = -1; | ||
| 400 | + } else if (data->fd >= 0) { | ||
| 401 | + ::close(data->fd); | ||
| 402 | + } | ||
| 378 | } | 403 | } |
| 379 | 404 | ||
| 380 | return true; | 405 | return true; |
| @@ -120,9 +120,12 @@ public: | |||
| 120 | /** | 120 | /** |
| 121 | * @brief Notify (write) to a notify eventId to wake up listeners. By default writes the value 1. | 121 | * @brief Notify (write) to a notify eventId to wake up listeners. By default writes the value 1. |
| 122 | * @param eventId The eventId returned by CreateNotifyEventId. | 122 | * @param eventId The eventId returned by CreateNotifyEventId. |
| 123 | - * @param increment The 64-bit value to add to the eventfd counter (default 1). | 123 | + * @param increment The 64-bit value to add to the eventfd counter (default 1). |
| 124 | - * @return true on success, false on failure. | 124 | + * @return true on success, false on failure. |
| 125 | - */ | 125 | + * @note Linux writes the event's fd directly (baseline). macOS writes |
| 126 | + * through the notify channel and only accepts eventIds from | ||
| 127 | + * CreateNotifyEventId. | ||
| 128 | + */ | ||
| 126 | bool NotifyEventId(int eventId, uint64_t increment = 1); | 129 | bool NotifyEventId(int eventId, uint64_t increment = 1); |
| 127 | 130 | ||
| 128 | /** | 131 | /** |
| @@ -17,6 +17,7 @@ | |||
| 17 | #include <cstring> | 17 | #include <cstring> |
| 18 | 18 | ||
| 19 | #include "mcp_log.h" | 19 | #include "mcp_log.h" |
| 20 | +#include "platform_compat.h" | ||
| 20 | 21 | ||
| 21 | namespace Mcp::Net { | 22 | namespace Mcp::Net { |
| 22 | 23 | ||
| @@ -291,17 +292,15 @@ void TcpSocket::SetTcpOptions(const TcpSocketOptions& opts) | |||
| 291 | " (" + std::to_string(errno) + ")"); | 292 | " (" + std::to_string(errno) + ")"); |
| 292 | } | 293 | } |
| 293 | if (opts.keepAliveIdleSec > 0) { | 294 | if (opts.keepAliveIdleSec > 0) { |
| 294 | - rc = ::setsockopt(fd_, IPPROTO_TCP, TCP_KEEPIDLE, &opts.keepAliveIdleSec, | 295 | + rc = Platform::SetKeepAliveIdle(fd_, opts.keepAliveIdleSec); |
| 295 | - static_cast<socklen_t>(sizeof(opts.keepAliveIdleSec))); | ||
| 296 | if (rc != 0) { | 296 | if (rc != 0) { |
| 297 | MCP_LOG(MCP_LOG_LEVEL_WARN, | 297 | MCP_LOG(MCP_LOG_LEVEL_WARN, |
| 298 | - std::string("setsockopt(TCP_KEEPIDLE) failed: ") + std::strerror(errno) + | 298 | + std::string("setsockopt(keepalive idle) failed: ") + std::strerror(errno) + |
| 299 | " (" + std::to_string(errno) + ")"); | 299 | " (" + std::to_string(errno) + ")"); |
| 300 | } | 300 | } |
| 301 | } | 301 | } |
| 302 | if (opts.keepAliveIntvlSec > 0) { | 302 | if (opts.keepAliveIntvlSec > 0) { |
| 303 | - rc = ::setsockopt(fd_, IPPROTO_TCP, TCP_KEEPINTVL, &opts.keepAliveIntvlSec, | 303 | + rc = Platform::SetKeepAliveIntvl(fd_, opts.keepAliveIntvlSec); |
| 304 | - static_cast<socklen_t>(sizeof(opts.keepAliveIntvlSec))); | ||
| 305 | if (rc != 0) { | 304 | if (rc != 0) { |
| 306 | MCP_LOG(MCP_LOG_LEVEL_WARN, | 305 | MCP_LOG(MCP_LOG_LEVEL_WARN, |
| 307 | std::string("setsockopt(TCP_KEEPINTVL) failed: ") + std::strerror(errno) + | 306 | std::string("setsockopt(TCP_KEEPINTVL) failed: ") + std::strerror(errno) + |
| @@ -309,8 +308,7 @@ void TcpSocket::SetTcpOptions(const TcpSocketOptions& opts) | |||
| 309 | } | 308 | } |
| 310 | } | 309 | } |
| 311 | if (opts.keepAliveCnt > 0) { | 310 | if (opts.keepAliveCnt > 0) { |
| 312 | - rc = ::setsockopt(fd_, IPPROTO_TCP, TCP_KEEPCNT, &opts.keepAliveCnt, | 311 | + rc = Platform::SetKeepAliveCnt(fd_, opts.keepAliveCnt); |
| 313 | - static_cast<socklen_t>(sizeof(opts.keepAliveCnt))); | ||
| 314 | if (rc != 0) { | 312 | if (rc != 0) { |
| 315 | MCP_LOG(MCP_LOG_LEVEL_WARN, | 313 | MCP_LOG(MCP_LOG_LEVEL_WARN, |
| 316 | std::string("setsockopt(TCP_KEEPCNT) failed: ") + std::strerror(errno) + | 314 | std::string("setsockopt(TCP_KEEPCNT) failed: ") + std::strerror(errno) + |
| @@ -309,7 +309,7 @@ void HttpServer::HandleNewConnection(const Mcp::Net::TcpSocketPtr& connection) | |||
| 309 | 309 | ||
| 310 | connection->OnClose([this](const Mcp::Net::SocketPtr& socket) { this->HandleClose(socket); }); | 310 | connection->OnClose([this](const Mcp::Net::SocketPtr& socket) { this->HandleClose(socket); }); |
| 311 | 311 | ||
| 312 | - connection->OnRead([this, fileDescriptor](const Mcp::Net::SocketPtr& socket) { | 312 | + connection->OnRead([this](const Mcp::Net::SocketPtr& socket) { |
| 313 | // Check if server is still running to avoid processing during shutdown | 313 | // Check if server is still running to avoid processing during shutdown |
| 314 | if (!running_.load()) { | 314 | if (!running_.load()) { |
| 315 | return; | 315 | return; |
| @@ -202,6 +202,7 @@ void ServerManager::Start() | |||
| 202 | } | 202 | } |
| 203 | 203 | ||
| 204 | threadQueueEventIds_[i] = eventId; | 204 | threadQueueEventIds_[i] = eventId; |
| 205 | + notifyArg->eventId = eventId; | ||
| 205 | eventSystems_.push_back(std::move(eventSystem)); | 206 | eventSystems_.push_back(std::move(eventSystem)); |
| 206 | threadQueues_.push_back(std::move(queue)); | 207 | threadQueues_.push_back(std::move(queue)); |
| 207 | } | 208 | } |
| @@ -506,7 +507,7 @@ void ServerManager::HandleQueueNotification(int fd, short events, void* arg) | |||
| 506 | // If we processed MAX_BATCH_SIZE messages and the queue is still not empty, | 507 | // If we processed MAX_BATCH_SIZE messages and the queue is still not empty, |
| 507 | // re-trigger the notification to continue processing in the next event loop iteration | 508 | // re-trigger the notification to continue processing in the next event loop iteration |
| 508 | if (processedCount >= MAX_BATCH_SIZE && !queue->Empty()) { | 509 | if (processedCount >= MAX_BATCH_SIZE && !queue->Empty()) { |
| 509 | - notifyEventArg->eventSystem->NotifyEventId(fd); | 510 | + notifyEventArg->eventSystem->NotifyEventId(notifyEventArg->eventId); |
| 510 | MCP_LOG(MCP_LOG_LEVEL_DEBUG, "Thread " + std::to_string(notifyEventArg->threadId) + | 511 | MCP_LOG(MCP_LOG_LEVEL_DEBUG, "Thread " + std::to_string(notifyEventArg->threadId) + |
| 511 | " re-triggered notification for remaining messages"); | 512 | " re-triggered notification for remaining messages"); |
| 512 | } | 513 | } |
| @@ -45,8 +45,9 @@ struct WorkerMessage { | |||
| 45 | }; | 45 | }; |
| 46 | 46 | ||
| 47 | struct NotifyEventArg { | 47 | struct NotifyEventArg { |
| 48 | - int threadId; | 48 | + int threadId{-1}; |
| 49 | - EventSystem* eventSystem; | 49 | + int eventId{-1}; |
| 50 | + EventSystem* eventSystem{nullptr}; | ||
| 50 | }; | 51 | }; |
| 51 | 52 | ||
| 52 | class ServerManager { | 53 | class ServerManager { |
| @@ -9,6 +9,7 @@ | |||
| 9 | #include <atomic> | 9 | #include <atomic> |
| 10 | #include <chrono> | 10 | #include <chrono> |
| 11 | #include <condition_variable> | 11 | #include <condition_variable> |
| 12 | +#include <limits> | ||
| 12 | #include <mutex> | 13 | #include <mutex> |
| 13 | #include <vector> | 14 | #include <vector> |
| 14 | #include <memory> | 15 | #include <memory> |
| @@ -247,6 +248,117 @@ TEST(EventSystemTest, EventFdCreateNotifyReadClose) | |||
| 247 | es.Stop(); | 248 | es.Stop(); |
| 248 | } | 249 | } |
| 249 | 250 | ||
| 251 | +TEST(EventSystemTest, NotifyEventIdCoalescesIntoOneWakeup) | ||
| 252 | +{ | ||
| 253 | + Mcp::EventSystem es(true); | ||
| 254 | + ASSERT_TRUE(es.Init()); | ||
| 255 | + | ||
| 256 | + constexpr uint64_t kNotifyCount = 10; | ||
| 257 | + std::mutex m; | ||
| 258 | + std::condition_variable cv; | ||
| 259 | + std::vector<uint64_t> values; | ||
| 260 | + std::atomic<int> calls{0}; | ||
| 261 | + | ||
| 262 | + auto cb = [&es, &m, &cv, &values, &calls](int fd, short, auto*) { | ||
| 263 | + uint64_t v = 0; | ||
| 264 | + while (es.ReadEventFd(fd, v)) { | ||
| 265 | + std::lock_guard<std::mutex> lk(m); | ||
| 266 | + values.push_back(v); | ||
| 267 | + } | ||
| 268 | + calls.fetch_add(1); | ||
| 269 | + cv.notify_all(); | ||
| 270 | + }; | ||
| 271 | + int notifyEventId = es.CreateNotifyEventId(cb, nullptr, true); | ||
| 272 | + ASSERT_GT(notifyEventId, 0); | ||
| 273 | + | ||
| 274 | + // Ten notifications must coalesce into one accumulated wakeup. | ||
| 275 | + for (uint64_t i = 0; i < kNotifyCount; ++i) { | ||
| 276 | + ASSERT_TRUE(es.NotifyEventId(notifyEventId, 1)); | ||
| 277 | + } | ||
| 278 | + es.Start(true); | ||
| 279 | + | ||
| 280 | + { | ||
| 281 | + std::unique_lock<std::mutex> lk(m); | ||
| 282 | + ASSERT_TRUE(cv.wait_for(lk, std::chrono::milliseconds(NOTIFY_WAIT_TIMEOUT_MS), | ||
| 283 | + [&calls]() { return calls.load() >= 1; })); | ||
| 284 | + } | ||
| 285 | + std::this_thread::sleep_for(std::chrono::milliseconds(NOTIFY_GAP_MS)); | ||
| 286 | + EXPECT_EQ(calls.load(), 1); | ||
| 287 | + { | ||
| 288 | + std::lock_guard<std::mutex> lk(m); | ||
| 289 | + ASSERT_EQ(values.size(), 1u); | ||
| 290 | + EXPECT_EQ(values[0], kNotifyCount); | ||
| 291 | + } | ||
| 292 | + | ||
| 293 | + EXPECT_TRUE(es.CloseNotifyEventId(notifyEventId)); | ||
| 294 | + es.Stop(); | ||
| 295 | +} | ||
| 296 | + | ||
| 297 | +TEST(EventSystemTest, NotifyEventIdZeroIncrementDoesNotWake) | ||
| 298 | +{ | ||
| 299 | + Mcp::EventSystem es(true); | ||
| 300 | + ASSERT_TRUE(es.Init()); | ||
| 301 | + | ||
| 302 | + std::atomic<int> calls{0}; | ||
| 303 | + int notifyEventId = es.CreateNotifyEventId( | ||
| 304 | + [&calls](int, short, auto*) { calls.fetch_add(1); }, nullptr, true); | ||
| 305 | + ASSERT_GT(notifyEventId, 0); | ||
| 306 | + | ||
| 307 | + // eventfd parity: succeeds without becoming readable. | ||
| 308 | + EXPECT_TRUE(es.NotifyEventId(notifyEventId, 0)); | ||
| 309 | + es.Start(true); | ||
| 310 | + std::this_thread::sleep_for(std::chrono::milliseconds(ONE_SHOT_GRACE_PERIOD_MS)); | ||
| 311 | + EXPECT_EQ(calls.load(), 0); | ||
| 312 | + | ||
| 313 | + EXPECT_TRUE(es.CloseNotifyEventId(notifyEventId)); | ||
| 314 | + es.Stop(); | ||
| 315 | +} | ||
| 316 | + | ||
| 317 | +TEST(EventSystemTest, NotifyEventIdMaxIncrementRejected) | ||
| 318 | +{ | ||
| 319 | + Mcp::EventSystem es(true); | ||
| 320 | + ASSERT_TRUE(es.Init()); | ||
| 321 | + | ||
| 322 | + std::mutex m; | ||
| 323 | + std::condition_variable cv; | ||
| 324 | + std::vector<uint64_t> values; | ||
| 325 | + std::atomic<int> calls{0}; | ||
| 326 | + | ||
| 327 | + auto cb = [&es, &m, &cv, &values, &calls](int fd, short, auto*) { | ||
| 328 | + uint64_t v = 0; | ||
| 329 | + while (es.ReadEventFd(fd, v)) { | ||
| 330 | + std::lock_guard<std::mutex> lk(m); | ||
| 331 | + values.push_back(v); | ||
| 332 | + } | ||
| 333 | + calls.fetch_add(1); | ||
| 334 | + cv.notify_all(); | ||
| 335 | + }; | ||
| 336 | + int notifyEventId = es.CreateNotifyEventId(cb, nullptr, true); | ||
| 337 | + ASSERT_GT(notifyEventId, 0); | ||
| 338 | + | ||
| 339 | + ASSERT_TRUE(es.NotifyEventId(notifyEventId, 1)); | ||
| 340 | + // eventfd rejects increments above 0xFFFFFFFFFFFFFFFE; the committed | ||
| 341 | + // count must remain untouched. | ||
| 342 | + EXPECT_FALSE(es.NotifyEventId(notifyEventId, std::numeric_limits<uint64_t>::max())); | ||
| 343 | + es.Start(true); | ||
| 344 | + | ||
| 345 | + { | ||
| 346 | + std::unique_lock<std::mutex> lk(m); | ||
| 347 | + ASSERT_TRUE(cv.wait_for(lk, std::chrono::milliseconds(NOTIFY_WAIT_TIMEOUT_MS), | ||
| 348 | + [&calls]() { return calls.load() >= 1; })); | ||
| 349 | + } | ||
| 350 | + std::this_thread::sleep_for(std::chrono::milliseconds(NOTIFY_GAP_MS)); | ||
| 351 | + EXPECT_EQ(calls.load(), 1); | ||
| 352 | + { | ||
| 353 | + std::lock_guard<std::mutex> lk(m); | ||
| 354 | + ASSERT_EQ(values.size(), 1u); | ||
| 355 | + EXPECT_EQ(values[0], 1u); | ||
| 356 | + } | ||
| 357 | + | ||
| 358 | + EXPECT_TRUE(es.CloseNotifyEventId(notifyEventId)); | ||
| 359 | + es.Stop(); | ||
| 360 | +} | ||
| 361 | + | ||
| 250 | TEST(EventSystemTest, NotifyAndCloseNotifyEventIdConcurrentStress) | 362 | TEST(EventSystemTest, NotifyAndCloseNotifyEventIdConcurrentStress) |
| 251 | { | 363 | { |
| 252 | Mcp::EventSystem es(true); | 364 | Mcp::EventSystem es(true); |
| @@ -444,7 +444,7 @@ TEST(TcpListenerTest, ListenInvalidHost) { | |||
| 444 | EXPECT_FALSE(listener.Listen("not-a-host", 0, 1, false)); | 444 | EXPECT_FALSE(listener.Listen("not-a-host", 0, 1, false)); |
| 445 | } | 445 | } |
| 446 | 446 | ||
| 447 | -TEST(TcpListenerTest, ListenPortConflictWithoutReuse) { | 447 | +TEST(TcpListenerTest, ListenPortConflictWithoutReusePort) { |
| 448 | Mcp::EventSystem es; | 448 | Mcp::EventSystem es; |
| 449 | ASSERT_TRUE(es.Init()); | 449 | ASSERT_TRUE(es.Init()); |
| 450 | 450 | ||
| @@ -462,7 +462,10 @@ TEST(TcpListenerTest, ListenPortConflictWithoutReuse) { | |||
| 462 | 462 | ||
| 463 | TcpListener listener(es); | 463 | TcpListener listener(es); |
| 464 | uint16_t boundPort = ntohs(addr.sin_port); | 464 | uint16_t boundPort = ntohs(addr.sin_port); |
| 465 | - EXPECT_FALSE(listener.Listen("", boundPort, 1, false)); | 465 | + // Pin the family to IPv4 so both sockets target the same address. A bare |
| 466 | + // Listen("") may return an IPv6 wildcard first, which can bind alongside the | ||
| 467 | + // reserved IPv4 wildcard on BSD/macOS and make the result platform-dependent. | ||
| 468 | + EXPECT_FALSE(listener.Listen("0.0.0.0", boundPort, 1, false)); | ||
| 466 | 469 | ||
| 467 | ::close(reserved); | 470 | ::close(reserved); |
| 468 | } | 471 | } |
| @@ -269,7 +269,7 @@ TEST_F(ResourceManagerTest, ListResources_ResourceInfoPreserved) | |||
| 269 | EXPECT_EQ(retrievedResource.icons->size(), 1); | 269 | EXPECT_EQ(retrievedResource.icons->size(), 1); |
| 270 | EXPECT_EQ(retrievedResource.icons->at(0).src, "icon.png"); | 270 | EXPECT_EQ(retrievedResource.icons->at(0).src, "icon.png"); |
| 271 | ASSERT_TRUE(retrievedResource.annotations.has_value()); | 271 | ASSERT_TRUE(retrievedResource.annotations.has_value()); |
| 272 | - EXPECT_EQ(retrievedResource.annotations->priority.value(), 1.0); | 272 | + EXPECT_DOUBLE_EQ(retrievedResource.annotations->priority.value(), 1.0); |
| 273 | } | 273 | } |
| 274 | 274 | ||
| 275 | // Test ReadResource | 275 | // Test ReadResource |
| @@ -530,7 +530,7 @@ TEST_F(ResourceManagerTest, ListResourceTemplates_TemplateInfoPreserved) | |||
| 530 | EXPECT_EQ(retrievedTemplate.icons->size(), 1); | 530 | EXPECT_EQ(retrievedTemplate.icons->size(), 1); |
| 531 | EXPECT_EQ(retrievedTemplate.icons->at(0).src, "template-icon.png"); | 531 | EXPECT_EQ(retrievedTemplate.icons->at(0).src, "template-icon.png"); |
| 532 | ASSERT_TRUE(retrievedTemplate.annotations.has_value()); | 532 | ASSERT_TRUE(retrievedTemplate.annotations.has_value()); |
| 533 | - EXPECT_EQ(retrievedTemplate.annotations->priority.value(), 1.0); | 533 | + EXPECT_DOUBLE_EQ(retrievedTemplate.annotations->priority.value(), 1.0); |
| 534 | } | 534 | } |
| 535 | 535 | ||
| 536 | // Test SubscribeResource | 536 | // Test SubscribeResource |


【review】脚本逻辑缺陷。macOS 的依赖检查分支(本块)只统计 need_curl 与 need_openssl 两个标志,安装分支也只 brew install 这两项;而同一脚本的校验阶段会检查 curl、openssl、libevent、nlohmann-json 四项。当 curl 与 openssl 已安装、仅缺 libevent 或 nlohmann-json 时,块后的 need_any 判定会认为「All dependencies are already installed」并提前 return,安装分支根本不执行;紧接着校验阶段报缺包并 exit 1。用户重跑脚本会得到完全相同的结果,形成无法自愈的循环,且报错指向「缺 libevent」而不是「检查逻辑漏项」,很难定位到根因。建议把检查项与校验项对齐:在 macOS 分支同样统计 libevent、nlohmann-json 并纳入提前返回判断;或直接去掉提前返回,让安装分支幂等地 brew install 全部所需包(brew 对已安装包是 no-op,重复执行无副作用)。