Merged
fix(a2a):adjust timeout config, support idle timeout in stream mode #390
fix(a2a):adjust timeout config, support idle timeout in stream mode #390
Merged
wangweizhenAdd on 12 days ago
Total: 18 files changed+1165-134
@@ -112,7 +112,7 @@ set_target_properties(a2a PROPERTIES
112)112)
113 113 
114if(A2A_ENABLE_EXAMPLES)114if(A2A_ENABLE_EXAMPLES)
115- foreach(_example_target helloworld_client helloworld_server streaming_client streaming_server)115+ foreach(_example_target helloworld_client helloworld_server streaming_client streaming_server timeout_client)
116 if(TARGET ${_example_target})116 if(TARGET ${_example_target})
117 set_target_properties(${_example_target} PROPERTIES117 set_target_properties(${_example_target} PROPERTIES
118 RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/output/bin118 RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/output/bin
@@ -16,6 +16,15 @@ A2A::AgentCard card = cardFuture.get();
16 16 
17默认路径为 `/.well-known/agent-card.json`(A2A 标准推荐方式)。17默认路径为 `/.well-known/agent-card.json`(A2A 标准推荐方式)。
18 18 
19+`GetAgentCard` 可选参数:相对路径与发现超时(秒):
20+ 
21+```cpp
22+// 指定 10s 发现超时(默认 60s,0 = 默认值)
23+auto cardFuture = resolver->GetAgentCard(std::nullopt, 10);
24+```
25+ 
26+`GetAllAgentCards(timeout)` 同样接受发现超时形参,语义与默认值相同。
27+ 
19## 创建客户端28## 创建客户端
20 29 
21```cpp30```cpp
@@ -115,6 +124,34 @@ std::variant<Message, A2AError, std::pair<Task, UpdateEvent>>
115| `supportedTransports` | 客户端支持的传输标签 |124| `supportedTransports` | 客户端支持的传输标签 |
116| `acceptedOutputModes` | 接受的输出模式 |125| `acceptedOutputModes` | 接受的输出模式 |
117| `pushNotificationConfigs` | 默认推送通知配置 |126| `pushNotificationConfigs` | 默认推送通知配置 |
127+| `timeoutSeconds` | 非流式请求总超时(秒,默认 300;<=0 用 SDK 默认值) |
128+| `streamingIdleTimeoutSeconds` | 流式空闲超时(秒,默认 60):相邻数据到达的最大间隔;流式请求无总时长上限 |
129+ 
130+## 超时语义
131+ 
132+超时参数以**秒**为单位,`0` 表示使用默认值。所有超时共享 **1800s 上限**:配置或传入更大的值会按上限截断(记 WARN 日志),不会导致客户端创建失败。每个阶段独立控制:
133+ 
134+| 阶段 | 配置入口 | 默认值 | 语义 |
135+|------|----------|--------|------|
136+| AgentCard 发现 | `A2ACardResolver::GetAgentCard(path, timeout)` / `GetAllAgentCards(timeout)` | 60s | 发现请求总超时 |
137+| TCP/TLS 连接 | 传输层内部(`LibcurlConn`) | 30s | 连接建立超时 |
138+| 非流式请求 | `ClientConfig::timeoutSeconds`,可被每次调用的 `timeout` 形参覆盖 | 300s | 请求总超时(含等待响应) |
139+| 流式空闲 | `ClientConfig::streamingIdleTimeoutSeconds`,可被 `SendMessage`/`Resubscribe` 的 `timeout` 形参覆盖 | 60s | 相邻数据到达的最大间隔,超时断开流 |
140+ 
141+超时发生时通过 `A2AClientTimeoutError`(code `-32101`)抛出,错误消息携带阶段与已耗时,例如:
142+ 
143+```
144+request timed out [stage=stream-idle, idle=60023ms, elapsed=60023ms]
145+request timed out [stage=waiting-response-body, elapsed=300012ms]
146+```
147+ 
148+超时行为可用自带桩服务的示例直接验证(无需真实 server):
149+ 
150+```bash
151+./output/bin/timeout_client # 退出码 = 失败场景数,0 = 全部通过
152+```
153+ 
154+该示例内置"只 accept、永不回包"的 TCP 桩,覆盖发现超时、非流式 per-call/config 超时、流式空闲超时(config/per-call)共 5 个场景,见 `examples/timeout_client.cpp`。
118 155 
119## 日志156## 日志
120 157 
@@ -99,6 +99,11 @@ std::variant<Message, A2AError, std::pair<Task, UpdateEvent>>
99| 任务不存在 | code 常为 `TASK_NOT_FOUND`(-32001) | 校验 taskId |99| 任务不存在 | code 常为 `TASK_NOT_FOUND`(-32001) | 校验 taskId |
100| HTTP 连接失败 | `A2AClientHTTPError` | 检查网络与 `LD_LIBRARY_PATH` |100| HTTP 连接失败 | `A2AClientHTTPError` | 检查网络与 `LD_LIBRARY_PATH` |
101| Card 解析失败 | `A2AClientJSONError` | 检查 `/.well-known/agent-card.json` |101| Card 解析失败 | `A2AClientJSONError` | 检查 `/.well-known/agent-card.json` |
102+| 请求超时 | `A2AClientTimeoutError`(`A2A_REQUEST_TIMEOUT` -32101),消息含 `stage` 与 `elapsed` | 按阶段定位:`connect-or-waiting-response-headers` / `waiting-response-body` / `stream-idle` |
103+ 
104+> **超时错误信息**:传输层超时会携带阶段与已消耗时间,例如
105+> `request timed out [stage=stream-idle, idle=60023ms, elapsed=60023ms]`。
106+> 分阶段超时配置见 [client.md - 超时语义](api/client.md#超时语义)。
102 107 
103## Server 侧108## Server 侧
104 109 
@@ -8,6 +8,11 @@ if(A2A_BUILD_CLIENT)
8 add_executable(streaming_client streaming_client.cpp)8 add_executable(streaming_client streaming_client.cpp)
9 set_property(TARGET streaming_client PROPERTY C_STANDARD 11)9 set_property(TARGET streaming_client PROPERTY C_STANDARD 11)
10 target_link_libraries(streaming_client PRIVATE a2a)10 target_link_libraries(streaming_client PRIVATE a2a)
11+ 
12+ # 超时功能打桩验证:自带"只 accept、永不回包"的桩服务,无需真实 server
13+ add_executable(timeout_client timeout_client.cpp)
14+ set_property(TARGET timeout_client PROPERTY C_STANDARD 11)
15+ target_link_libraries(timeout_client PRIVATE a2a)
11endif()16endif()
12 17 
13if(A2A_BUILD_SERVER)18if(A2A_BUILD_SERVER)
AA2A/cpp-sdk/examples/timeout_client.cpp+473-0File content is under review, please try again later
@@ -13,6 +13,9 @@
13 13 
14namespace A2A::Client {14namespace A2A::Client {
15 15 
16+/** @brief Default AgentCard discovery timeout in seconds. */
17+constexpr int DEFAULT_CARD_TIMEOUT_SECONDS = 60;
18+ 
16/**19/**
17 * @brief Resolves AgentCard documents from a remote or local source.20 * @brief Resolves AgentCard documents from a remote or local source.
18 * @note 代理卡片解析器抽象接口。21 * @note 代理卡片解析器抽象接口。
@@ -25,19 +28,23 @@ public:
25 /**28 /**
26 * @brief Fetch an agent card from a relative path.29 * @brief Fetch an agent card from a relative path.
27 * @param[in] relativeCardPath Optional path relative to the resolver base URL.30 * @param[in] relativeCardPath Optional path relative to the resolver base URL.
31+ * @param[in] timeout Discovery request timeout in seconds (0 = SDK default 60s).
28 * @return Future that completes with the resolved AgentCard.32 * @return Future that completes with the resolved AgentCard.
29 * @throws A2AClientHTTPError on non-2xx HTTP status.33 * @throws A2AClientHTTPError on non-2xx HTTP status.
30 * @throws A2AClientJSONError on invalid card JSON.34 * @throws A2AClientJSONError on invalid card JSON.
31 */35 */
32 virtual std::future<AgentCard> GetAgentCard(36 virtual std::future<AgentCard> GetAgentCard(
33- const std::optional<std::string>& relativeCardPath = std::nullopt) const = 0;37+ const std::optional<std::string>& relativeCardPath = std::nullopt,
38+ int timeout = DEFAULT_CARD_TIMEOUT_SECONDS) const = 0;
34 39 
35 /**40 /**
36 * @brief Fetch all agent cards from the resolver source.41 * @brief Fetch all agent cards from the resolver source.
42+ * @param[in] timeout Discovery request timeout in seconds (0 = SDK default 60s).
37 * @return Future that completes with a vector of AgentCard objects.43 * @return Future that completes with a vector of AgentCard objects.
38 * @throws A2AClientHTTPError on transport failure.44 * @throws A2AClientHTTPError on transport failure.
39 */45 */
40- virtual std::future<std::vector<AgentCard>> GetAllAgentCards() const = 0;46+ virtual std::future<std::vector<AgentCard>> GetAllAgentCards(
47+ int timeout = DEFAULT_CARD_TIMEOUT_SECONDS) const = 0;
41};48};
42 49 
43} // namespace A2A::Client50} // namespace A2A::Client
MA2A/cpp-sdk/include/client/client.h+15-2File content is under review, please try again later
@@ -28,6 +28,7 @@ public:
28 * @param[in] agentCardPath Path to the agent card (default: /.well-known/agent-card.json).28 * @param[in] agentCardPath Path to the agent card (default: /.well-known/agent-card.json).
29 * @param[in] httpKwargs Extra HTTP headers or options.29 * @param[in] httpKwargs Extra HTTP headers or options.
30 * @return Shared pointer to the created resolver.30 * @return Shared pointer to the created resolver.
31+ * @note The discovery timeout is passed per call via A2ACardResolver::GetAgentCard().
31 */32 */
32 static std::shared_ptr<A2ACardResolver> Build(std::string baseUrl, std::string agentCardPath,33 static std::shared_ptr<A2ACardResolver> Build(std::string baseUrl, std::string agentCardPath,
33 const std::map<std::string, std::string>& httpKwargs = {});34 const std::map<std::string, std::string>& httpKwargs = {});
@@ -55,18 +55,17 @@ public:
55 * @param[in] message message to send.55 * @param[in] message message to send.
56 * @param[in] headers headers of connection56 * @param[in] headers headers of connection
57 * @param[in] userData user data57 * @param[in] userData user data
58+ * @param[in] timeoutSecs per-request timeout in seconds (0 = connection default).
59+ * Non-streaming requests: total request timeout.
60+ * Streaming requests: idle timeout between data arrivals.
58 */61 */
59 virtual int SendMessage(const std::string& message, const std::map<std::string, std::string>& headers,62 virtual int SendMessage(const std::string& message, const std::map<std::string, std::string>& headers,
60- std::shared_ptr<UserData> userData, int timeout) = 0;63+ std::shared_ptr<UserData> userData, int timeoutSecs) = 0;
61 64 
62 /**65 /**
63 * @brief Set callback interface for handling connection events.66 * @brief Set callback interface for handling connection events.
64 */67 */
65 virtual void SetCallback(std::shared_ptr<ConnCallback> callback) = 0;68 virtual void SetCallback(std::shared_ptr<ConnCallback> callback) = 0;
66- 
67- virtual void FinishRequest(int timerId) = 0;
68- 
69- virtual void RefreshRequest(int timerId, int timeout) = 0;
70};69};
71 70 
72} // namespace A2A71} // namespace A2A
MA2A/cpp-sdk/src/client/connection/libcurl_conn.cpp+234-72File content is under review, please try again later
MA2A/cpp-sdk/src/client/connection/libcurl_conn.h+101-15File content is under review, please try again later
@@ -46,7 +46,7 @@ HttpCardResolver::HttpCardResolver(
46}46}
47 47 
48std::future<AgentCard> HttpCardResolver::GetAgentCard([[maybe_unused]] const std::optional<std::string>&48std::future<AgentCard> HttpCardResolver::GetAgentCard([[maybe_unused]] const std::optional<std::string>&
49- relativeCardPath) const49+ relativeCardPath, int timeout) const
50{50{
51 std::string requestId = GenerateUuid();51 std::string requestId = GenerateUuid();
52 std::shared_ptr<std::promise<AgentCard>> promise;52 std::shared_ptr<std::promise<AgentCard>> promise;
@@ -57,8 +57,9 @@ std::future<AgentCard> HttpCardResolver::GetAgentCard([[maybe_unused]] const std
57 pendingPromises_[requestId] = promise;57 pendingPromises_[requestId] = promise;
58 }58 }
59 59 
60- // send request60+ // send request (discovery timeout; <=0 = SDK default 60s, not the 300s
61- transport_->GetCard(requestId, nullptr, 0);61+ // transport-wide default, since discovery should fail fast)
62+ transport_->GetCard(requestId, nullptr, timeout > 0 ? timeout : DEFAULT_CARD_TIMEOUT_SECONDS);
62 } catch (const std::bad_alloc& e) {63 } catch (const std::bad_alloc& e) {
63 A2A_LOG(A2A_LOG_LEVEL::ERROR, std::string("exception occured: ") + e.what());64 A2A_LOG(A2A_LOG_LEVEL::ERROR, std::string("exception occured: ") + e.what());
64 std::promise<AgentCard> fallbackPromise;65 std::promise<AgentCard> fallbackPromise;
@@ -75,9 +76,9 @@ std::future<AgentCard> HttpCardResolver::GetAgentCard([[maybe_unused]] const std
75 return promise->get_future();76 return promise->get_future();
76}77}
77 78 
78-std::future<std::vector<AgentCard>> HttpCardResolver::GetAllAgentCards() const79+std::future<std::vector<AgentCard>> HttpCardResolver::GetAllAgentCards(int timeout) const
79{80{
80- auto outerCardFuture = GetAgentCard(std::nullopt);81+ auto outerCardFuture = GetAgentCard(std::nullopt, timeout);
81 return std::async(std::launch::async,82 return std::async(std::launch::async,
82 [cardFuture = std::move(outerCardFuture)]() mutable -> std::vector<AgentCard> {83 [cardFuture = std::move(outerCardFuture)]() mutable -> std::vector<AgentCard> {
83 AgentCard card = cardFuture.get();84 AgentCard card = cardFuture.get();
@@ -20,15 +20,22 @@ namespace A2A::Client {
20 20 
21class HttpCardResolver : public A2ACardResolver {21class HttpCardResolver : public A2ACardResolver {
22public:22public:
23+ /**
24+ * @brief Construct an HTTP card resolver.
25+ * @param[in] baseUrl Server base URL.
26+ * @param[in] relativeCardPath Optional card path relative to the base URL.
27+ * @param[in] httpKwargs Extra HTTP headers or options.
28+ */
23 HttpCardResolver(std::string baseUrl, const std::optional<std::string>& relativeCardPath,29 HttpCardResolver(std::string baseUrl, const std::optional<std::string>& relativeCardPath,
24 std::map<std::string, std::string> httpKwargs = {});30 std::map<std::string, std::string> httpKwargs = {});
25 31 
26 ~HttpCardResolver() override = default;32 ~HttpCardResolver() override = default;
27 33 
28- std::future<AgentCard> GetAgentCard(34+ std::future<AgentCard> GetAgentCard(const std::optional<std::string>& relativeCardPath = std::nullopt,
29- const std::optional<std::string>& relativeCardPath = std::nullopt) const override;35+ int timeout = DEFAULT_CARD_TIMEOUT_SECONDS) const override;
30 36 
31- std::future<std::vector<AgentCard>> GetAllAgentCards() const override;37+ std::future<std::vector<AgentCard>> GetAllAgentCards(
38+ int timeout = DEFAULT_CARD_TIMEOUT_SECONDS) const override;
32 39 
33protected:40protected:
34 std::string baseUrl_;41 std::string baseUrl_;
MA2A/cpp-sdk/src/client/jsonrpc_transport_impl.cpp+22-17File content is under review, please try again later
@@ -50,13 +50,15 @@ constexpr size_t HTTP_QUEUE_MAX_BATCH_SIZE = 64;
50constexpr int HTTPS_READ_BUFFER_SIZE = 4096;50constexpr int HTTPS_READ_BUFFER_SIZE = 4096;
51constexpr int HTTP_LISTEN_BACKLOG = 128;51constexpr int HTTP_LISTEN_BACKLOG = 128;
52 52 
53+// Public client APIs express timeouts in seconds; the HTTP transport layer
54+// works in milliseconds. This is the single conversion factor between them.
55+constexpr int SECONDS_TO_MS = 1000;
56+ 
53struct UserData {57struct UserData {
54 std::string requestId = "";58 std::string requestId = "";
55 std::string method;59 std::string method;
56 bool isStream = false;60 bool isStream = false;
57 bool valid = true;61 bool valid = true;
58- int timerId = -1;
59- int timeout = 0;
60};62};
61 63 
62struct BaseResponse {64struct BaseResponse {
MA2A/cpp-sdk/src/shared/http_common.h+1-0File content is under review, please try again later
@@ -38,8 +38,6 @@ public:
38 (override));38 (override));
39 MOCK_METHOD(void, SetCallback, (std::shared_ptr<ConnCallback>), (override));39 MOCK_METHOD(void, SetCallback, (std::shared_ptr<ConnCallback>), (override));
40 MOCK_METHOD(void, Terminate, (), (override));40 MOCK_METHOD(void, Terminate, (), (override));
41- MOCK_METHOD(void, FinishRequest, (int), (override));
42- MOCK_METHOD(void, RefreshRequest, (int timerId, int timeout), (override));
43};41};
44 42 
45// ===========================================================================43// ===========================================================================
MA2A/cpp-sdk/tests/ut/client/test_libcurl_conn.cpp+237-8File content is under review, please try again later