Merged
feat(a2a): a2a support macos #351
feat(a2a): a2a support macos #351
Merged
zhuyutong888Add on 28 days ago
Total: 21 files changed+1107-258
@@ -5,6 +5,26 @@ set(CMAKE_CXX_STANDARD 17)
5set(CMAKE_CXX_STANDARD_REQUIRED ON)5set(CMAKE_CXX_STANDARD_REQUIRED ON)
6set(CMAKE_CXX_EXTENSIONS OFF)6set(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+ 
8option(A2A_BUILD_CLIENT "Build A2A client components" ON)28option(A2A_BUILD_CLIENT "Build A2A client components" ON)
9option(A2A_BUILD_SERVER "Build A2A server components" ON)29option(A2A_BUILD_SERVER "Build A2A server components" ON)
10option(A2A_ENABLE_EXAMPLES "Build example binaries" OFF)30option(A2A_ENABLE_EXAMPLES "Build example binaries" OFF)
@@ -32,13 +52,35 @@ endif()
32 52 
33find_package(OpenSSL REQUIRED)53find_package(OpenSSL REQUIRED)
34find_package(CURL REQUIRED)54find_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 
38if(TARGET event)61if(TARGET event)
39 list(APPEND _a2a_link_libs event)62 list(APPEND _a2a_link_libs event)
40elseif(TARGET libevent)63elseif(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()
42endif()84endif()
43 85 
44if(TARGET event_pthreads)86if(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 \
70sudo pacman -S --needed base-devel cmake openssl curl libevent nlohmann-json71sudo 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```bash93```bash
@@ -81,6 +99,9 @@ curl-config --version
81 99 
82# CMake100# CMake
83cmake --version101cmake --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] message48[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### 默认输出:stdout53### 默认输出: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.
106template<typename... Args>116template<typename... Args>
107inline void LogInternal(A2A_LOG_LEVEL level, const char* file, const char* func, int line,117inline 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+ }
maoqiming
maoqimingmaoqiming23 days ago

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

likedislike
zhuyutong888
21 days ago Comments:
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+ }
maoqiming
maoqimingmaoqiming23 days ago

【review】性能问题。macOS 管道路径 NotifyChannelRead 的 drain 循环一直读直到 EAGAIN 才退出,而它整体在 EventSystem::ReadEventFd 的全局互斥锁内执行(事件回调中常见 while(ReadEventFd(fd,value)) 循环,如 libcurl_conn.cpp)。通知持续到达时,事件线程会长时间卡在 drain 循环并持有全局锁,阻塞其它线程的 NotifyEventId/AddEvent/RemoveEvent 与回调,造成事件循环饥饿。建议对单次 NotifyChannelRead 的 drain 次数设上限(如最多读 2-4 次即返回),计数交换能保证语义正确,多余唤醒留到下一轮回调;并考虑事件线程路径避免持锁读 fd。

likedislike
zhuyutong888
21 days ago Comments:
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 
11echo "==> Checking system dependencies for yellow_a2a..."11echo "==> Checking system dependencies for yellow_a2a..."
12 12 
13-if [[ ! -f /etc/os-release ]]; then13+if [[ "$(uname -s)" == "Darwin" ]]; then
14- echo "Error: Linux with /etc/os-release is required" >&214+ 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 123 exit 1
16fi24fi
17-# shellcheck disable=SC1091
18-. /etc/os-release
19-OS="${ID:-}"
20-OS_VERSION="${VERSION_ID:-}"
21 25 
22if [[ "${EUID}" -ne 0 ]]; then26if [[ "${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=066 local need_libevent=0
63 local need_json=067 local need_json=0
64 local need_http_parser=068 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=1189 need_build_tools=1
185 fi190 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; then237 if command_exists curl-config; then
189 echo " - libcurl: OK"238 echo " - libcurl: OK"
@@ -201,7 +250,7 @@ install_dependencies() {
201 ;;250 ;;
202 esac251 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 ]]; then254 if [[ ${need_any} -eq 0 ]]; then
206 echo "==> All tracked dependencies are already installed!"255 echo "==> All tracked dependencies are already installed!"
207 return 0256 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}" >&2329 echo "Error: Unsupported OS for automatic install: ${OS}" >&2
264 echo "Please install manually: cmake, g++, pkg-config, libcurl-devel, openssl-devel," >&2330 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=1343 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"
maoqiming
maoqimingmaoqiming25 days ago

【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 并以非零退出;只有全部通过才打印已验证成功的提示,让安装阶段就能暴露问题。

likedislike
zhuyutong888
24 days ago Comments:
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; then397 if ! command_exists cmake; then
280 echo "✗ cmake is missing" >&2398 echo "✗ cmake is missing" >&2
281 ok=0399 ok=0
@@ -17,7 +17,31 @@ OUTPUT_DIR="${A2A_OUTPUT_DIR:-${ROOT}/output}"
17EXAMPLE_BIN="${OUTPUT_DIR}/bin"17EXAMPLE_BIN="${OUTPUT_DIR}/bin"
18LIB_DIR="${OUTPUT_DIR}/lib"18LIB_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+}
maoqiming
maoqimingmaoqiming23 days ago

【review】脚本健壮性。macOS 默认没有 GNU timeout,若也未安装 coreutils 的 gtimeout,TIMEOUT_BIN 为空,run_with_timeout 静默退化为无超时直接执行,示例客户端假死时冒烟脚本会无限挂起而非失败,问题被掩盖。建议找不到 timeout/gtimeout 时报错并要求安装 coreutils,或用后台进程加 kill 机制兜底实现超时,保证任何平台都不丢失超时保护。

likedislike
zhuyutong888
21 days ago Comments:
21 45 
22PORT="${A2A_EXAMPLE_PORT:-8888}"46PORT="${A2A_EXAMPLE_PORT:-8888}"
23JSONRPC_BASE="http://127.0.0.1:${PORT}/jsonrpc"47JSONRPC_BASE="http://127.0.0.1:${PORT}/jsonrpc"
@@ -95,10 +119,26 @@ expect_agent_card_http() {
95 fi119 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+ 
98run_helloworld_example() {138run_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 1141+ 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() {
119run_streaming_example() {159run_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 1162+ 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 fi49 fi
50done50done
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 
54if [[ ${WITH_ASAN} -eq 1 && -z "${A2A_SKIP_ASAN:-}" ]]; then58if [[ ${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}" ]]; then60+ # 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 fi69 fi
59fi70fi
60 71 
@@ -2,9 +2,15 @@
2 2 
3add_library(a2a SHARED)3add_library(a2a SHARED)
4 4 
5-add_compile_options(5+# Warnings are errors on every platform. Do not add directory-wide -Wno-*
6- -Werror6+# 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 
9if(A2A_BUILD_CLIENT)15if(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 
20namespace A2A {20namespace 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+ }
maoqiming
maoqimingmaoqiming20 days ago

【review】并发问题。CreateNotifyEventId 在 AddEvent 注册 read fd 之后才把通道附加到 EventData。窗口内若有其他线程调用 NotifyEventId(非 Linux 分支),会在未附加的 NotifyChannel 上先提交 CAS 增量再因 write(-1) 失败回滚,增量被静默丢失。窗口很小,但建议补显式不变量。非 Linux 分支在 notifyChannel.writeFd < 0 (通道尚未附加)时直接返回 false,使未附加的通道显式不可用。

likedislike
zhuyutong888
20 days ago Comments:
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 
293bool EventSystem::NotifyEventId(int eventId, uint64_t increment)314bool 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);
maoqiming
maoqimingmaoqiming23 days ago

【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)并在头文件注释中同步说明差异,避免调用方误用。

likedislike
zhuyutong888
21 days ago Comments:
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 
321bool EventSystem::ReadEventFd(int fd, uint64_t& outValue) const342bool 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; // retry354+ 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 
342bool EventSystem::CloseNotifyEventId(int eventId)361bool 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;
maoqiming
maoqimingmaoqiming23 days ago

【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 的通道。

likedislike
zhuyutong888
21 days ago Comments:
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 
22namespace A2A::Server {23namespace 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 }
@@ -6,6 +6,8 @@ target_link_libraries(a2a_shared PRIVATE third_party_headers)
6target_include_directories(a2a_shared6target_include_directories(a2a_shared
7 PUBLIC7 PUBLIC
8 ${CMAKE_SOURCE_DIR}/include8 ${CMAKE_SOURCE_DIR}/include
9+ PRIVATE
10+ ${CMAKE_CURRENT_SOURCE_DIR}/..
9)11)
10 12 
11set_target_properties(a2a_shared PROPERTIES13set_target_properties(a2a_shared PROPERTIES
@@ -2,17 +2,22 @@
2 * Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.2 * Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
3 */3 */
4 4 
5-#include <unistd.h>5+#include <string>
6-#include <iostream>6+#include <utility>
7-#include <sys/eventfd.h>
8 7 
9#include "a2a_log.h"8#include "a2a_log.h"
9+#include "event/event_system.h"
10#include "a2a_timer.h"10#include "a2a_timer.h"
11 11 
12-constexpr int MAX_EPOLL_CNT = 16;12+namespace {
13+ 
14+// Keeps the internal event loop from exiting while no timers are pending,
15+// so timers added later (from any thread) fire as expected.
16+constexpr long KEEP_ALIVE_INTERVAL_MS = 60 * 60 * 1000;
17+ 
18+} // namespace
13 19 
14A2ATimer::A2ATimer() noexcept20A2ATimer::A2ATimer() noexcept
15- : running_(false)
16{21{
17}22}
18 23 
@@ -27,38 +32,6 @@ A2ATimer& A2ATimer::Instance()
27 return instance;32 return instance;
28}33}
29 34 
30-int A2ATimer::Init()
31-{
32- epfd_ = epoll_create1(0);
33- if (epfd_ == -1) {
34- A2A_LOG(A2A_LOG_LEVEL::ERROR, "a2a timer epoll_create1 failed");
35- return -1;
36- }
37- 
38- wakeFd_ = eventfd(0, EFD_NONBLOCK);
39- if (wakeFd_ == -1) {
40- A2A_LOG(A2A_LOG_LEVEL::ERROR, "a2a timer eventfd failed");
41- close(epfd_);
42- epfd_ = -1;
43- return -1;
44- }
45- 
46- epoll_event ev;
47- ev.events = EPOLLIN;
48- ev.data.fd = wakeFd_;
49- epoll_ctl(epfd_, EPOLL_CTL_ADD, wakeFd_, &ev);
50- if (epfd_ == -1) {
51- A2A_LOG(A2A_LOG_LEVEL::ERROR, "a2a timer epoll_ctl failed");
52- close(epfd_);
53- epfd_ = -1;
54- close(wakeFd_);
55- wakeFd_ = -1;
56- return -1;
57- }
58- 
59- return 0;
60-}
61- 
62int A2ATimer::Start()35int A2ATimer::Start()
63{36{
64 bool expected = false;37 bool expected = false;
@@ -67,12 +40,27 @@ int A2ATimer::Start()
67 return 0;40 return 0;
68 }41 }
69 42 
70- if (this->Init() != 0) {43+ if (eventSystem_ == nullptr) {
44+ eventSystem_ = std::make_unique<A2A::EventSystem>();
45+ }
46+ if (!eventSystem_->Init()) {
47+ A2A_LOG(A2A_LOG_LEVEL::ERROR, "a2a timer init event system failed");
71 running_.store(false);48 running_.store(false);
72 return -1;49 return -1;
73 }50 }
74 51 
75- loopThread_ = std::thread(&A2ATimer::RunLoop, this);52+ if (keepAliveEventId_ == -1) {
53+ const int id = eventSystem_->AddTimer(
54+ KEEP_ALIVE_INTERVAL_MS, [](int, short, void*) {}, nullptr, true);
55+ if (id < 0) {
56+ A2A_LOG(A2A_LOG_LEVEL::ERROR, "a2a timer create keep-alive event failed");
57+ running_.store(false);
58+ return -1;
59+ }
60+ keepAliveEventId_ = id;
61+ }
62+ 
63+ eventSystem_->Start(true);
76 A2A_LOG(A2A_LOG_LEVEL::INFO, "start a2a timer succeed");64 A2A_LOG(A2A_LOG_LEVEL::INFO, "start a2a timer succeed");
77 return 0;65 return 0;
78}66}
@@ -85,50 +73,45 @@ void A2ATimer::Stop()
85 return;73 return;
86 }74 }
87 75 
88- {76+ if (eventSystem_ != nullptr) {
89- std::lock_guard<std::mutex> lock(mtx_);77+ eventSystem_->Stop();
90- uint64_t one = 1;
91- if (write(wakeFd_, &one, sizeof(one)) < 0) {
92- A2A_LOG(A2A_LOG_LEVEL::WARN, "write failed");
93- }
94- }
95- 
96- if (loopThread_.joinable()) {
97- loopThread_.join();
98- }
99- 
100- if (epfd_ > 0) {
101- close(epfd_);
102- epfd_ = -1;
103- }
104- if (wakeFd_ > 0) {
105- close(wakeFd_);
106- wakeFd_ = -1;
107 }78 }
108 A2A_LOG(A2A_LOG_LEVEL::INFO, "stop a2a timer succeed");79 A2A_LOG(A2A_LOG_LEVEL::INFO, "stop a2a timer succeed");
109}80}
110 81 
111int A2ATimer::AddTimer(int ms, TimerCallback cb, void *arg)82int A2ATimer::AddTimer(int ms, TimerCallback cb, void *arg)
112{83{
113- if (!running_.load() && this->Start() != 0) {84+ if (ms <= 0) {
85+ A2A_LOG(A2A_LOG_LEVEL::ERROR, "invalid timer timeout: " + std::to_string(ms));
86+ return -1;
87+ }
maoqiming
maoqimingmaoqiming20 days ago

【review】顺序问题。AddTimer 先 EnsureStarted()(可能启动整个 EventSystem)再校验 ms <= 0,非法参数也付出启动成本。将 ms <= 0 校验移到 EnsureStarted() 之前。

likedislike
zhuyutong888
20 days ago Comments:
88+ if (!this->EnsureStarted()) {
114 A2A_LOG(A2A_LOG_LEVEL::ERROR, "a2a timer not started");89 A2A_LOG(A2A_LOG_LEVEL::ERROR, "a2a timer not started");
115 return -1;90 return -1;
116 }91 }
117 92 
118 std::lock_guard<std::mutex> lock(mtx_);93 std::lock_guard<std::mutex> lock(mtx_);
119- TimerTask t;94+ auto task = std::make_unique<TimerTask>();
120- t.id = nextId_++;95+ task->id = nextId_++;
121- t.expire = std::chrono::steady_clock::now() + std::chrono::milliseconds(ms);96+ task->callback = std::move(cb);
122- t.callback = cb;97+ task->arg = arg;
123- t.arg = arg;98+ const int id = task->id;
124- tasks_[t.id] = t;99+ const uint64_t generation = nextGeneration_++;
125- 100+ task->generation = generation;
126- // 写一个字节唤醒epoll101+ task->eventId = eventSystem_->AddTimer(
127- uint64_t one = 1;102+ static_cast<long>(ms),
128- if (write(wakeFd_, &one, sizeof(one)) < 0) {103+ [this, id, generation](int, short, void*) {
129- A2A_LOG(A2A_LOG_LEVEL::WARN, "write failed");104+ this->OnTimerFired(id, generation);
105+ },
106+ nullptr, false);
107+ if (task->eventId < 0) {
108+ A2A_LOG(A2A_LOG_LEVEL::ERROR, "a2a timer add task failed, id: " + std::to_string(task->id));
109+ return -1;
130 }110 }
131- return t.id;111+ tasks_.emplace(id, std::move(task));
112+ 
113+ A2A_LOG(A2A_LOG_LEVEL::DEBUG, "timer added, id: " + std::to_string(id) + ", timeout: " + std::to_string(ms));
114+ return id;
132}115}
133 116 
134void A2ATimer::CancelTimer(int id)117void A2ATimer::CancelTimer(int id)
@@ -138,8 +121,27 @@ void A2ATimer::CancelTimer(int id)
138 return;121 return;
139 }122 }
140 123 
141- std::lock_guard<std::mutex> lock(mtx_);124+ std::unique_ptr<TimerTask> task;
142- tasks_.erase(id);125+ int eventId = -1;
126+ {
127+ std::lock_guard<std::mutex> lock(mtx_);
128+ auto it = tasks_.find(id);
129+ if (it == tasks_.end()) {
130+ return;
131+ }
132+ eventId = it->second->eventId;
133+ task = std::move(it->second);
134+ tasks_.erase(it);
135+ }
136+ 
137+ // RemoveEvent may wait for a currently running callback (libevent defers
138+ // event_del while the callback executes), so it must run WITHOUT holding
139+ // mtx_: the callback itself needs mtx_ and would otherwise deadlock.
140+ // Callbacks carry (id, generation) by value only, so freeing the task here
141+ // is safe even if a stale callback is still pending in libevent.
142+ if (eventSystem_ != nullptr && eventId >= 0) {
143+ eventSystem_->RemoveEvent(eventId);
144+ }
143}145}
144 146 
145int A2ATimer::RefreshTimer(int id, int ms)147int A2ATimer::RefreshTimer(int id, int ms)
@@ -152,90 +154,72 @@ int A2ATimer::RefreshTimer(int id, int ms)
152 A2A_LOG(A2A_LOG_LEVEL::ERROR, "invalid timer timeout: " + std::to_string(ms));154 A2A_LOG(A2A_LOG_LEVEL::ERROR, "invalid timer timeout: " + std::to_string(ms));
153 return -1;155 return -1;
154 }156 }
155- std::lock_guard<std::mutex> lock(mtx_);157+ 
156- auto it = tasks_.find(id);158+ int oldEventId = -1;
157- if (it == tasks_.end()) {159+ {
158- A2A_LOG(A2A_LOG_LEVEL::ERROR, "timer not found, id: " + std::to_string(id));160+ std::lock_guard<std::mutex> lock(mtx_);
159- return -1;161+ auto it = tasks_.find(id);
162+ if (it == tasks_.end()) {
163+ A2A_LOG(A2A_LOG_LEVEL::ERROR, "timer not found, id: " + std::to_string(id));
164+ return -1;
165+ }
166+ oldEventId = it->second->eventId;
167+ const uint64_t generation = nextGeneration_++;
168+ const int newEventId = eventSystem_->AddTimer(
169+ static_cast<long>(ms),
170+ [this, id, generation](int, short, void*) {
171+ this->OnTimerFired(id, generation);
172+ },
173+ nullptr, false);
174+ if (newEventId < 0) {
175+ // Keep the current arming: a failed refresh must not lose the timer.
176+ A2A_LOG(A2A_LOG_LEVEL::ERROR, "a2a timer refresh failed, id: " + std::to_string(id));
177+ return -1;
178+ }
179+ // Publish under the same lock so the replacement callback (which must
180+ // take mtx_) cannot run before the new generation is visible.
181+ it->second->generation = generation;
182+ it->second->eventId = newEventId;
160 }183 }
161- it->second.expire = std::chrono::steady_clock::now() + std::chrono::milliseconds(ms);184+ 
185+ // RemoveEvent may block on a running callback: call it outside mtx_.
186+ if (oldEventId >= 0) {
187+ (void)eventSystem_->RemoveEvent(oldEventId);
188+ }
189+ 
162 A2A_LOG(A2A_LOG_LEVEL::DEBUG,190 A2A_LOG(A2A_LOG_LEVEL::DEBUG,
163 "timer refreshed, id: " + std::to_string(id) +191 "timer refreshed, id: " + std::to_string(id) +
164 ", timeout: " + std::to_string(ms));192 ", timeout: " + std::to_string(ms));
165- uint64_t one = 1;
166- if (write(wakeFd_, &one, sizeof(one)) < 0) {
167- A2A_LOG(A2A_LOG_LEVEL::WARN, "write failed");
168- return -1;
169- }
170 return 0;193 return 0;
171}194}
172 195 
173-int A2ATimer::GetNextTimeout()196+bool A2ATimer::EnsureStarted()
174{197{
175- std::lock_guard<std::mutex> lock(mtx_);198+ if (running_.load()) {
176- if (tasks_.empty()) {199+ return true;
177- return -1;
178 }200 }
179- 201+ return this->Start() == 0;
180- auto now = std::chrono::steady_clock::now();
181- auto nearest = tasks_.begin()->second.expire;
182- for (const auto& item : tasks_) {
183- if (item.second.expire < nearest) {
184- nearest = item.second.expire;
185- }
186- }
187- auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(nearest - now).count();
188- return diff > 0 ? static_cast<int>(diff) : 0;
189}202}
190 203 
191-void A2ATimer::HandleExpired()204+void A2ATimer::OnTimerFired(int id, uint64_t generation)
192{205{
193- std::vector<TimerTask> expired;206+ TimerCallback cb;
207+ void *userArg = nullptr;
194 {208 {
195 std::lock_guard<std::mutex> lock(mtx_);209 std::lock_guard<std::mutex> lock(mtx_);
196- auto now = std::chrono::steady_clock::now();210+ auto it = tasks_.find(id);
197- 211+ if (it == tasks_.end() || it->second->generation != generation) {
198- for (auto it = tasks_.begin(); it != tasks_.end();) {212+ // Removed, fired, or re-armed: this arming is stale.
199- if (it->second.expire < now + std::chrono::milliseconds(1)) {213+ return;
200- expired.emplace_back(it->second);
201- it = tasks_.erase(it);
202- } else {
203- ++it;
204- }
205 }214 }
215+ cb = std::move(it->second->callback);
216+ userArg = it->second->arg;
217+ tasks_.erase(it);
206 }218 }
207 219 
208- for (auto& e : expired) {220+ // Run callbacks without holding the lock so other threads can add/cancel timers.
209- if (e.callback) {221+ if (cb) {
210- e.callback(e.arg);222+ cb(userArg);
211- }
212- }
213-}
214- 
215-void A2ATimer::RunLoop()
216-{
217- while (running_) {
218- int timeout = GetNextTimeout();
219- epoll_event events[MAX_EPOLL_CNT];
220- int nfds = epoll_wait(epfd_, events, MAX_EPOLL_CNT, timeout);
221- if (nfds == 0) {
222- HandleExpired();
223- continue;
224- } else if (nfds < 0) {
225- continue;
226- }
227- 
228- for (int i = 0; i < nfds; i++) {
229- A2A_LOG(A2A_LOG_LEVEL::INFO, "Got I/O event on fd " + std::to_string(events[i].data.fd));
230- if (events[i].data.fd != wakeFd_) {
231- continue;
232- }
233- uint64_t val;
234- if (read(wakeFd_, &val, sizeof(val)) < 0) {
235- A2A_LOG(A2A_LOG_LEVEL::WARN, "read failed");
236- }
237- HandleExpired();
238- }
239 }223 }
240}224}
241 225 
@@ -250,4 +234,4 @@ struct A2ATimerInitializer {
250 }234 }
251};235};
252 236 
253-static A2ATimerInitializer g_timerInitializer;237+static A2ATimerInitializer g_timerInitializer;
@@ -5,22 +5,25 @@
5#ifndef A2A_TIMER_H5#ifndef A2A_TIMER_H
6#define A2A_TIMER_H6#define A2A_TIMER_H
7 7 
8-#include <vector>
9-#include <chrono>
10-#include <functional>
11-#include <unordered_map>
12-#include <mutex>
13-#include <thread>
14#include <atomic>8#include <atomic>
15-#include <sys/epoll.h>9+#include <cstdint>
10+#include <functional>
11+#include <memory>
12+#include <mutex>
13+#include <unordered_map>
14+ 
15+#include "event/event_system.h"
16 16 
17using TimerCallback = std::function<void(void *)>;17using TimerCallback = std::function<void(void *)>;
18 18 
19struct TimerTask {19struct TimerTask {
20- int id;20+ int id{0};
21- std::chrono::steady_clock::time_point expire;21+ // Unique token of the current arming; callbacks carry it by value so stale
22+ // callbacks never dereference task objects.
23+ uint64_t generation{0};
24+ int eventId{-1};
22 TimerCallback callback;25 TimerCallback callback;
23- void *arg;26+ void *arg{nullptr};
24};27};
25 28 
26class A2ATimer {29class A2ATimer {
@@ -38,19 +41,21 @@ private:
38 A2ATimer() noexcept;41 A2ATimer() noexcept;
39 ~A2ATimer() noexcept;42 ~A2ATimer() noexcept;
40 43 
41- int Init();44+ A2ATimer(const A2ATimer&) = delete;
42- void RunLoop();45+ A2ATimer& operator=(const A2ATimer&) = delete;
43- int GetNextTimeout();46+ 
44- void HandleExpired();47+ bool EnsureStarted();
48+ void OnTimerFired(int id, uint64_t generation);
45 49 
46 int nextId_ = 1;50 int nextId_ = 1;
47- int epfd_ = -1;51+ // Monotonic arming tokens (guarded by mtx_).
48- int wakeFd_ = -1;52+ uint64_t nextGeneration_ = 1;
49- std::unordered_map<int, TimerTask> tasks_;53+ int keepAliveEventId_ = -1;
54+ std::unordered_map<int, std::unique_ptr<TimerTask>> tasks_;
50 55 
51 std::mutex mtx_;56 std::mutex mtx_;
52- std::thread loopThread_;57+ std::atomic<bool> running_{false};
53- std::atomic<bool> running_;58+ std::unique_ptr<A2A::EventSystem> eventSystem_;
54};59};
55 60 
56-#endif // A2A_TIMER_H61+#endif // A2A_TIMER_H
@@ -5,22 +5,21 @@
5#ifndef A2A_THREAD_UTILS_H5#ifndef A2A_THREAD_UTILS_H
6#define A2A_THREAD_UTILS_H6#define A2A_THREAD_UTILS_H
7 7 
8-#include <pthread.h>
9#include <string>8#include <string>
10 9 
10+#include "platform_compat.h"
11+ 
11namespace A2A {12namespace A2A {
12 13 
13/**14/**
14- * @brief Set the name of the current thread (Linux only)15+ * @brief Set the name of the current thread.
15 * @param name The thread name (max 15 characters + null terminator)16 * @param name The thread name (max 15 characters + null terminator)
16 */17 */
17inline void SetCurrentThreadName(const std::string& name)18inline void SetCurrentThreadName(const std::string& name)
18{19{
19- // pthread_setname_np limits thread names to 16 chars including null terminator20+ Platform::SetCurrentThreadName(name);
20- std::string truncatedName = name.substr(0, 15);
21- (void)pthread_setname_np(pthread_self(), truncatedName.c_str());
22}21}
23 22 
24} // namespace A2A23} // namespace A2A
25 24 
26-#endif // A2A_THREAD_UTILS_H25+#endif // A2A_THREAD_UTILS_H
@@ -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.
28static std::pair<int, int> CreateTestSocketPair()35static 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).
38static int CreateTestEventFd()55static 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.
44static void SleepMs(int ms)62static 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).
311TEST(EventSystemTest, ReadEventFd_Valid)331TEST(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 Tests368// 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__)
809TEST(EventSystemTest, ReadEventFd_MultipleValues)937TEST(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 Tests964// CloseNotifyEventId Tests
@@ -1164,8 +1293,11 @@ TEST(EventSystemTest, AddEvent_InvalidFd)
1164 es.Init();1293 es.Init();
1165 1294 
1166 // Use a closed fd1295 // 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::Test702+} // namespace A2A::Server::Test
@@ -28,7 +28,9 @@ class TcpListenerTest : public ::testing::Test {
28protected:28protected:
29 void SetUp() override29 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+}
@@ -12,6 +12,18 @@
12 12 
13namespace A2A::Test {13namespace A2A::Test {
14 14 
15+namespace {
16+ 
17+constexpr int REFRESH_INITIAL_TIMEOUT_MS = 1000;
18+constexpr int REFRESH_REPEAT_COUNT = 10;
19+constexpr int REFRESH_INTERVAL_MS = 50;
20+constexpr int REFRESH_SETTLE_MS = 250;
21+constexpr int CONCURRENT_REFRESH_COUNT = 50;
22+constexpr int CONCURRENT_REFRESH_INTERVAL_MS = 20;
23+constexpr int CONCURRENT_REFRESH_SETTLE_MS = 300;
24+ 
25+} // namespace
26+ 
15class A2ATimerTest : public ::testing::Test {27class A2ATimerTest : public ::testing::Test {
16protected:28protected:
17 void TearDown() override29 void TearDown() override
@@ -70,6 +82,52 @@ TEST_F(A2ATimerTest, RefreshTimer_DelaysCallback)
70 EXPECT_EQ(fired.load(), 1);82 EXPECT_EQ(fired.load(), 1);
71}83}
72 84 
85+TEST_F(A2ATimerTest, RefreshTimer_RepeatedRefreshFiresOnce)
86+{
87+ std::atomic<int> fired{0};
88+ const int id = A2ATimer::Instance().AddTimer(
89+ REFRESH_INITIAL_TIMEOUT_MS,
90+ [](void* arg) {
91+ (*static_cast<std::atomic<int>*>(arg))++;
92+ },
93+ &fired);
94+ ASSERT_GT(id, 0);
95+ 
96+ // Only the last arming may fire, and it must fire exactly once.
97+ for (int i = 0; i < REFRESH_REPEAT_COUNT; ++i) {
98+ EXPECT_EQ(A2ATimer::Instance().RefreshTimer(id, REFRESH_INTERVAL_MS), 0);
99+ }
100+ 
101+ std::this_thread::sleep_for(std::chrono::milliseconds(REFRESH_SETTLE_MS));
102+ EXPECT_EQ(fired.load(), 1);
103+}
104+ 
105+TEST_F(A2ATimerTest, RefreshTimer_ConcurrentRefreshFiresOnce)
106+{
107+ std::atomic<int> fired{0};
108+ const int id = A2ATimer::Instance().AddTimer(
109+ REFRESH_INITIAL_TIMEOUT_MS,
110+ [](void* arg) {
111+ (*static_cast<std::atomic<int>*>(arg))++;
112+ },
113+ &fired);
114+ ASSERT_GT(id, 0);
115+ 
116+ auto refresher = [&id]() {
117+ for (int i = 0; i < CONCURRENT_REFRESH_COUNT; ++i) {
118+ // Superseded refreshes return -1 by design.
119+ (void)A2ATimer::Instance().RefreshTimer(id, CONCURRENT_REFRESH_INTERVAL_MS);
120+ }
121+ };
122+ std::thread first(refresher);
123+ std::thread second(refresher);
124+ first.join();
125+ second.join();
126+ 
127+ std::this_thread::sleep_for(std::chrono::milliseconds(CONCURRENT_REFRESH_SETTLE_MS));
128+ EXPECT_EQ(fired.load(), 1);
129+}
130+ 
73TEST_F(A2ATimerTest, Stop_IsIdempotent)131TEST_F(A2ATimerTest, Stop_IsIdempotent)
74{132{
75 EXPECT_NO_THROW(A2ATimer::Instance().Stop());133 EXPECT_NO_THROW(A2ATimer::Instance().Stop());