Skip to main content

rap_client/
notifier.rs

1/// Best-effort lifecycle notifications to RAP tool servers.
2use std::collections::HashMap;
3
4use crate::http::HttpClient;
5
6/// Sends best-effort notifications to all configured RAP tool servers.
7#[derive(Clone)]
8pub struct RapNotifier<H: HttpClient> {
9    server_urls: Vec<String>,
10    client: H,
11}
12
13impl<H: HttpClient> RapNotifier<H> {
14    /// Create a notifier for the given server URLs.
15    pub fn new(server_urls: Vec<String>, client: H) -> Self {
16        Self {
17            server_urls,
18            client,
19        }
20    }
21
22    /// Best-effort notification that a thread has been closed.
23    pub async fn notify_thread_closed(&self, thread_id: &rap_protocol::ThreadId<str>) {
24        let payload = serde_json::json!({ "thread_id": thread_id }).to_string();
25        for url in &self.server_urls {
26            let endpoint = format!("{}/close_thread", url.trim_end_matches('/'));
27            match self.client.post(&endpoint, &payload).await {
28                Ok(status) => {
29                    tracing::info!("Notified {} of thread close (status: {})", endpoint, status);
30                }
31                Err(e) => {
32                    tracing::warn!("Failed to notify {} of thread close: {}", endpoint, e);
33                }
34            }
35        }
36    }
37
38    /// Best-effort notification that a tool call has been cancelled.
39    pub async fn notify_tool_cancelled(
40        &self,
41        thread_id: &rap_protocol::ThreadId<str>,
42        tool_call_id: &rap_protocol::ToolCallId<str>,
43    ) {
44        let payload = serde_json::json!({
45            "thread_id": thread_id,
46            "tool_call_id": tool_call_id,
47        })
48        .to_string();
49        for url in &self.server_urls {
50            let endpoint = format!("{}/cancel_tool_call", url.trim_end_matches('/'));
51            match self.client.post(&endpoint, &payload).await {
52                Ok(status) => {
53                    tracing::info!(
54                        "Notified {} of tool cancellation (status: {})",
55                        endpoint,
56                        status
57                    );
58                }
59                Err(e) => {
60                    tracing::warn!("Failed to notify {} of tool cancellation: {}", endpoint, e);
61                }
62            }
63        }
64    }
65
66    /// Request RAP servers to migrate their state to destination servers.
67    /// `servers_needing_migration` is a list of `(config_id, source_url)` pairs.
68    /// `destination_urls` maps config ID → destination server URL.
69    pub async fn request_migration(
70        &self,
71        session_id: &rap_protocol::ThreadId<str>,
72        servers_needing_migration: &[(String, String)],
73        destination_urls: &HashMap<String, String>,
74    ) -> Result<(), Vec<String>> {
75        let mut errors = Vec::new();
76        for (id, url) in servers_needing_migration {
77            let endpoint = format!("{}/migrate", url.trim_end_matches('/'));
78            let dest_url = destination_urls.get(id).cloned().unwrap_or_default();
79            let payload = serde_json::json!({
80                "session_id": session_id,
81                "destination_url": dest_url,
82            })
83            .to_string();
84            match self.client.post(&endpoint, &payload).await {
85                Ok(status) if (200..300).contains(&status) => {
86                    tracing::info!(
87                        "Migration request to {} succeeded (status: {})",
88                        endpoint,
89                        status
90                    );
91                }
92                Ok(status) => {
93                    errors.push(format!(
94                        "Migration to {} returned status {}",
95                        endpoint, status
96                    ));
97                }
98                Err(e) => {
99                    errors.push(format!("Migration to {} failed: {}", endpoint, e));
100                }
101            }
102        }
103        if errors.is_empty() {
104            Ok(())
105        } else {
106            Err(errors)
107        }
108    }
109}