| @@ -5,6 +5,26 @@ set(CMAKE_CXX_STANDARD 17) | |||
| 5 | set(CMAKE_CXX_STANDARD_REQUIRED ON) | 5 | set(CMAKE_CXX_STANDARD_REQUIRED ON) |
| 6 | set(CMAKE_CXX_EXTENSIONS OFF) | 6 | set(CMAKE_CXX_EXTENSIONS OFF) |
| 7 | 7 | ||
| 8 | +# On macOS, Homebrew installs some dependencies (OpenSSL, curl, ...) as keg-only, | ||
| 9 | +# meaning they are not on the default search path. Prepend their prefixes so that | ||
| 10 | +# find_package/find_library can locate them without manual OPENSSL_ROOT_DIR. | ||
| 11 | +if(APPLE) | ||
| 12 | + find_program(A2A_BREW_EXECUTABLE brew) | ||
| 13 | + if(A2A_BREW_EXECUTABLE) | ||
| 14 | + foreach(_a2a_brew_pkg openssl@3 openssl curl libevent nlohmann-json) | ||
| 15 | + execute_process( | ||
| 16 | + COMMAND ${A2A_BREW_EXECUTABLE} --prefix ${_a2a_brew_pkg} | ||
| 17 | + OUTPUT_VARIABLE _a2a_brew_prefix | ||
| 18 | + OUTPUT_STRIP_TRAILING_WHITESPACE | ||
| 19 | + ERROR_QUIET) | ||
| 20 | + if(_a2a_brew_prefix AND EXISTS "${_a2a_brew_prefix}") | ||
| 21 | + list(APPEND CMAKE_PREFIX_PATH "${_a2a_brew_prefix}") | ||
| 22 | + endif() | ||
| 23 | + endforeach() | ||
| 24 | + list(REMOVE_DUPLICATES CMAKE_PREFIX_PATH) | ||
| 25 | + endif() | ||
| 26 | +endif() | ||
| 27 | + | ||
| 8 | option(A2A_BUILD_CLIENT "Build A2A client components" ON) | 28 | option(A2A_BUILD_CLIENT "Build A2A client components" ON) |
| 9 | option(A2A_BUILD_SERVER "Build A2A server components" ON) | 29 | option(A2A_BUILD_SERVER "Build A2A server components" ON) |
| 10 | option(A2A_ENABLE_EXAMPLES "Build example binaries" OFF) | 30 | option(A2A_ENABLE_EXAMPLES "Build example binaries" OFF) |
| @@ -32,13 +52,35 @@ endif() | |||
| 32 | 52 | ||
| 33 | find_package(OpenSSL REQUIRED) | 53 | find_package(OpenSSL REQUIRED) |
| 34 | find_package(CURL REQUIRED) | 54 | find_package(CURL REQUIRED) |
| 55 | +find_package(Threads REQUIRED) | ||
| 35 | 56 | ||
| 36 | -set(_a2a_link_libs pthread dl OpenSSL::SSL OpenSSL::Crypto http_parser) | 57 | +# pthread is provided by the system (Threads::Threads); dl exists only on Linux |
| 58 | +# and is exposed via CMAKE_DL_LIBS (empty on macOS). | ||
| 59 | +set(_a2a_link_libs Threads::Threads ${CMAKE_DL_LIBS} OpenSSL::SSL OpenSSL::Crypto http_parser) | ||
| 37 | 60 | ||
| 38 | if(TARGET event) | 61 | if(TARGET event) |
| 39 | list(APPEND _a2a_link_libs event) | 62 | list(APPEND _a2a_link_libs event) |
| 40 | elseif(TARGET libevent) | 63 | elseif(TARGET libevent) |
| 41 | list(APPEND _a2a_link_libs libevent) | 64 | list(APPEND _a2a_link_libs libevent) |
| 65 | +else() | ||
| 66 | + # Preferred: imported targets from find_package (Linux distros). Fallback: | ||
| 67 | + # locate the library by name (macOS/Homebrew ships libevent without a | ||
| 68 | + # CMake config; the brew prefixes were already added to CMAKE_PREFIX_PATH). | ||
| 69 | + find_library(_a2a_event_lib NAMES event libevent) | ||
| 70 | + if(NOT _a2a_event_lib) | ||
| 71 | + message(FATAL_ERROR | ||
| 72 | + "libevent not found. Install it first: 'brew install libevent' (macOS) " | ||
| 73 | + "or 'apt install libevent-dev' (Linux).") | ||
| 74 | + endif() | ||
| 75 | + list(APPEND _a2a_link_libs ${_a2a_event_lib}) | ||
| 76 | + # Keep headers and library from the same prefix so the fallback can never | ||
| 77 | + # pair a system libevent library with third-party headers. The include dir | ||
| 78 | + # is attached to the shared interface target because event_system.cpp is | ||
| 79 | + # compiled by object libraries (a2a_event/a2a_shared), not by `a2a` itself. | ||
| 80 | + get_filename_component(_a2a_event_lib_dir "${_a2a_event_lib}" DIRECTORY) | ||
| 81 | + if(EXISTS "${_a2a_event_lib_dir}/../include") | ||
| 82 | + target_include_directories(third_party_headers INTERFACE "${_a2a_event_lib_dir}/../include") | ||
| 83 | + endif() | ||
| 42 | endif() | 84 | endif() |
| 43 | 85 | ||
| 44 | if(TARGET event_pthreads) | 86 | if(TARGET event_pthreads) |
| @@ -32,7 +32,7 @@ A2A C++ SDK 是 [Agent-to-Agent 协议 v1.0](https://a2a-protocol.org/v1.0.0/spe | |||
| 32 | 32 | ||
| 33 | ## 环境要求 | 33 | ## 环境要求 |
| 34 | 34 | ||
| 35 | -- **操作系统**:Linux(glibc 或 musl,主要验证平台) | 35 | +- **操作系统**:Linux(glibc 或 musl,主要验证平台)、macOS |
| 36 | - **编译器**:C++17 及以上(GCC 9+ / Clang 10+) | 36 | - **编译器**:C++17 及以上(GCC 9+ / Clang 10+) |
| 37 | - **CMake**:≥ 3.15(见根目录 `CMakeLists.txt`) | 37 | - **CMake**:≥ 3.15(见根目录 `CMakeLists.txt`) |
| 38 | - **依赖**:见 [docs/dependencies.md](docs/dependencies.md) | 38 | - **依赖**:见 [docs/dependencies.md](docs/dependencies.md) |
| @@ -30,6 +30,7 @@ | |||
| 30 | | nlohmann_json | 3.11.2 | JSON 序列化 | | 30 | | nlohmann_json | 3.11.2 | JSON 序列化 | |
| 31 | | libevent | 2.1.12 | 事件循环(Server I/O) | | 31 | | libevent | 2.1.12 | 事件循环(Server I/O) | |
| 32 | | http_parser | 2.9.4 | HTTP 解析 | | 32 | | http_parser | 2.9.4 | HTTP 解析 | |
| 33 | +| GNU coreutils | — | 仅 macOS:`run_example.sh` 超时保护(提供 `gtimeout`;Linux 自带 `timeout`) | | ||
| 33 | 34 | ||
| 34 | ## 系统包安装 | 35 | ## 系统包安装 |
| 35 | 36 | ||
| @@ -70,6 +71,23 @@ sudo yum install -y \ | |||
| 70 | sudo pacman -S --needed base-devel cmake openssl curl libevent nlohmann-json | 71 | sudo pacman -S --needed base-devel cmake openssl curl libevent nlohmann-json |
| 71 | ``` | 72 | ``` |
| 72 | 73 | ||
| 74 | +### macOS(Homebrew) | ||
| 75 | + | ||
| 76 | +```bash | ||
| 77 | +brew install cmake pkgconf openssl@3 curl libevent nlohmann-json coreutils | ||
| 78 | +``` | ||
| 79 | + | ||
| 80 | +macOS 上 OpenSSL/curl 为 keg-only,CMake 会自动从 Homebrew 前缀查找它们;也可用 | ||
| 81 | +`bash scripts/install_deps.sh` 自动安装。 | ||
| 82 | + | ||
| 83 | +macOS 没有 GNU `timeout`,`scripts/run_example.sh` 的冒烟测试依赖 coreutils 提供的 | ||
| 84 | +`gtimeout` 做超时保护(找不到时会直接报错退出,不会静默取消超时)。 | ||
| 85 | + | ||
| 86 | +> **conda/Anaconda 环境注意**:若当前 shell 激活了 conda(`CONDA_PREFIX` 非空),其自带的 | ||
| 87 | +> OpenSSL/curl/libevent/nlohmann_json/GTest 等可能被 CMake 抢先选中,导致链接错误或 | ||
| 88 | +> undefined symbols。构建前请 `conda deactivate`(含 base),并删除 `build/` 后重新配置 | ||
| 89 | +> (CMake 会把已找到的路径缓存进 `build/CMakeCache.txt`,不删缓存不生效)。 | ||
| 90 | + | ||
| 73 | ## 验证依赖 | 91 | ## 验证依赖 |
| 74 | 92 | ||
| 75 | ```bash | 93 | ```bash |
| @@ -81,6 +99,9 @@ curl-config --version | |||
| 81 | 99 | ||
| 82 | # CMake | 100 | # CMake |
| 83 | cmake --version | 101 | cmake --version |
| 102 | + | ||
| 103 | +# GNU timeout(macOS 为 gtimeout,来自 coreutils) | ||
| 104 | +timeout --version 2>/dev/null || gtimeout --version | ||
| 84 | ``` | 105 | ``` |
| 85 | 106 | ||
| 86 | ## 说明 | 107 | ## 说明 |
| @@ -48,7 +48,7 @@ A2A_LOG(A2A::Log::A2A_LOG_LEVEL::INFO, | |||
| 48 | [YYYY-MM-DD HH:MM:SS.mmm] [tid] [LEVEL] file.cpp::Function:[line] message | 48 | [YYYY-MM-DD HH:MM:SS.mmm] [tid] [LEVEL] file.cpp::Function:[line] message |
| 49 | ``` | 49 | ``` |
| 50 | 50 | ||
| 51 | -其中 `LEVEL` 为 `DEBUG` / `INFO` / `WARN` / `ERROR` / `FATAL` 之一;`tid` 为 Linux 线程 ID(`syscall(SYS_gettid)`)。级别名由 SDK 自动写入;`A2aLogCallback` 的第一个参数仍为枚举值 `A2A_LOG_LEVEL`。 | 51 | +其中 `LEVEL` 为 `DEBUG` / `INFO` / `WARN` / `ERROR` / `FATAL` 之一;`tid` 为当前线程的内核级 ID(Linux 为 `gettid`,macOS 为 `pthread_threadid_np`)。级别名由 SDK 自动写入;`A2aLogCallback` 的第一个参数仍为枚举值 `A2A_LOG_LEVEL`。 |
| 52 | 52 | ||
| 53 | ### 默认输出:stdout | 53 | ### 默认输出:stdout |
| 54 | 54 | ||
| @@ -7,11 +7,12 @@ | |||
| 7 | 7 | ||
| 8 | #include <stdint.h> | 8 | #include <stdint.h> |
| 9 | #include <string.h> | 9 | #include <string.h> |
| 10 | -#include <sys/syscall.h> | ||
| 11 | #include <sys/types.h> | 10 | #include <sys/types.h> |
| 12 | #include <time.h> | 11 | #include <time.h> |
| 13 | #include <unistd.h> | 12 | #include <unistd.h> |
| 14 | 13 | ||
| 14 | +#include "platform_compat.h" | ||
| 15 | + | ||
| 15 | #include <iomanip> | 16 | #include <iomanip> |
| 16 | #include <sstream> | 17 | #include <sstream> |
| 17 | #include <string> | 18 | #include <string> |
| @@ -102,6 +103,15 @@ static inline void GetCurrentTimeStamp(std::string& timestamp) | |||
| 102 | timestamp = oss.str(); | 103 | timestamp = oss.str(); |
| 103 | } | 104 | } |
| 104 | 105 | ||
| 106 | +/** | ||
| 107 | + * @brief Get the current OS thread id in a platform-portable way. | ||
| 108 | + * @return A numeric thread id used for log correlation. | ||
| 109 | + */ | ||
| 110 | +static inline long long GetCurrentThreadId() | ||
| 111 | +{ | ||
| 112 | + return static_cast<long long>(Platform::GetThreadId()); | ||
| 113 | +} | ||
| 114 | + | ||
| 105 | // Internal helper to reduce macro lines and handle C++ string formatting. | 115 | // Internal helper to reduce macro lines and handle C++ string formatting. |
| 106 | template<typename... Args> | 116 | template<typename... Args> |
| 107 | inline void LogInternal(A2A_LOG_LEVEL level, const char* file, const char* func, int line, | 117 | inline void LogInternal(A2A_LOG_LEVEL level, const char* file, const char* func, int line, |
| @@ -119,7 +129,7 @@ inline void LogInternal(A2A_LOG_LEVEL level, const char* file, const char* func, | |||
| 119 | const char* filename = strrchr(file, '/'); | 129 | const char* filename = strrchr(file, '/'); |
| 120 | filename = filename ? filename + 1 : file; | 130 | filename = filename ? filename + 1 : file; |
| 121 | 131 | ||
| 122 | - std::string prefix = "[" + timestamp + "] [" + std::to_string(syscall(SYS_gettid)) + "] [" + | 132 | + std::string prefix = "[" + timestamp + "] [" + std::to_string(GetCurrentThreadId()) + "] [" + |
| 123 | std::string(GetLogLevelName(level)) + "] " + std::string(filename) + "::" + | 133 | std::string(GetLogLevelName(level)) + "] " + std::string(filename) + "::" + |
| 124 | std::string(func) + ":[" + std::to_string(line) + "] "; | 134 | std::string(func) + ":[" + std::to_string(line) + "] "; |
| 125 | 135 | ||
| @@ -0,0 +1,389 @@ | |||
| 1 | +/* | ||
| 2 | + * Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. | ||
| 3 | + */ | ||
| 4 | +#ifndef A2A_PLATFORM_COMPAT_H | ||
| 5 | +#define A2A_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 A2A::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 | + // Channel not attached yet (or already closed): fail without side effects. | ||
| 241 | + if (ch.writeFd < 0) { | ||
| 242 | + return false; | ||
| 243 | + } | ||
| 244 | + | ||
| 245 | + // eventfd parity: a zero increment is a successful no-op. | ||
| 246 | + if (value == 0) { | ||
| 247 | + return true; | ||
| 248 | + } | ||
| 249 | + | ||
| 250 | + // Same counter bound as eventfd; reject invalid increments before the | ||
| 251 | + // subtraction below can underflow. | ||
| 252 | + constexpr uint64_t MAX_COUNTER = UINT64_MAX - 1; | ||
| 253 | + if (value > MAX_COUNTER) { | ||
| 254 | + return false; | ||
| 255 | + } | ||
| 256 | + | ||
| 257 | + uint64_t current = ch.counter.load(std::memory_order_relaxed); | ||
| 258 | + while (current <= MAX_COUNTER - value) { | ||
| 259 | + if (ch.counter.compare_exchange_weak( | ||
| 260 | + current, current + value, | ||
| 261 | + std::memory_order_acq_rel, std::memory_order_relaxed)) { | ||
| 262 | + break; | ||
| 263 | + } | ||
| 264 | + } | ||
| 265 | + if (current > MAX_COUNTER - value) { | ||
| 266 | + return false; | ||
| 267 | + } | ||
| 268 | + if (current > 0) { | ||
| 269 | + // Coalesce into the pending wake record. | ||
| 270 | + return true; | ||
| 271 | + } | ||
| 272 | + | ||
| 273 | + // Only the empty->non-empty edge writes a wake byte. A write racing with a | ||
| 274 | + // drain can leave an extra pending byte, so the reader keeps draining until | ||
| 275 | + // EAGAIN instead of assuming a fixed byte count. | ||
| 276 | + const uint8_t wakeByte = 1; | ||
| 277 | + while (true) { | ||
| 278 | + const ssize_t written = ::write(ch.writeFd, &wakeByte, sizeof(wakeByte)); | ||
| 279 | + if (written == static_cast<ssize_t>(sizeof(wakeByte))) { | ||
| 280 | + return true; | ||
| 281 | + } | ||
| 282 | + if (written < 0) { | ||
| 283 | + if (errno == EINTR) { | ||
| 284 | + continue; | ||
| 285 | + } | ||
| 286 | + if (errno == EAGAIN || errno == EWOULDBLOCK) { | ||
| 287 | + // Count committed and a wake record is pending: deliverable. | ||
| 288 | + return true; | ||
| 289 | + } | ||
| 290 | + // Undeliverable: roll back the committed increment. | ||
| 291 | + ch.counter.fetch_sub(value, std::memory_order_acq_rel); | ||
| 292 | + return false; | ||
| 293 | + } | ||
| 294 | + ch.counter.fetch_sub(value, std::memory_order_acq_rel); | ||
| 295 | + return false; | ||
| 296 | + } | ||
| 297 | +#endif | ||
| 298 | +} | ||
| 299 | + | ||
| 300 | +/** | ||
| 301 | + * @brief Read the accumulated counter value from the channel and reset it. | ||
| 302 | + * Linux reads the eventfd; pipe reads drain the wake records and then | ||
| 303 | + * return the software counter. | ||
| 304 | + * @return true and @p outValue set on success; false when empty / on error. | ||
| 305 | + */ | ||
| 306 | +inline bool NotifyChannelRead(NotifyChannel& ch, int readFd, uint64_t& outValue) | ||
| 307 | +{ | ||
| 308 | +#if defined(__linux__) | ||
| 309 | + uint64_t val = 0; | ||
| 310 | + while (true) { | ||
| 311 | + const ssize_t rd = ::read(readFd, &val, sizeof(val)); | ||
| 312 | + if (rd == static_cast<ssize_t>(sizeof(val))) { | ||
| 313 | + outValue = val; | ||
| 314 | + return true; | ||
| 315 | + } | ||
| 316 | + if (rd < 0) { | ||
| 317 | + if (errno == EINTR) { | ||
| 318 | + continue; | ||
| 319 | + } | ||
| 320 | + return false; | ||
| 321 | + } | ||
| 322 | + return false; | ||
| 323 | + } | ||
| 324 | +#else | ||
| 325 | + // Drain until EAGAIN: a producer's wake write may race with this drain and | ||
| 326 | + // leave more than one byte pending, so do not replace the loop with a | ||
| 327 | + // fixed read count. | ||
| 328 | + uint8_t buffer[NOTIFY_DRAIN_BUF_SIZE]; | ||
| 329 | + while (true) { | ||
| 330 | + const ssize_t rd = ::read(readFd, buffer, sizeof(buffer)); | ||
| 331 | + if (rd > 0) { | ||
| 332 | + continue; | ||
| 333 | + } | ||
| 334 | + if (rd < 0) { | ||
| 335 | + if (errno == EINTR) { | ||
| 336 | + continue; | ||
| 337 | + } | ||
| 338 | + if (errno == EAGAIN || errno == EWOULDBLOCK) { | ||
| 339 | + break; | ||
| 340 | + } | ||
| 341 | + return false; | ||
| 342 | + } | ||
| 343 | + break; | ||
| 344 | + } | ||
| 345 | + | ||
| 346 | + const uint64_t count = ch.counter.exchange(0, std::memory_order_acq_rel); | ||
| 347 | + if (count == 0) { | ||
| 348 | + errno = EAGAIN; | ||
| 349 | + return false; | ||
| 350 | + } | ||
【review】性能问题。macOS 管道路径 NotifyChannelRead 的 drain 循环一直读直到 EAGAIN 才退出,而它整体在 EventSystem::ReadEventFd 的全局互斥锁内执行(事件回调中常见 while(ReadEventFd(fd,value)) 循环,如 libcurl_conn.cpp)。通知持续到达时,事件线程会长时间卡在 drain 循环并持有全局锁,阻塞其它线程的 NotifyEventId/AddEvent/RemoveEvent 与回调,造成事件循环饥饿。建议对单次 NotifyChannelRead 的 drain 次数设上限(如最多读 2-4 次即返回),计数交换能保证语义正确,多余唤醒留到下一轮回调;并考虑事件线程路径避免持锁读 fd。 ![]() ![]() | |||
| 351 | + | ||
| 352 | + outValue = count; | ||
| 353 | + return true; | ||
| 354 | +#endif | ||
| 355 | +} | ||
| 356 | + | ||
| 357 | +/** | ||
| 358 | + * @brief Fallback raw read for fds without a registered notify channel. | ||
| 359 | + * Linux keeps the legacy 8-byte read semantics; other platforms do not | ||
| 360 | + * support it (always false), matching previous behavior. | ||
| 361 | + * @return true and @p outValue set on success; false otherwise. | ||
| 362 | + */ | ||
| 363 | +inline bool ReadChannelFdRaw(int fd, uint64_t& outValue) | ||
| 364 | +{ | ||
| 365 | +#if defined(__linux__) | ||
| 366 | + uint64_t val = 0; | ||
| 367 | + while (true) { | ||
| 368 | + const ssize_t rd = ::read(fd, &val, sizeof(val)); | ||
| 369 | + if (rd == static_cast<ssize_t>(sizeof(val))) { | ||
| 370 | + outValue = val; | ||
| 371 | + return true; | ||
| 372 | + } | ||
| 373 | + if (rd < 0) { | ||
| 374 | + if (errno == EINTR) { | ||
| 375 | + continue; | ||
| 376 | + } | ||
| 377 | + return false; | ||
| 378 | + } | ||
| 379 | + return false; | ||
| 380 | + } | ||
| 381 | +#else | ||
| 382 | + (void)fd; | ||
| 383 | + (void)outValue; | ||
| 384 | + return false; | ||
| 385 | +#endif | ||
| 386 | +} | ||
| 387 | + | ||
| 388 | +} // namespace A2A::Platform | ||
| 389 | +#endif | ||
| @@ -10,14 +10,18 @@ set -euo pipefail | |||
| 10 | 10 | ||
| 11 | echo "==> Checking system dependencies for yellow_a2a..." | 11 | echo "==> Checking system dependencies for yellow_a2a..." |
| 12 | 12 | ||
| 13 | -if [[ ! -f /etc/os-release ]]; then | 13 | +if [[ "$(uname -s)" == "Darwin" ]]; then |
| 14 | - echo "Error: Linux with /etc/os-release is required" >&2 | 14 | + OS="macos" |
| 15 | + OS_VERSION="$(sw_vers -productVersion 2>/dev/null || echo unknown)" | ||
| 16 | +elif [[ -f /etc/os-release ]]; then | ||
| 17 | + # shellcheck disable=SC1091 | ||
| 18 | + . /etc/os-release | ||
| 19 | + OS="${ID:-}" | ||
| 20 | + OS_VERSION="${VERSION_ID:-}" | ||
| 21 | +else | ||
| 22 | + echo "Error: unsupported platform (need macOS or Linux with /etc/os-release)" >&2 | ||
| 15 | exit 1 | 23 | exit 1 |
| 16 | fi | 24 | fi |
| 17 | -# shellcheck disable=SC1091 | ||
| 18 | -. /etc/os-release | ||
| 19 | -OS="${ID:-}" | ||
| 20 | -OS_VERSION="${VERSION_ID:-}" | ||
| 21 | 25 | ||
| 22 | if [[ "${EUID}" -ne 0 ]]; then | 26 | if [[ "${EUID}" -ne 0 ]]; then |
| 23 | echo "Warning: Not running as root. Package install may require sudo." | 27 | echo "Warning: Not running as root. Package install may require sudo." |
| @@ -62,6 +66,7 @@ install_dependencies() { | |||
| 62 | local need_libevent=0 | 66 | local need_libevent=0 |
| 63 | local need_json=0 | 67 | local need_json=0 |
| 64 | local need_http_parser=0 | 68 | local need_http_parser=0 |
| 69 | + local need_coreutils=0 | ||
| 65 | 70 | ||
| 66 | echo "Detected OS: ${OS} ${OS_VERSION}" | 71 | echo "Detected OS: ${OS} ${OS_VERSION}" |
| 67 | 72 | ||
| @@ -184,6 +189,50 @@ install_dependencies() { | |||
| 184 | need_build_tools=1 | 189 | need_build_tools=1 |
| 185 | fi | 190 | fi |
| 186 | ;; | 191 | ;; |
| 192 | + macos) | ||
| 193 | + if ! command_exists brew; then | ||
| 194 | + echo " - Homebrew: NOT FOUND (see https://brew.sh)" | ||
| 195 | + need_build_tools=1 | ||
| 196 | + fi | ||
| 197 | + command_exists cmake || { echo " - cmake: NOT FOUND"; need_build_tools=1; } | ||
| 198 | + if ! command_exists pkg-config && ! command_exists pkgconf; then | ||
| 199 | + echo " - pkg-config: NOT FOUND" | ||
| 200 | + need_build_tools=1 | ||
| 201 | + fi | ||
| 202 | + if brew list --versions openssl@3 >/dev/null 2>&1 || brew list --versions openssl >/dev/null 2>&1; then | ||
| 203 | + echo " - openssl: OK" | ||
| 204 | + else | ||
| 205 | + echo " - openssl: NOT FOUND" | ||
| 206 | + need_openssl=1 | ||
| 207 | + fi | ||
| 208 | + if brew list --versions curl >/dev/null 2>&1; then | ||
| 209 | + echo " - curl: OK" | ||
| 210 | + else | ||
| 211 | + echo " - curl: NOT FOUND" | ||
| 212 | + need_curl=1 | ||
| 213 | + fi | ||
| 214 | + if brew list --versions libevent >/dev/null 2>&1; then | ||
| 215 | + echo " - libevent: OK" | ||
| 216 | + else | ||
| 217 | + echo " - libevent: NOT FOUND" | ||
| 218 | + need_libevent=1 | ||
| 219 | + fi | ||
| 220 | + if brew list --versions nlohmann-json >/dev/null 2>&1; then | ||
| 221 | + echo " - nlohmann_json: OK" | ||
| 222 | + else | ||
| 223 | + echo " - nlohmann_json: NOT FOUND" | ||
| 224 | + need_json=1 | ||
| 225 | + fi | ||
| 226 | + # GNU timeout is required by scripts/run_example.sh; on macOS it is | ||
| 227 | + # provided by Homebrew coreutils as gtimeout. | ||
| 228 | + if command_exists gtimeout; then | ||
| 229 | + echo " - coreutils (gtimeout): OK" | ||
| 230 | + else | ||
| 231 | + echo " - coreutils (gtimeout): NOT FOUND" | ||
| 232 | + need_coreutils=1 | ||
| 233 | + fi | ||
| 234 | + # http_parser is fetched from source by CMake; no brew package needed. | ||
| 235 | + ;; | ||
| 187 | *) | 236 | *) |
| 188 | if command_exists curl-config; then | 237 | if command_exists curl-config; then |
| 189 | echo " - libcurl: OK" | 238 | echo " - libcurl: OK" |
| @@ -201,7 +250,7 @@ install_dependencies() { | |||
| 201 | ;; | 250 | ;; |
| 202 | esac | 251 | esac |
| 203 | 252 | ||
| 204 | - local need_any=$((need_build_tools + need_curl + need_openssl + need_libevent + need_json + need_http_parser)) | 253 | + local need_any=$((need_build_tools + need_curl + need_openssl + need_libevent + need_json + need_http_parser + need_coreutils)) |
| 205 | if [[ ${need_any} -eq 0 ]]; then | 254 | if [[ ${need_any} -eq 0 ]]; then |
| 206 | echo "==> All tracked dependencies are already installed!" | 255 | echo "==> All tracked dependencies are already installed!" |
| 207 | return 0 | 256 | return 0 |
| @@ -259,6 +308,23 @@ install_dependencies() { | |||
| 259 | echo "Installing: ${pkgs[*]}" | 308 | echo "Installing: ${pkgs[*]}" |
| 260 | ${SUDO} pacman -S --noconfirm "${pkgs[@]}" | 309 | ${SUDO} pacman -S --noconfirm "${pkgs[@]}" |
| 261 | ;; | 310 | ;; |
| 311 | + macos) | ||
| 312 | + if ! command_exists brew; then | ||
| 313 | + echo "Error: Homebrew is required on macOS (see https://brew.sh)" >&2 | ||
| 314 | + exit 1 | ||
| 315 | + fi | ||
| 316 | + local pkgs=() | ||
| 317 | + [[ ${need_build_tools} -eq 1 ]] && pkgs+=(cmake pkgconf) | ||
| 318 | + [[ ${need_coreutils} -eq 1 ]] && pkgs+=(coreutils) | ||
| 319 | + [[ ${need_curl} -eq 1 ]] && pkgs+=(curl) | ||
| 320 | + [[ ${need_openssl} -eq 1 ]] && pkgs+=(openssl@3) | ||
| 321 | + [[ ${need_libevent} -eq 1 ]] && pkgs+=(libevent) | ||
| 322 | + [[ ${need_json} -eq 1 ]] && pkgs+=(nlohmann-json) | ||
| 323 | + if [[ ${#pkgs[@]} -gt 0 ]]; then | ||
| 324 | + echo "Installing (Homebrew): ${pkgs[*]}" | ||
| 325 | + brew install "${pkgs[@]}" | ||
| 326 | + fi | ||
| 327 | + ;; | ||
| 262 | *) | 328 | *) |
| 263 | echo "Error: Unsupported OS for automatic install: ${OS}" >&2 | 329 | echo "Error: Unsupported OS for automatic install: ${OS}" >&2 |
| 264 | echo "Please install manually: cmake, g++, pkg-config, libcurl-devel, openssl-devel," >&2 | 330 | echo "Please install manually: cmake, g++, pkg-config, libcurl-devel, openssl-devel," >&2 |
| @@ -276,6 +342,58 @@ check_dependencies() { | |||
| 276 | echo "==> Verifying installation..." | 342 | echo "==> Verifying installation..." |
| 277 | local ok=1 | 343 | local ok=1 |
| 278 | 344 | ||
| 345 | + if [[ "${OS}" == "macos" ]]; then | ||
| 346 | + command_exists cmake || { echo "✗ cmake is missing" >&2; ok=0; } | ||
| 347 | + if ! command_exists clang++ && ! command_exists g++; then | ||
| 348 | + echo "✗ C++ compiler (clang++) is missing" >&2 | ||
| 349 | + ok=0 | ||
| 350 | + fi | ||
| 351 | + if command_exists brew; then | ||
| 352 | + echo "✓ Homebrew found" | ||
| 353 | + else | ||
| 354 | + echo "✗ Homebrew is missing" >&2 | ||
| 355 | + ok=0 | ||
| 356 | + fi | ||
| 357 | + # Same package checks as the install step below, so a partially failed | ||
| 358 | + # install is reported here instead of failing later at CMake configure. | ||
| 359 | + if brew list --versions openssl@3 >/dev/null 2>&1 || brew list --versions openssl >/dev/null 2>&1; then | ||
| 360 | + echo " - openssl: OK" | ||
| 361 | + else | ||
| 362 | + echo "✗ openssl is missing (brew install openssl@3)" >&2 | ||
| 363 | + ok=0 | ||
| 364 | + fi | ||
| 365 | + if brew list --versions curl >/dev/null 2>&1; then | ||
| 366 | + echo " - curl: OK" | ||
| 367 | + else | ||
| 368 | + echo "✗ curl is missing (brew install curl)" >&2 | ||
| 369 | + ok=0 | ||
| 370 | + fi | ||
| 371 | + if brew list --versions libevent >/dev/null 2>&1; then | ||
| 372 | + echo " - libevent: OK" | ||
| 373 | + else | ||
| 374 | + echo "✗ libevent is missing (brew install libevent)" >&2 | ||
| 375 | + ok=0 | ||
| 376 | + fi | ||
| 377 | + if brew list --versions nlohmann-json >/dev/null 2>&1; then | ||
| 378 | + echo " - nlohmann_json: OK" | ||
| 379 | + else | ||
| 380 | + echo "✗ nlohmann_json is missing (brew install nlohmann-json)" >&2 | ||
| 381 | + ok=0 | ||
| 382 | + fi | ||
| 383 | + if command_exists gtimeout; then | ||
| 384 | + echo " - coreutils (gtimeout): OK" | ||
| 385 | + else | ||
| 386 | + echo "✗ coreutils is missing (brew install coreutils)" >&2 | ||
| 387 | + ok=0 | ||
| 388 | + fi | ||
| 389 | + if [[ ${ok} -eq 1 ]]; then | ||
| 390 | + echo "✓ Core dependencies verified. You can run: bash ./scripts/build.sh -e" | ||
【review】脚本逻辑缺陷。macOS 分支的 check_dependencies 只验证 cmake、编译器和 brew 是否存在,完全没有校验 openssl/curl/libevent/nlohmann-json,随后直接打印「Core dependencies verified」并 return 0。而同一脚本的 install_dependencies 在 macOS 上是用 brew list --versions 逐个检查这些包的,两边判定口径不一致:当 brew install 部分失败(例如 openssl@3 未装成功)时,check_dependencies 仍报成功,用户会在后续 CMake 配置阶段才遇到报错,且错误信息指向依赖缺失而非安装脚本。建议 macOS 分支补齐与 install_dependencies 相同的 brew list 校验项,任一项缺失即 ok=0 并以非零退出;只有全部通过才打印已验证成功的提示,让安装阶段就能暴露问题。 ![]() ![]() | |||
| 391 | + return 0 | ||
| 392 | + fi | ||
| 393 | + echo "✗ Some required dependencies are still missing." >&2 | ||
| 394 | + exit 1 | ||
| 395 | + fi | ||
| 396 | + | ||
| 279 | if ! command_exists cmake; then | 397 | if ! command_exists cmake; then |
| 280 | echo "✗ cmake is missing" >&2 | 398 | echo "✗ cmake is missing" >&2 |
| 281 | ok=0 | 399 | ok=0 |
| @@ -17,7 +17,31 @@ OUTPUT_DIR="${A2A_OUTPUT_DIR:-${ROOT}/output}" | |||
| 17 | EXAMPLE_BIN="${OUTPUT_DIR}/bin" | 17 | EXAMPLE_BIN="${OUTPUT_DIR}/bin" |
| 18 | LIB_DIR="${OUTPUT_DIR}/lib" | 18 | LIB_DIR="${OUTPUT_DIR}/lib" |
| 19 | 19 | ||
| 20 | -export LD_LIBRARY_PATH="${LIB_DIR}:${LD_LIBRARY_PATH:-}" | 20 | +if [[ "$(uname -s)" == "Darwin" ]]; then |
| 21 | + export DYLD_LIBRARY_PATH="${LIB_DIR}:${DYLD_LIBRARY_PATH:-}" | ||
| 22 | +else | ||
| 23 | + export LD_LIBRARY_PATH="${LIB_DIR}:${LD_LIBRARY_PATH:-}" | ||
| 24 | +fi | ||
| 25 | + | ||
| 26 | +# The smoke test must never run without a timeout wrapper: a hung example | ||
| 27 | +# client would otherwise block the script forever instead of failing. GNU | ||
| 28 | +# `timeout` ships with coreutils and is always available on Linux; on macOS it | ||
| 29 | +# comes from Homebrew coreutils as `gtimeout`. | ||
| 30 | +if command -v timeout >/dev/null 2>&1; then | ||
| 31 | + TIMEOUT_BIN="timeout" | ||
| 32 | +elif command -v gtimeout >/dev/null 2>&1; then | ||
| 33 | + TIMEOUT_BIN="gtimeout" | ||
| 34 | +else | ||
| 35 | + echo "Error: no timeout tool found (neither 'timeout' nor 'gtimeout')." >&2 | ||
| 36 | + echo " macOS: brew install coreutils (provides gtimeout)" >&2 | ||
| 37 | + echo " Linux: install the coreutils package" >&2 | ||
| 38 | + exit 1 | ||
| 39 | +fi | ||
| 40 | + | ||
| 41 | +run_with_timeout() { | ||
| 42 | + local secs="$1"; shift | ||
| 43 | + "${TIMEOUT_BIN}" "${secs}" "$@" | ||
| 44 | +} | ||
【review】脚本健壮性。macOS 默认没有 GNU timeout,若也未安装 coreutils 的 gtimeout,TIMEOUT_BIN 为空,run_with_timeout 静默退化为无超时直接执行,示例客户端假死时冒烟脚本会无限挂起而非失败,问题被掩盖。建议找不到 timeout/gtimeout 时报错并要求安装 coreutils,或用后台进程加 kill 机制兜底实现超时,保证任何平台都不丢失超时保护。 ![]() ![]() | |||
| 21 | 45 | ||
| 22 | PORT="${A2A_EXAMPLE_PORT:-8888}" | 46 | PORT="${A2A_EXAMPLE_PORT:-8888}" |
| 23 | JSONRPC_BASE="http://127.0.0.1:${PORT}/jsonrpc" | 47 | JSONRPC_BASE="http://127.0.0.1:${PORT}/jsonrpc" |
| @@ -95,10 +119,26 @@ expect_agent_card_http() { | |||
| 95 | fi | 119 | fi |
| 96 | } | 120 | } |
| 97 | 121 | ||
| 122 | +wait_for_example_ready() { | ||
| 123 | + local label="$1" | ||
| 124 | + local server_name="$2" | ||
| 125 | + local attempts=50 | ||
| 126 | + while (( attempts > 0 )); do | ||
| 127 | + if curl -sS -o /dev/null --max-time 1 "${CARD_URL}" 2>/dev/null; then | ||
| 128 | + return 0 | ||
| 129 | + fi | ||
| 130 | + sleep 0.1 | ||
| 131 | + attempts=$((attempts - 1)) | ||
| 132 | + done | ||
| 133 | + clear_example_process "${server_name}" | ||
| 134 | + echo "${label} server did not become ready" >&2 | ||
| 135 | + exit 1 | ||
| 136 | +} | ||
| 137 | + | ||
| 98 | run_helloworld_example() { | 138 | run_helloworld_example() { |
| 99 | clear_example_process "helloworld_server" | 139 | clear_example_process "helloworld_server" |
| 100 | "${EXAMPLE_BIN}/helloworld_server" -i 127.0.0.1 -p "${PORT}" & | 140 | "${EXAMPLE_BIN}/helloworld_server" -i 127.0.0.1 -p "${PORT}" & |
| 101 | - sleep 1 | 141 | + wait_for_example_ready "helloworld" "helloworld_server" |
| 102 | 142 | ||
| 103 | expect_agent_card_http "helloworld agent card (HTTP)" | 143 | expect_agent_card_http "helloworld agent card (HTTP)" |
| 104 | jsonrpc_expect_result \ | 144 | jsonrpc_expect_result \ |
| @@ -110,7 +150,7 @@ run_helloworld_example() { | |||
| 110 | jsonrpc_expect_result "${hello_send_msg}" "helloworld SendMessage" | 150 | jsonrpc_expect_result "${hello_send_msg}" "helloworld SendMessage" |
| 111 | 151 | ||
| 112 | echo "Running helloworld_client against 127.0.0.1:${PORT}..." | 152 | echo "Running helloworld_client against 127.0.0.1:${PORT}..." |
| 113 | - timeout 30 "${EXAMPLE_BIN}/helloworld_client" -i 127.0.0.1 -p "${PORT}" | 153 | + run_with_timeout 30 "${EXAMPLE_BIN}/helloworld_client" -i 127.0.0.1 -p "${PORT}" |
| 114 | 154 | ||
| 115 | check_example_process "helloworld_server" | 155 | check_example_process "helloworld_server" |
| 116 | clear_example_process "helloworld_server" | 156 | clear_example_process "helloworld_server" |
| @@ -119,7 +159,7 @@ run_helloworld_example() { | |||
| 119 | run_streaming_example() { | 159 | run_streaming_example() { |
| 120 | clear_example_process "streaming_server" | 160 | clear_example_process "streaming_server" |
| 121 | "${EXAMPLE_BIN}/streaming_server" -i 127.0.0.1 -p "${PORT}" & | 161 | "${EXAMPLE_BIN}/streaming_server" -i 127.0.0.1 -p "${PORT}" & |
| 122 | - sleep 1 | 162 | + wait_for_example_ready "streaming" "streaming_server" |
| 123 | 163 | ||
| 124 | expect_agent_card_http "streaming agent card (HTTP)" | 164 | expect_agent_card_http "streaming agent card (HTTP)" |
| 125 | jsonrpc_expect_result \ | 165 | jsonrpc_expect_result \ |
| @@ -131,7 +171,7 @@ run_streaming_example() { | |||
| 131 | jsonrpc_expect_result "${streaming_send_msg}" "streaming SendMessage" | 171 | jsonrpc_expect_result "${streaming_send_msg}" "streaming SendMessage" |
| 132 | 172 | ||
| 133 | echo "Running streaming_client against 127.0.0.1:${PORT}..." | 173 | echo "Running streaming_client against 127.0.0.1:${PORT}..." |
| 134 | - timeout 60 "${EXAMPLE_BIN}/streaming_client" -i 127.0.0.1 -p "${PORT}" | 174 | + run_with_timeout 60 "${EXAMPLE_BIN}/streaming_client" -i 127.0.0.1 -p "${PORT}" |
| 135 | 175 | ||
| 136 | check_example_process "streaming_server" | 176 | check_example_process "streaming_server" |
| 137 | clear_example_process "streaming_server" | 177 | clear_example_process "streaming_server" |
| @@ -49,12 +49,23 @@ for _libdir in \ | |||
| 49 | fi | 49 | fi |
| 50 | done | 50 | done |
| 51 | 51 | ||
| 52 | -RUN_ENV=(env "LD_LIBRARY_PATH=${CTEST_LD_LIBRARY_PATH}:${LD_LIBRARY_PATH:-}") | 52 | +if [[ "$(uname -s)" == "Darwin" ]]; then |
| 53 | + RUN_ENV=(env "DYLD_LIBRARY_PATH=${CTEST_LD_LIBRARY_PATH}:${DYLD_LIBRARY_PATH:-}") | ||
| 54 | +else | ||
| 55 | + RUN_ENV=(env "LD_LIBRARY_PATH=${CTEST_LD_LIBRARY_PATH}:${LD_LIBRARY_PATH:-}") | ||
| 56 | +fi | ||
| 53 | 57 | ||
| 54 | if [[ ${WITH_ASAN} -eq 1 && -z "${A2A_SKIP_ASAN:-}" ]]; then | 58 | if [[ ${WITH_ASAN} -eq 1 && -z "${A2A_SKIP_ASAN:-}" ]]; then |
| 55 | - ASAN_LIB="$(gcc -print-file-name=libasan.so 2>/dev/null || true)" | 59 | + if [[ "$(uname -s)" == "Darwin" ]]; then |
| 56 | - if [[ -n "${ASAN_LIB}" && -f "${ASAN_LIB}" ]]; then | 60 | + # ASAN itself is active on macOS (the sanitizer runtime is linked into |
| 57 | - RUN_ENV+=(LD_PRELOAD="${ASAN_LIB}" ASAN_OPTIONS="${ASAN_OPTIONS:-verify_asan_link_order=0}") | 61 | + # the test binaries by the compiler); only the Linux-specific |
| 62 | + # LD_PRELOAD of libasan.so does not apply here. | ||
| 63 | + echo "Note: ASAN enabled; skipping the Linux-only libasan LD_PRELOAD on macOS." | ||
| 64 | + else | ||
| 65 | + ASAN_LIB="$(gcc -print-file-name=libasan.so 2>/dev/null || true)" | ||
| 66 | + if [[ -n "${ASAN_LIB}" && -f "${ASAN_LIB}" ]]; then | ||
| 67 | + RUN_ENV+=(LD_PRELOAD="${ASAN_LIB}" ASAN_OPTIONS="${ASAN_OPTIONS:-verify_asan_link_order=0}") | ||
| 68 | + fi | ||
| 58 | fi | 69 | fi |
| 59 | fi | 70 | fi |
| 60 | 71 | ||
| @@ -2,9 +2,15 @@ | |||
| 2 | 2 | ||
| 3 | add_library(a2a SHARED) | 3 | add_library(a2a SHARED) |
| 4 | 4 | ||
| 5 | -add_compile_options( | 5 | +# Warnings are errors on every platform. Do not add directory-wide -Wno-* |
| 6 | - -Werror | 6 | +# switches here: every SDK source (and its subdirectories) is built under this |
| 7 | -) | 7 | +# directory, so such an exemption would also hide the same warning in newly |
| 8 | +# added code. If a pre-existing site ever needs a compiler-specific exemption, | ||
| 9 | +# scope it to the offending source file in the subdirectory that adds it, e.g. | ||
| 10 | +# set_source_files_properties(<file> PROPERTIES COMPILE_OPTIONS | ||
| 11 | +# "$<$<CXX_COMPILER_ID:AppleClang,Clang>:-Wno-...>") | ||
| 12 | +# or to the specific OBJECT library that compiles it. | ||
| 13 | +add_compile_options(-Werror) | ||
| 8 | 14 | ||
| 9 | if(A2A_BUILD_CLIENT) | 15 | if(A2A_BUILD_CLIENT) |
| 10 | add_subdirectory(client) | 16 | add_subdirectory(client) |
| @@ -3,7 +3,6 @@ | |||
| 3 | */ | 3 | */ |
| 4 | 4 | ||
| 5 | #include <event2/util.h> | 5 | #include <event2/util.h> |
| 6 | -#include <sys/eventfd.h> | ||
| 7 | #include <unistd.h> | 6 | #include <unistd.h> |
| 8 | 7 | ||
| 9 | #include <atomic> | 8 | #include <atomic> |
| @@ -15,6 +14,7 @@ | |||
| 15 | 14 | ||
| 16 | #include "a2a_log.h" | 15 | #include "a2a_log.h" |
| 17 | #include "shared/thread_utils.h" | 16 | #include "shared/thread_utils.h" |
| 17 | +#include "platform_compat.h" | ||
| 18 | #include "event_system.h" | 18 | #include "event_system.h" |
| 19 | 19 | ||
| 20 | namespace A2A { | 20 | namespace A2A { |
| @@ -90,6 +90,7 @@ struct EventSystem::Impl { | |||
| 90 | std::unique_ptr<event, decltype(&event_free)> handle{nullptr, &event_free}; | 90 | std::unique_ptr<event, decltype(&event_free)> handle{nullptr, &event_free}; |
| 91 | short flags{0}; | 91 | short flags{0}; |
| 92 | bool persistent{false}; | 92 | bool persistent{false}; |
| 93 | + Platform::NotifyChannel notifyChannel; | ||
| 93 | 94 | ||
| 94 | static void eventCallbackAdapter(evutil_socket_t eventFd, short events, void* arg) | 95 | static void eventCallbackAdapter(evutil_socket_t eventFd, short events, void* arg) |
| 95 | { | 96 | { |
| @@ -136,6 +137,9 @@ struct EventSystem::Impl { | |||
| 136 | bool enableThreadSupport{false}; | 137 | bool enableThreadSupport{false}; |
| 137 | std::atomic<int> nextEventId{1}; | 138 | std::atomic<int> nextEventId{1}; |
| 138 | std::unordered_map<int, std::unique_ptr<EventData>> events; | 139 | std::unordered_map<int, std::unique_ptr<EventData>> events; |
| 140 | + // Notify-channel events indexed by their registered read fd (guarded by the | ||
| 141 | + // EventSystem mutex). Keeps ReadEventFd O(1) without exposing raw pointers. | ||
| 142 | + std::unordered_map<int, EventData*> notifyEventsByFd; | ||
| 139 | std::thread eventThread; | 143 | std::thread eventThread; |
| 140 | }; | 144 | }; |
| 141 | 145 | ||
| @@ -152,6 +156,7 @@ EventSystem::~EventSystem() | |||
| 152 | { | 156 | { |
| 153 | std::lock_guard<std::mutex> lock(mutex_); | 157 | std::lock_guard<std::mutex> lock(mutex_); |
| 154 | events.swap(impl_->events); | 158 | events.swap(impl_->events); |
| 159 | + impl_->notifyEventsByFd.clear(); | ||
| 155 | } | 160 | } |
| 156 | 161 | ||
| 157 | for (auto& entry : events) { | 162 | for (auto& entry : events) { |
| @@ -159,6 +164,11 @@ EventSystem::~EventSystem() | |||
| 159 | event_del(entry.second->handle.get()); | 164 | event_del(entry.second->handle.get()); |
| 160 | entry.second->handle.reset(); | 165 | entry.second->handle.reset(); |
| 161 | } | 166 | } |
| 167 | + // Only fds created by CreateNotifyEventId are owned here. Fds passed to | ||
| 168 | + // AddEvent stay owned by their callers and must never be closed by us. | ||
| 169 | + if (entry.second != nullptr) { | ||
| 170 | + Platform::CloseNotifyChannel(entry.second->notifyChannel); | ||
| 171 | + } | ||
| 162 | } | 172 | } |
| 163 | 173 | ||
| 164 | if (eventBase_ != nullptr) { | 174 | if (eventBase_ != nullptr) { |
| @@ -267,76 +277,85 @@ int EventSystem::CreateNotifyEventId(EventCallback callback, void* arg, bool per | |||
| 267 | return -1; | 277 | return -1; |
| 268 | } | 278 | } |
| 269 | 279 | ||
| 270 | - // Create an eventfd with non-blocking and close-on-exec flags. | 280 | + Platform::NotifyChannel channel; |
| 271 | - int efd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC); | 281 | + if (Platform::CreateNotifyChannel(channel) != 0) { |
| 272 | - if (efd < 0) { | 282 | + A2A_LOG(A2A_LOG_LEVEL::ERROR, "Create notify channel failed."); |
| 273 | - A2A_LOG(A2A_LOG_LEVEL::ERROR, "Create eventfd failed."); | ||
| 274 | return -1; | 283 | return -1; |
| 275 | } | 284 | } |
| 276 | 285 | ||
| 277 | - // Register the eventfd for read events. Make it persistent by default unless caller says otherwise. | 286 | + // Register the read end for read events. Make it persistent by default unless caller says otherwise. |
| 278 | EventType type = EventType::READ; | 287 | EventType type = EventType::READ; |
| 279 | if (persist) { | 288 | if (persist) { |
| 280 | type = static_cast<EventType>(static_cast<unsigned int>(type) | static_cast<unsigned int>(EventType::PERSIST)); | 289 | type = static_cast<EventType>(static_cast<unsigned int>(type) | static_cast<unsigned int>(EventType::PERSIST)); |
| 281 | } | 290 | } |
| 282 | 291 | ||
| 283 | - int eventId = AddEvent(efd, type, std::move(callback), arg, 0); | 292 | + int eventId = AddEvent(channel.readFd, type, std::move(callback), arg, 0); |
| 284 | if (eventId < 0) { | 293 | if (eventId < 0) { |
| 285 | - A2A_LOG(A2A_LOG_LEVEL::ERROR, "Failed to add eventFd to the event system."); | 294 | + A2A_LOG(A2A_LOG_LEVEL::ERROR, "Failed to add notify fd to the event system."); |
| 286 | - ::close(efd); | 295 | + Platform::CloseNotifyChannel(channel); |
| 287 | return -1; | 296 | return -1; |
| 288 | } | 297 | } |
| 289 | 298 | ||
| 299 | + { | ||
| 300 | + std::lock_guard<std::mutex> lock(mutex_); | ||
| 301 | + auto it = impl_->events.find(eventId); | ||
| 302 | + if (it != impl_->events.end() && it->second != nullptr) { | ||
| 303 | + it->second->notifyChannel.readFd = channel.readFd; | ||
| 304 | + it->second->notifyChannel.writeFd = channel.writeFd; | ||
| 305 | + impl_->notifyEventsByFd[channel.readFd] = it->second.get(); | ||
| 306 | + } | ||
| 307 | + } | ||
【review】并发问题。CreateNotifyEventId 在 AddEvent 注册 read fd 之后才把通道附加到 EventData。窗口内若有其他线程调用 NotifyEventId(非 Linux 分支),会在未附加的 NotifyChannel 上先提交 CAS 增量再因 write(-1) 失败回滚,增量被静默丢失。窗口很小,但建议补显式不变量。非 Linux 分支在 notifyChannel.writeFd < 0 (通道尚未附加)时直接返回 false,使未附加的通道显式不可用。 ![]() ![]() | |||
| 308 | + | ||
| 309 | + // The eventId is published only after the channel is attached; notifying | ||
| 310 | + // an unattached channel fails without touching its counter. | ||
| 290 | return eventId; | 311 | return eventId; |
| 291 | } | 312 | } |
| 292 | 313 | ||
| 293 | bool EventSystem::NotifyEventId(int eventId, uint64_t increment) | 314 | bool EventSystem::NotifyEventId(int eventId, uint64_t increment) |
| 294 | { | 315 | { |
| 295 | - // Use eventfd write to increment the counter atomically. | 316 | +#if defined(__linux__) |
| 296 | - ssize_t written = 0; | 317 | + // Baseline: resolve the fd under the mutex, write outside it. |
| 297 | - const uint64_t val = increment; | 318 | + int eventFd = -1; |
| 298 | - | 319 | + { |
| 299 | - int eventFd = ToEventFd(eventId); | 320 | + std::lock_guard<std::mutex> lock(mutex_); |
| 300 | - if (eventFd == -1) { | 321 | + auto it = impl_->events.find(eventId); |
| 322 | + if (it == impl_->events.end() || it->second == nullptr) { | ||
| 323 | + A2A_LOG(A2A_LOG_LEVEL::ERROR, "The eventId not found."); | ||
| 324 | + return false; | ||
| 325 | + } | ||
| 326 | + eventFd = it->second->fd; | ||
| 327 | + } | ||
| 328 | + return Platform::WriteChannelFdRaw(eventFd, increment); | ||
| 329 | +#else | ||
| 330 | + // macOS: the channel may be closed concurrently, so write under the lock. | ||
| 331 | + std::lock_guard<std::mutex> lock(mutex_); | ||
| 332 | + auto it = impl_->events.find(eventId); | ||
| 333 | + if (it == impl_->events.end() || it->second == nullptr) { | ||
| 301 | A2A_LOG(A2A_LOG_LEVEL::ERROR, "The eventId not found."); | 334 | A2A_LOG(A2A_LOG_LEVEL::ERROR, "The eventId not found."); |
| 302 | return false; | 335 | return false; |
| 303 | } | 336 | } |
| 304 | - while (true) { | 337 | + |
| 305 | - written = ::write(eventFd, &val, sizeof(val)); | 338 | + return Platform::NotifyChannelNotify(it->second->notifyChannel, increment); |
【review】性能问题。NotifyEventId 现在每次都要获取 EventSystem 全局互斥锁,再把通知写入 eventfd/管道。旧实现是无锁的直接 eventfd 写,MPSCNotifyQueue::Send、连接停止通知等热路径每次调用都会与 AddEvent/RemoveEvent/ReadEventFd 串行化,高并发通知场景下是明显性能回归;同时 NotifyEventId 对通过 AddEvent 注册的普通 fd 调用时,notifyChannel 未初始化(writeFd=-1),现在必然失败,而旧代码会直接写该 fd,属于语义不兼容的行为变化。建议评估热路径无锁化:为 notifyChannel 分配稳定的堆对象,用只读的 ID 到 fd 的原子注册表,避免通知路径持有全局锁;若保持带锁实现,请将 NotifyEventId 与 AddEvent 注册的普通 fd 兼容旧语义(写回 data->fd)并在头文件注释中同步说明差异,避免调用方误用。 ![]() ![]() | |||
| 306 | - if (written == static_cast<ssize_t>(sizeof(val))) { | 339 | +#endif |
| 307 | - return true; | ||
| 308 | - } | ||
| 309 | - if (written < 0) { | ||
| 310 | - if (errno == EINTR) { | ||
| 311 | - continue; // retry | ||
| 312 | - } | ||
| 313 | - // EAGAIN/EWOULDBLOCK means the fd would block; treat as failure for notify. | ||
| 314 | - return false; | ||
| 315 | - } | ||
| 316 | - // Partial write, treat as failure. | ||
| 317 | - return false; | ||
| 318 | - } | ||
| 319 | } | 340 | } |
| 320 | 341 | ||
| 321 | bool EventSystem::ReadEventFd(int fd, uint64_t& outValue) const | 342 | bool EventSystem::ReadEventFd(int fd, uint64_t& outValue) const |
| 322 | { | 343 | { |
| 323 | - uint64_t val = 0; | 344 | +#if defined(__linux__) |
| 324 | - ssize_t rd = 0; | 345 | + // Baseline: plain eventfd read without the lock or a map lookup. |
| 325 | - while (true) { | 346 | + return Platform::ReadChannelFdRaw(fd, outValue); |
| 326 | - rd = ::read(fd, &val, sizeof(val)); | 347 | +#else |
| 327 | - if (rd == static_cast<ssize_t>(sizeof(val))) { | 348 | + // Keep the lookup and the read inside the lock: no raw EventData pointer |
| 328 | - outValue = val; | 349 | + // escapes the critical section, so a concurrent RemoveEvent/destruction |
| 329 | - return true; | 350 | + // cannot invalidate it. |
| 330 | - } | 351 | + std::lock_guard<std::mutex> lock(mutex_); |
| 331 | - if (rd < 0) { | 352 | + auto it = impl_->notifyEventsByFd.find(fd); |
| 332 | - if (errno == EINTR) { | 353 | + if (it != impl_->notifyEventsByFd.end() && it->second != nullptr) { |
| 333 | - continue; // retry | 354 | + return Platform::NotifyChannelRead(it->second->notifyChannel, fd, outValue); |
| 334 | - } | ||
| 335 | - return false; | ||
| 336 | - } | ||
| 337 | - // Partial read or EOF | ||
| 338 | - return false; | ||
| 339 | } | 355 | } |
| 356 | + | ||
| 357 | + return Platform::ReadChannelFdRaw(fd, outValue); | ||
| 358 | +#endif | ||
| 340 | } | 359 | } |
| 341 | 360 | ||
| 342 | bool EventSystem::CloseNotifyEventId(int eventId) | 361 | bool EventSystem::CloseNotifyEventId(int eventId) |
| @@ -374,6 +393,9 @@ bool EventSystem::RemoveEventInternal(int eventId, bool closeFd) | |||
| 374 | } | 393 | } |
| 375 | data = std::move(it->second); | 394 | data = std::move(it->second); |
| 376 | impl_->events.erase(it); | 395 | impl_->events.erase(it); |
| 396 | + if (data != nullptr && data->notifyChannel.readFd >= 0) { | ||
| 397 | + impl_->notifyEventsByFd.erase(data->fd); | ||
| 398 | + } | ||
| 377 | } | 399 | } |
| 378 | 400 | ||
| 379 | if (data != nullptr && data->handle != nullptr) { | 401 | if (data != nullptr && data->handle != nullptr) { |
| @@ -381,8 +403,13 @@ bool EventSystem::RemoveEventInternal(int eventId, bool closeFd) | |||
| 381 | data->handle.reset(); | 403 | data->handle.reset(); |
| 382 | } | 404 | } |
| 383 | 405 | ||
| 384 | - if (closeFd && data != nullptr && data->fd >= 0) { | 406 | + if (closeFd && data != nullptr) { |
| 385 | - ::close(data->fd); | 407 | + if (data->notifyChannel.readFd >= 0) { |
| 408 | + Platform::CloseNotifyChannel(data->notifyChannel); | ||
| 409 | + data->fd = -1; | ||
【review】资源泄漏。persist=false 的一次性 notify 事件触发后,eventCallbackAdapter 会调用 RemoveEvent(savedId)(closeFd=false),新代码在 closeFd=false 时不执行 CloseNotifyChannel,SDK 自己创建的 notify channel fd 不会被关闭:Linux 每个一次性 notify 事件泄漏 1 个 eventfd,macOS 泄漏 2 个管道 fd。新注释声明这些 fd 由 EventSystem 所有,但自动移除路径恰好绕过了关闭逻辑。建议在 EventData 中记录 ownsNotifyChannel 标志,并让 eventCallbackAdapter 自动移除一次性事件时对 SDK 自建通道走关闭路径(RemoveEventInternal closeFd=true 仅对自建通道生效),或对非持久事件触发后同样关闭属于 SDK 的通道。 ![]() ![]() | |||
| 410 | + } else if (data->fd >= 0) { | ||
| 411 | + ::close(data->fd); | ||
| 412 | + } | ||
| 386 | } | 413 | } |
| 387 | 414 | ||
| 388 | return true; | 415 | return true; |
| @@ -120,13 +120,16 @@ public: | |||
| 120 | * @param eventId The eventId returned by CreateNotifyEventId. | 120 | * @param eventId The eventId returned by CreateNotifyEventId. |
| 121 | * @param increment The 64-bit value to add to the eventfd counter (default 1). | 121 | * @param increment The 64-bit value to add to the eventfd counter (default 1). |
| 122 | * @return true on success, false on failure. | 122 | * @return true on success, false on failure. |
| 123 | + * @note Linux writes the event's fd directly (baseline). macOS writes | ||
| 124 | + * through the notify channel and only accepts eventIds from | ||
| 125 | + * CreateNotifyEventId. | ||
| 123 | */ | 126 | */ |
| 124 | bool NotifyEventId(int eventId, uint64_t increment = 1); | 127 | bool NotifyEventId(int eventId, uint64_t increment = 1); |
| 125 | 128 | ||
| 126 | /** | 129 | /** |
| 127 | * @brief Read the current counter value from a file descriptor. | 130 | * @brief Read the current counter value from a file descriptor. |
| 128 | * @param fd The fd. | 131 | * @param fd The fd. |
| 129 | - * @param outValue On success set to the value read from the eventfd. | 132 | + * @param outValue On success set to the value read. |
| 130 | * @return true on success, false on failure. | 133 | * @return true on success, false on failure. |
| 131 | */ | 134 | */ |
| 132 | bool ReadEventFd(int fd, uint64_t& outValue) const; | 135 | bool ReadEventFd(int fd, uint64_t& outValue) const; |
| @@ -163,7 +166,7 @@ private: | |||
| 163 | std::unique_ptr<Impl> impl_; | 166 | std::unique_ptr<Impl> impl_; |
| 164 | // Protects access to impl_ state that is shared across threads (primarily events map). | 167 | // Protects access to impl_ state that is shared across threads (primarily events map). |
| 165 | // Do not hold this lock while invoking callbacks or calling event_del/close to avoid deadlocks. | 168 | // Do not hold this lock while invoking callbacks or calling event_del/close to avoid deadlocks. |
| 166 | - std::mutex mutex_; | 169 | + mutable std::mutex mutex_; |
| 167 | std::atomic<bool> running_{false}; | 170 | std::atomic<bool> running_{false}; |
| 168 | struct event_base* eventBase_{nullptr}; | 171 | struct event_base* eventBase_{nullptr}; |
| 169 | int eventThreadIndex_{0}; | 172 | int eventThreadIndex_{0}; |
| @@ -18,6 +18,7 @@ | |||
| 18 | 18 | ||
| 19 | #include "a2a_log.h" | 19 | #include "a2a_log.h" |
| 20 | #include "event_system.h" | 20 | #include "event_system.h" |
| 21 | +#include "platform_compat.h" | ||
| 21 | 22 | ||
| 22 | namespace A2A::Server { | 23 | namespace A2A::Server { |
| 23 | 24 | ||
| @@ -247,22 +248,19 @@ void TcpSocket::SetTcpOptions(const TcpSocketOptions& opts) const | |||
| 247 | A2A_LOG(A2A_LOG_LEVEL::ERROR, "setsockopt(SO_KEEPALIVE) failed, errno: " + std::to_string(errno)); | 248 | A2A_LOG(A2A_LOG_LEVEL::ERROR, "setsockopt(SO_KEEPALIVE) failed, errno: " + std::to_string(errno)); |
| 248 | } | 249 | } |
| 249 | if (opts.keepAliveIdleSec > 0) { | 250 | if (opts.keepAliveIdleSec > 0) { |
| 250 | - rc = ::setsockopt(fd_, IPPROTO_TCP, TCP_KEEPIDLE, &opts.keepAliveIdleSec, | 251 | + rc = Platform::SetKeepAliveIdle(fd_, opts.keepAliveIdleSec); |
| 251 | - static_cast<socklen_t>(sizeof(opts.keepAliveIdleSec))); | ||
| 252 | if (rc != 0) { | 252 | if (rc != 0) { |
| 253 | - A2A_LOG(A2A_LOG_LEVEL::ERROR, "setsockopt(TCP_KEEPIDLE) failed, errno: " + std::to_string(errno)); | 253 | + A2A_LOG(A2A_LOG_LEVEL::ERROR, "setsockopt(keepalive idle) failed, errno: " + std::to_string(errno)); |
| 254 | } | 254 | } |
| 255 | } | 255 | } |
| 256 | if (opts.keepAliveIntvlSec > 0) { | 256 | if (opts.keepAliveIntvlSec > 0) { |
| 257 | - rc = ::setsockopt(fd_, IPPROTO_TCP, TCP_KEEPINTVL, &opts.keepAliveIntvlSec, | 257 | + rc = Platform::SetKeepAliveIntvl(fd_, opts.keepAliveIntvlSec); |
| 258 | - static_cast<socklen_t>(sizeof(opts.keepAliveIntvlSec))); | ||
| 259 | if (rc != 0) { | 258 | if (rc != 0) { |
| 260 | A2A_LOG(A2A_LOG_LEVEL::ERROR, "setsockopt(TCP_KEEPINTVL) failed, errno: " + std::to_string(errno)); | 259 | A2A_LOG(A2A_LOG_LEVEL::ERROR, "setsockopt(TCP_KEEPINTVL) failed, errno: " + std::to_string(errno)); |
| 261 | } | 260 | } |
| 262 | } | 261 | } |
| 263 | if (opts.keepAliveCnt > 0) { | 262 | if (opts.keepAliveCnt > 0) { |
| 264 | - rc = ::setsockopt(fd_, IPPROTO_TCP, TCP_KEEPCNT, &opts.keepAliveCnt, | 263 | + rc = Platform::SetKeepAliveCnt(fd_, opts.keepAliveCnt); |
| 265 | - static_cast<socklen_t>(sizeof(opts.keepAliveCnt))); | ||
| 266 | if (rc != 0) { | 264 | if (rc != 0) { |
| 267 | A2A_LOG(A2A_LOG_LEVEL::ERROR, "setsockopt(TCP_KEEPCNT) failed, errno: " + std::to_string(errno)); | 265 | A2A_LOG(A2A_LOG_LEVEL::ERROR, "setsockopt(TCP_KEEPCNT) failed, errno: " + std::to_string(errno)); |
| 268 | } | 266 | } |
| @@ -3,15 +3,22 @@ | |||
| 3 | */ | 3 | */ |
| 4 | 4 | ||
| 5 | #include <gtest/gtest.h> | 5 | #include <gtest/gtest.h> |
| 6 | +#include <fcntl.h> | ||
| 6 | #include <unistd.h> | 7 | #include <unistd.h> |
| 7 | -#include <sys/eventfd.h> | ||
| 8 | #include <sys/socket.h> | 8 | #include <sys/socket.h> |
| 9 | #include <cstring> | 9 | #include <cstring> |
| 10 | +#include <limits> | ||
| 10 | #include <thread> | 11 | #include <thread> |
| 11 | #include <chrono> | 12 | #include <chrono> |
| 12 | #include <atomic> | 13 | #include <atomic> |
| 13 | #include <future> | 14 | #include <future> |
| 15 | +#include <mutex> | ||
| 14 | #include <unordered_set> | 16 | #include <unordered_set> |
| 17 | +#include <vector> | ||
| 18 | + | ||
| 19 | +#if defined(__linux__) | ||
| 20 | +#include <sys/eventfd.h> | ||
| 21 | +#endif | ||
| 15 | 22 | ||
| 16 | #include "event_system.h" | 23 | #include "event_system.h" |
| 17 | #include "a2a_log.h" | 24 | #include "a2a_log.h" |
| @@ -27,18 +34,29 @@ using namespace A2A; | |||
| 27 | /// Create a non-blocking socket pair for testing I/O events. | 34 | /// Create a non-blocking socket pair for testing I/O events. |
| 28 | static std::pair<int, int> CreateTestSocketPair() | 35 | static std::pair<int, int> CreateTestSocketPair() |
| 29 | { | 36 | { |
| 30 | - int fds[2]; | 37 | + // A socket pair provides exactly two fds: the read end and the write end. |
| 31 | - if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK, 0, fds) < 0) { | 38 | + const int socketPairFdCount = 2; |
| 39 | + | ||
| 40 | + int fds[socketPairFdCount]; | ||
| 41 | + if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds) < 0) { | ||
| 32 | return {-1, -1}; | 42 | return {-1, -1}; |
| 33 | } | 43 | } |
| 44 | + for (int i = 0; i < socketPairFdCount; ++i) { | ||
| 45 | + int flags = fcntl(fds[i], F_GETFL, 0); | ||
| 46 | + if (flags >= 0) { | ||
| 47 | + (void)fcntl(fds[i], F_SETFL, flags | O_NONBLOCK); | ||
| 48 | + } | ||
| 49 | + } | ||
| 34 | return {fds[0], fds[1]}; | 50 | return {fds[0], fds[1]}; |
| 35 | } | 51 | } |
| 36 | 52 | ||
| 37 | -/// Create an eventfd for testing notify events. | 53 | +#if defined(__linux__) |
| 54 | +/// Create an eventfd for testing notify events (eventfd is Linux-only). | ||
| 38 | static int CreateTestEventFd() | 55 | static int CreateTestEventFd() |
| 39 | { | 56 | { |
| 40 | return eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC); | 57 | return eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC); |
| 41 | } | 58 | } |
| 59 | +#endif | ||
| 42 | 60 | ||
| 43 | /// Sleep helper for async tests. | 61 | /// Sleep helper for async tests. |
| 44 | static void SleepMs(int ms) | 62 | static void SleepMs(int ms) |
| @@ -308,6 +326,8 @@ TEST(EventSystemTest, NotifyEventId_InvalidId) | |||
| 308 | EXPECT_FALSE(es.NotifyEventId(99999, 1)); | 326 | EXPECT_FALSE(es.NotifyEventId(99999, 1)); |
| 309 | } | 327 | } |
| 310 | 328 | ||
| 329 | +#if defined(__linux__) | ||
| 330 | +// These tests rely on eventfd counter semantics (Linux-only). | ||
| 311 | TEST(EventSystemTest, ReadEventFd_Valid) | 331 | TEST(EventSystemTest, ReadEventFd_Valid) |
| 312 | { | 332 | { |
| 313 | EventSystem es(false, 0); | 333 | EventSystem es(false, 0); |
| @@ -342,6 +362,7 @@ TEST(EventSystemTest, ReadEventFd_Empty) | |||
| 342 | 362 | ||
| 343 | close(efd); | 363 | close(efd); |
| 344 | } | 364 | } |
| 365 | +#endif | ||
| 345 | 366 | ||
| 346 | // --------------------------------------------------------------------------- | 367 | // --------------------------------------------------------------------------- |
| 347 | // RemoveEvent Tests | 368 | // RemoveEvent Tests |
| @@ -806,6 +827,113 @@ TEST(EventSystemTest, NotifyEventId_WithIncrements) | |||
| 806 | es.CloseNotifyEventId(eventId); | 827 | es.CloseNotifyEventId(eventId); |
| 807 | } | 828 | } |
| 808 | 829 | ||
| 830 | +TEST(EventSystemTest, NotifyEventId_CoalescesIntoOneWakeup) | ||
| 831 | +{ | ||
| 832 | + EventSystem es(true, 0); | ||
| 833 | + es.Init(); | ||
| 834 | + | ||
| 835 | + std::mutex readsMutex; | ||
| 836 | + std::vector<uint64_t> reads; | ||
| 837 | + std::atomic<int> callbackCount{0}; | ||
| 838 | + | ||
| 839 | + int eventId = es.CreateNotifyEventId( | ||
| 840 | + [&](int fd, short, auto*) { | ||
| 841 | + callbackCount.fetch_add(1); | ||
| 842 | + uint64_t value = 0; | ||
| 843 | + while (es.ReadEventFd(fd, value)) { | ||
| 844 | + std::lock_guard<std::mutex> lock(readsMutex); | ||
| 845 | + reads.push_back(value); | ||
| 846 | + } | ||
| 847 | + }, | ||
| 848 | + nullptr, true); | ||
| 849 | + ASSERT_GE(eventId, 0); | ||
| 850 | + | ||
| 851 | + // Ten notifications must coalesce into one accumulated wakeup; extra wake | ||
| 852 | + // bytes would cause additional callbacks. | ||
| 853 | + for (int i = 0; i < 10; ++i) { | ||
| 854 | + ASSERT_TRUE(es.NotifyEventId(eventId, 1)); | ||
| 855 | + } | ||
| 856 | + | ||
| 857 | + std::thread loop([&es]() { es.Start(false); }); | ||
| 858 | + SleepMs(100); | ||
| 859 | + es.Stop(); | ||
| 860 | + loop.join(); | ||
| 861 | + | ||
| 862 | + EXPECT_EQ(callbackCount.load(), 1); | ||
| 863 | + { | ||
| 864 | + std::lock_guard<std::mutex> lock(readsMutex); | ||
| 865 | + ASSERT_EQ(reads.size(), 1u); | ||
| 866 | + EXPECT_EQ(reads[0], 10u); | ||
| 867 | + } | ||
| 868 | + | ||
| 869 | + es.CloseNotifyEventId(eventId); | ||
| 870 | +} | ||
| 871 | + | ||
| 872 | +TEST(EventSystemTest, NotifyEventId_ZeroIncrementDoesNotWake) | ||
| 873 | +{ | ||
| 874 | + EventSystem es(true, 0); | ||
| 875 | + es.Init(); | ||
| 876 | + | ||
| 877 | + std::atomic<int> callbackCount{0}; | ||
| 878 | + int eventId = es.CreateNotifyEventId( | ||
| 879 | + [&callbackCount](int, short, auto*) { callbackCount.fetch_add(1); }, | ||
| 880 | + nullptr, true); | ||
| 881 | + ASSERT_GE(eventId, 0); | ||
| 882 | + | ||
| 883 | + // eventfd parity: succeeds without becoming readable. | ||
| 884 | + EXPECT_TRUE(es.NotifyEventId(eventId, 0)); | ||
| 885 | + | ||
| 886 | + std::thread loop([&es]() { es.Start(false); }); | ||
| 887 | + SleepMs(100); | ||
| 888 | + es.Stop(); | ||
| 889 | + loop.join(); | ||
| 890 | + | ||
| 891 | + EXPECT_EQ(callbackCount.load(), 0); | ||
| 892 | + | ||
| 893 | + es.CloseNotifyEventId(eventId); | ||
| 894 | +} | ||
| 895 | + | ||
| 896 | +TEST(EventSystemTest, NotifyEventId_MaxIncrementRejected) | ||
| 897 | +{ | ||
| 898 | + EventSystem es(true, 0); | ||
| 899 | + es.Init(); | ||
| 900 | + | ||
| 901 | + std::mutex readsMutex; | ||
| 902 | + uint64_t readValue = 0; | ||
| 903 | + std::atomic<int> callbackCount{0}; | ||
| 904 | + | ||
| 905 | + int eventId = es.CreateNotifyEventId( | ||
| 906 | + [&](int fd, short, auto*) { | ||
| 907 | + callbackCount.fetch_add(1); | ||
| 908 | + uint64_t value = 0; | ||
| 909 | + while (es.ReadEventFd(fd, value)) { | ||
| 910 | + std::lock_guard<std::mutex> lock(readsMutex); | ||
| 911 | + readValue = value; | ||
| 912 | + } | ||
| 913 | + }, | ||
| 914 | + nullptr, true); | ||
| 915 | + ASSERT_GE(eventId, 0); | ||
| 916 | + | ||
| 917 | + ASSERT_TRUE(es.NotifyEventId(eventId, 1)); | ||
| 918 | + // eventfd rejects increments above 0xFFFFFFFFFFFFFFFE; the committed | ||
| 919 | + // count must remain untouched. | ||
| 920 | + EXPECT_FALSE(es.NotifyEventId(eventId, std::numeric_limits<uint64_t>::max())); | ||
| 921 | + | ||
| 922 | + std::thread loop([&es]() { es.Start(false); }); | ||
| 923 | + SleepMs(100); | ||
| 924 | + es.Stop(); | ||
| 925 | + loop.join(); | ||
| 926 | + | ||
| 927 | + EXPECT_EQ(callbackCount.load(), 1); | ||
| 928 | + { | ||
| 929 | + std::lock_guard<std::mutex> lock(readsMutex); | ||
| 930 | + EXPECT_EQ(readValue, 1u); | ||
| 931 | + } | ||
| 932 | + | ||
| 933 | + es.CloseNotifyEventId(eventId); | ||
| 934 | +} | ||
| 935 | + | ||
| 936 | +#if defined(__linux__) | ||
| 809 | TEST(EventSystemTest, ReadEventFd_MultipleValues) | 937 | TEST(EventSystemTest, ReadEventFd_MultipleValues) |
| 810 | { | 938 | { |
| 811 | EventSystem es(false, 0); | 939 | EventSystem es(false, 0); |
| @@ -830,6 +958,7 @@ TEST(EventSystemTest, ReadEventFd_MultipleValues) | |||
| 830 | 958 | ||
| 831 | close(efd); | 959 | close(efd); |
| 832 | } | 960 | } |
| 961 | +#endif | ||
| 833 | 962 | ||
| 834 | // --------------------------------------------------------------------------- | 963 | // --------------------------------------------------------------------------- |
| 835 | // CloseNotifyEventId Tests | 964 | // CloseNotifyEventId Tests |
| @@ -1164,8 +1293,11 @@ TEST(EventSystemTest, AddEvent_InvalidFd) | |||
| 1164 | es.Init(); | 1293 | es.Init(); |
| 1165 | 1294 | ||
| 1166 | // Use a closed fd | 1295 | // Use a closed fd |
| 1167 | - int invalidFd = CreateTestEventFd(); | 1296 | + auto [fd1, fd2] = CreateTestSocketPair(); |
| 1168 | - close(invalidFd); | 1297 | + ASSERT_GE(fd1, 0); |
| 1298 | + close(fd1); | ||
| 1299 | + close(fd2); | ||
| 1300 | + int invalidFd = fd1; | ||
| 1169 | 1301 | ||
| 1170 | int eventId = es.AddEvent(invalidFd, EventType::READ, [](int, short, void*) {}, nullptr, 0); | 1302 | int eventId = es.AddEvent(invalidFd, EventType::READ, [](int, short, void*) {}, nullptr, 0); |
| 1171 | 1303 | ||
| @@ -312,7 +312,9 @@ TEST_F(SocketTest, ApplyOptionsReusePort) | |||
| 312 | int reuse = 0; | 312 | int reuse = 0; |
| 313 | socklen_t len = sizeof(reuse); | 313 | socklen_t len = sizeof(reuse); |
| 314 | EXPECT_EQ(::getsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &reuse, &len), 0); | 314 | EXPECT_EQ(::getsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &reuse, &len), 0); |
| 315 | - EXPECT_EQ(reuse, 1); | 315 | + // macOS reports the SO_REUSEPORT option bit value (0x200) instead of 1, |
| 316 | + // both mean the option is enabled. | ||
| 317 | + EXPECT_NE(reuse, 0); | ||
| 316 | } | 318 | } |
| 317 | 319 | ||
| 318 | // =========================================================================== | 320 | // =========================================================================== |
| @@ -697,4 +699,4 @@ TEST_F(SocketTest, ConcurrentEnableDisable) | |||
| 697 | EXPECT_EQ(successCount.load(), 40); | 699 | EXPECT_EQ(successCount.load(), 40); |
| 698 | } | 700 | } |
| 699 | 701 | ||
| 700 | -} // namespace A2A::Server::Test | 702 | +} // namespace A2A::Server::Test |
| @@ -28,7 +28,9 @@ class TcpListenerTest : public ::testing::Test { | |||
| 28 | protected: | 28 | protected: |
| 29 | void SetUp() override | 29 | void SetUp() override |
| 30 | { | 30 | { |
| 31 | - eventSystem_ = std::make_unique<EventSystem>(false, 0); | 31 | + // Thread support is required: these tests run the event loop in the |
| 32 | + // background and stop it from the test thread afterwards. | ||
| 33 | + eventSystem_ = std::make_unique<EventSystem>(true, 0); | ||
| 32 | ASSERT_TRUE(eventSystem_->Init()); | 34 | ASSERT_TRUE(eventSystem_->Init()); |
| 33 | 35 | ||
| 34 | listener_ = std::make_unique<TcpListener>(*eventSystem_); | 36 | listener_ = std::make_unique<TcpListener>(*eventSystem_); |
| @@ -271,4 +273,4 @@ TEST_F(TcpListenerTest, MultipleStartStopCycles) | |||
| 271 | } | 273 | } |
| 272 | } | 274 | } |
| 273 | 275 | ||
| 274 | -} | 276 | +} |


【review】逻辑问题。macOS 管道路径 NotifyChannelNotify 中,软件计数在写管道前已 fetch_add,若 write 因管道满返回 EAGAIN,函数返回 false,但该次通知已被计数并在下次 drain 时投递。上层 MPSCNotifyQueue::Send 把返回值当作失败处理,libcurl_conn 会误报 Request queue is full(消息实际已入队会被处理),语义不一致。建议把 EAGAIN 视为成功(计数已累加且管道可读性保证事件会被处理),或扩展返回值语义区分已确认与已排队,并同步修正调用方对失败的处理。