a2a_protocol_client/methods/
tasks.rs1use a2a_protocol_types::{
12 CancelTaskParams, ListTasksParams, Task, TaskIdParams, TaskListResponse, TaskQueryParams,
13};
14
15use crate::client::A2aClient;
16use crate::error::{ClientError, ClientResult};
17use crate::interceptor::{ClientRequest, ClientResponse};
18use crate::streaming::EventStream;
19
20impl A2aClient {
21 pub async fn get_task(&self, params: TaskQueryParams) -> ClientResult<Task> {
30 self.read_task(params, &[]).await
31 }
32
33 pub async fn list_tasks(&self, mut params: ListTasksParams) -> ClientResult<TaskListResponse> {
50 const METHOD: &str = "ListTasks";
51
52 params.tenant = self.tenant_or_default(params.tenant.take())?;
53 params.status_timestamp_after = params
54 .status_timestamp_after
55 .take()
56 .map(|ts| super::status_timestamp::utc(&ts))
57 .transpose()?;
58 let params_value = serde_json::to_value(¶ms).map_err(ClientError::Serialization)?;
59
60 let mut req = ClientRequest::new(METHOD, params_value);
61 self.interceptors.run_before(&mut req).await?;
62
63 self.send_decoded(METHOD, &mut req, |result| {
64 let page = serde_json::from_value::<TaskListResponse>(result)
65 .map_err(ClientError::Serialization)?;
66 crate::received::page(&page)?;
67 self.content.page(&page)?;
68 Ok(page)
69 })
70 .await
71 }
72
73 pub async fn cancel_task(&self, id: impl Into<String>) -> ClientResult<Task> {
84 self.cancel_task_in(None, id.into()).await
85 }
86
87 pub(crate) async fn cancel_task_in(
91 &self,
92 tenant: Option<String>,
93 id: String,
94 ) -> ClientResult<Task> {
95 const METHOD: &str = "CancelTask";
96
97 let params = {
98 let mut built = CancelTaskParams::new(id);
99 built.tenant = self.tenant_or_default(tenant)?;
100 built
101 };
102 let params_value = serde_json::to_value(¶ms).map_err(ClientError::Serialization)?;
103
104 let mut req = ClientRequest::new(METHOD, params_value);
105 self.interceptors.run_before(&mut req).await?;
106
107 self.send_decoded(METHOD, &mut req, |result| {
108 let task =
109 serde_json::from_value::<Task>(result).map_err(ClientError::Serialization)?;
110 crate::received::task(METHOD, &task)?;
111 self.content.task(&task)?;
112 Ok(task)
113 })
114 .await
115 }
116
117 pub async fn subscribe_to_task(&self, id: impl Into<String>) -> ClientResult<EventStream> {
132 self.subscribe(id.into(), None).await
133 }
134
135 pub async fn subscribe_to_task_from(
170 &self,
171 id: impl Into<String>,
172 last_event_id: impl Into<String>,
173 ) -> ClientResult<EventStream> {
174 self.subscribe(id.into(), Some(last_event_id.into())).await
175 }
176
177 async fn subscribe(
178 &self,
179 id: String,
180 last_event_id: Option<String>,
181 ) -> ClientResult<EventStream> {
182 self.subscribe_in(None, id, last_event_id).await
183 }
184
185 pub(crate) async fn subscribe_in(
189 &self,
190 tenant: Option<String>,
191 id: String,
192 last_event_id: Option<String>,
193 ) -> ClientResult<EventStream> {
194 const METHOD: &str = "SubscribeToTask";
195 self.require_declared(crate::declared::Capability::Streaming, METHOD)?;
196
197 let params = {
198 let mut built = TaskIdParams::new(id);
199 built.tenant = self.tenant_or_default(tenant)?;
200 built
201 };
202 let params_value = serde_json::to_value(¶ms).map_err(ClientError::Serialization)?;
203
204 let mut req = ClientRequest::new(METHOD, params_value);
205 if let Some(last_event_id) = last_event_id {
206 req.extra_headers
209 .insert("last-event-id".to_owned(), last_event_id);
210 }
211 self.interceptors.run_before(&mut req).await?;
212
213 let stream = self.send_streaming_intercepted(METHOD, &mut req).await?;
214 let mut stream = self.configure_stream(stream);
215
216 let resp = ClientResponse {
219 method: METHOD.to_owned(),
220 result: serde_json::Value::Null,
221 status_code: 200,
222 };
223 if let Err(e) = self.interceptors.run_after(&resp).await {
224 stream.fail_call(&e);
225 return Err(e);
226 }
227
228 Ok(stream)
229 }
230}
231
232#[cfg(test)]
235mod tests {
236 use std::collections::HashMap;
237 use std::future::Future;
238 use std::pin::Pin;
239
240 use a2a_protocol_types::{ListTasksParams, TaskQueryParams};
241
242 use crate::ClientBuilder;
243 use crate::error::{ClientError, ClientResult};
244 use crate::streaming::EventStream;
245 use crate::transport::Transport;
246
247 struct MockTransport {
250 response: serde_json::Value,
251 }
252
253 impl MockTransport {
254 fn new(response: serde_json::Value) -> Self {
255 Self { response }
256 }
257 }
258
259 impl Transport for MockTransport {
260 fn send_request<'a>(
261 &'a self,
262 _method: &'a str,
263 _params: serde_json::Value,
264 _extra_headers: &'a HashMap<String, String>,
265 ) -> Pin<Box<dyn Future<Output = ClientResult<serde_json::Value>> + Send + 'a>> {
266 let resp = self.response.clone();
267 Box::pin(async move { Ok(resp) })
268 }
269
270 fn send_streaming_request<'a>(
271 &'a self,
272 _method: &'a str,
273 _params: serde_json::Value,
274 _extra_headers: &'a HashMap<String, String>,
275 ) -> Pin<Box<dyn Future<Output = ClientResult<EventStream>> + Send + 'a>> {
276 Box::pin(async move {
277 Err(ClientError::Transport(
278 "mock: streaming not supported".into(),
279 ))
280 })
281 }
282 }
283
284 fn make_client(transport: impl Transport) -> crate::A2aClient {
285 ClientBuilder::new("http://localhost:8080")
286 .with_custom_transport(transport)
287 .build()
288 .expect("build client")
289 }
290
291 fn task_json() -> serde_json::Value {
292 serde_json::json!({
293 "id": "task-1",
294 "contextId": "ctx-1",
295 "status": {
296 "state": "TASK_STATE_COMPLETED"
297 }
298 })
299 }
300
301 #[tokio::test]
302 async fn get_task_success() {
303 let transport = MockTransport::new(task_json());
304 let client = make_client(transport);
305
306 let params = TaskQueryParams::new("task-1");
307 let task = client.get_task(params).await.unwrap();
308 assert_eq!(task.id.as_ref(), "task-1");
309 }
310
311 #[tokio::test]
312 async fn list_tasks_success() {
313 let response = serde_json::json!({
314 "tasks": [
315 {
316 "id": "task-1",
317 "contextId": "ctx-1",
318 "status": { "state": "TASK_STATE_COMPLETED" }
319 },
320 {
321 "id": "task-2",
322 "contextId": "ctx-2",
323 "status": { "state": "TASK_STATE_WORKING" }
324 }
325 ]
326 });
327 let transport = MockTransport::new(response);
328 let client = make_client(transport);
329
330 let params = ListTasksParams::default();
331 let result = client.list_tasks(params).await.unwrap();
332 assert_eq!(result.tasks.len(), 2);
333 assert_eq!(result.tasks[0].id.as_ref(), "task-1");
334 }
335
336 #[tokio::test]
337 async fn cancel_task_success() {
338 let transport = MockTransport::new(task_json());
339 let client = make_client(transport);
340
341 let task = client.cancel_task("task-1").await.unwrap();
342 assert_eq!(task.id.as_ref(), "task-1");
343 }
344
345 #[allow(clippy::unused_async_trait_impl)]
349 #[tokio::test]
350 async fn subscribe_to_task_calls_after_interceptor() {
351 use std::sync::Arc;
352 use std::sync::atomic::{AtomicUsize, Ordering};
353
354 use crate::interceptor::{CallInterceptor, ClientRequest, ClientResponse};
355
356 struct StreamingOkTransport;
357
358 impl Transport for StreamingOkTransport {
359 fn send_request<'a>(
360 &'a self,
361 _method: &'a str,
362 _params: serde_json::Value,
363 _extra_headers: &'a HashMap<String, String>,
364 ) -> Pin<Box<dyn Future<Output = ClientResult<serde_json::Value>> + Send + 'a>>
365 {
366 Box::pin(async move { Ok(serde_json::Value::Null) })
367 }
368
369 fn send_streaming_request<'a>(
370 &'a self,
371 _method: &'a str,
372 _params: serde_json::Value,
373 _extra_headers: &'a HashMap<String, String>,
374 ) -> Pin<Box<dyn Future<Output = ClientResult<EventStream>> + Send + 'a>> {
375 Box::pin(async move {
376 let (tx, rx) = tokio::sync::mpsc::channel(8);
377 drop(tx);
378 Ok(EventStream::new(rx))
379 })
380 }
381 }
382
383 struct CountingInterceptor {
384 before_count: Arc<AtomicUsize>,
385 after_count: Arc<AtomicUsize>,
386 }
387
388 impl CallInterceptor for CountingInterceptor {
389 async fn before<'a>(&'a self, _req: &'a mut ClientRequest) -> ClientResult<()> {
390 self.before_count.fetch_add(1, Ordering::SeqCst);
391 Ok(())
392 }
393 async fn after<'a>(&'a self, _resp: &'a ClientResponse) -> ClientResult<()> {
394 self.after_count.fetch_add(1, Ordering::SeqCst);
395 Ok(())
396 }
397 }
398
399 let before = Arc::new(AtomicUsize::new(0));
400 let after = Arc::new(AtomicUsize::new(0));
401 let interceptor = CountingInterceptor {
402 before_count: Arc::clone(&before),
403 after_count: Arc::clone(&after),
404 };
405
406 let client = ClientBuilder::new("http://localhost:8080")
407 .with_custom_transport(StreamingOkTransport)
408 .with_interceptor(interceptor)
409 .build()
410 .expect("build");
411
412 let result = client.subscribe_to_task("task-1").await;
413 assert!(result.is_ok(), "subscribe should succeed");
414 assert_eq!(before.load(Ordering::SeqCst), 1, "before should be called");
415 assert_eq!(
416 after.load(Ordering::SeqCst),
417 1,
418 "after should be called for subscribe streaming"
419 );
420 }
421
422 #[tokio::test]
423 async fn subscribe_to_task_returns_transport_error() {
424 let transport = MockTransport::new(serde_json::Value::Null);
428 let client = make_client(transport);
429
430 let err = client.subscribe_to_task("task-1").await.unwrap_err();
431 assert!(
432 matches!(err, ClientError::Transport(ref msg) if msg.contains("streaming not supported")),
433 "expected Transport error, got {err:?}"
434 );
435 }
436}