1use std::time::Duration;
4
5use serde_json::{json, Map, Value};
6
7use crate::client::Client;
8use crate::errors::Result;
9use crate::session::connect_with_retries;
10
11#[derive(Debug, Clone)]
13pub struct AsyncCommandClient {
14 ws_url: String,
15 timeout: Duration,
16}
17
18impl AsyncCommandClient {
19 pub fn new(ws_url: impl Into<String>) -> Self {
21 Self {
22 ws_url: ws_url.into(),
23 timeout: Duration::from_secs(30),
24 }
25 }
26
27 pub fn with_timeout(mut self, timeout: Duration) -> Self {
29 self.timeout = timeout;
30 self
31 }
32
33 async fn with_client<F, Fut>(&self, f: F) -> Result<Map<String, Value>>
34 where
35 F: FnOnce(Client) -> Fut,
36 Fut: std::future::Future<Output = Result<Map<String, Value>>>,
37 {
38 let client = Client::new(&self.ws_url);
39 connect_with_retries(&client, 5, Duration::from_millis(250)).await?;
40 let result = f(client.clone()).await;
41 let _ = client.close().await;
42 result
43 }
44
45 async fn rpc(&self, method: &str, params: Map<String, Value>) -> Result<Map<String, Value>> {
46 let timeout = self.timeout;
47 self.with_client(|c| async move { c.request(method, params, timeout).await })
48 .await
49 }
50
51 pub async fn request(
53 &self,
54 method: &str,
55 params: Map<String, Value>,
56 ) -> Result<Map<String, Value>> {
57 self.rpc(method, params).await
58 }
59
60 pub async fn job_create(
62 &self,
63 goal: &str,
64 rail_id: &str,
65 workspace: Option<&str>,
66 ) -> Result<Map<String, Value>> {
67 if goal.trim().is_empty() {
68 return Err(crate::errors::Error::msg("goal is required"));
69 }
70 if rail_id.trim().is_empty() {
71 return Err(crate::errors::Error::msg("rail_id is required"));
72 }
73 let mut params = Map::new();
74 params.insert("goal".into(), json!(goal));
75 params.insert("rail_id".into(), json!(rail_id));
76 if let Some(ws) = workspace {
77 params.insert("workspace".into(), json!(ws));
78 }
79 self.rpc("job_create", params).await
80 }
81
82 pub async fn job_status(&self, job_id: &str) -> Result<Map<String, Value>> {
84 let mut params = Map::new();
85 params.insert("job_id".into(), json!(job_id));
86 self.rpc("job_status", params).await
87 }
88
89 pub async fn job_pause(&self, job_id: &str) -> Result<Map<String, Value>> {
91 let mut params = Map::new();
92 params.insert("job_id".into(), json!(job_id));
93 self.rpc("job_pause", params).await
94 }
95
96 pub async fn job_resume(&self, job_id: &str) -> Result<Map<String, Value>> {
98 let mut params = Map::new();
99 params.insert("job_id".into(), json!(job_id));
100 self.rpc("job_resume", params).await
101 }
102
103 pub async fn job_cancel(&self, job_id: &str) -> Result<Map<String, Value>> {
105 let mut params = Map::new();
106 params.insert("job_id".into(), json!(job_id));
107 self.rpc("job_cancel", params).await
108 }
109
110 pub async fn job_dag(&self, job_id: &str) -> Result<Map<String, Value>> {
112 let mut params = Map::new();
113 params.insert("job_id".into(), json!(job_id));
114 self.rpc("job_dag", params).await
115 }
116
117 pub async fn job_guidance(
119 &self,
120 job_id: &str,
121 content: &str,
122 goal_id: Option<&str>,
123 ) -> Result<Map<String, Value>> {
124 let mut params = Map::new();
125 params.insert("job_id".into(), json!(job_id));
126 params.insert("content".into(), json!(content));
127 if let Some(g) = goal_id {
128 params.insert("goal_id".into(), json!(g));
129 }
130 self.rpc("job_guidance", params).await
131 }
132
133 pub async fn cron_add(&self, text: &str, priority: Option<i32>) -> Result<Map<String, Value>> {
135 let mut params = Map::new();
136 params.insert("text".into(), json!(text));
137 if let Some(p) = priority {
138 params.insert("priority".into(), json!(p));
139 }
140 let result = self.rpc("cron_add", params).await?;
141 Ok(normalize_cron_add(result))
142 }
143
144 pub async fn cron_list(&self, status: Option<&str>) -> Result<Map<String, Value>> {
146 let mut params = Map::new();
147 if let Some(s) = status {
148 params.insert("status".into(), json!(s));
149 }
150 self.rpc("cron_list", params).await
151 }
152
153 pub async fn cron_show(&self, job_id: &str) -> Result<Map<String, Value>> {
155 let mut params = Map::new();
156 params.insert("job_id".into(), json!(job_id));
157 let result = self.rpc("cron_show", params).await?;
158 Ok(normalize_cron_show(result))
159 }
160
161 pub async fn cron_cancel(&self, job_id: &str) -> Result<Map<String, Value>> {
163 let mut params = Map::new();
164 params.insert("job_id".into(), json!(job_id));
165 self.rpc("cron_cancel", params).await
166 }
167
168 pub async fn memory_stats(&self, mode: &str) -> Result<Map<String, Value>> {
170 let mut params = Map::new();
171 params.insert("mode".into(), json!(mode));
172 self.rpc("memory_stats", params).await
173 }
174}
175
176#[derive(Debug, Clone)]
178pub struct CommandClient {
179 inner: AsyncCommandClient,
180}
181
182impl CommandClient {
183 pub fn new(ws_url: impl Into<String>) -> Self {
185 Self {
186 inner: AsyncCommandClient::new(ws_url),
187 }
188 }
189
190 pub fn with_timeout(mut self, timeout: Duration) -> Self {
192 self.inner = self.inner.with_timeout(timeout);
193 self
194 }
195
196 fn block<F, T>(&self, f: F) -> Result<T>
197 where
198 F: std::future::Future<Output = Result<T>>,
199 {
200 match tokio::runtime::Handle::try_current() {
201 Ok(handle) => tokio::task::block_in_place(|| handle.block_on(f)),
202 Err(_) => {
203 let rt = tokio::runtime::Builder::new_current_thread()
204 .enable_all()
205 .build()
206 .map_err(|e| crate::errors::Error::msg(e.to_string()))?;
207 rt.block_on(f)
208 }
209 }
210 }
211
212 pub fn job_create(
214 &self,
215 goal: &str,
216 rail_id: &str,
217 workspace: Option<&str>,
218 ) -> Result<Map<String, Value>> {
219 self.block(self.inner.job_create(goal, rail_id, workspace))
220 }
221
222 pub fn job_status(&self, job_id: &str) -> Result<Map<String, Value>> {
224 self.block(self.inner.job_status(job_id))
225 }
226
227 pub fn job_pause(&self, job_id: &str) -> Result<Map<String, Value>> {
229 self.block(self.inner.job_pause(job_id))
230 }
231
232 pub fn job_resume(&self, job_id: &str) -> Result<Map<String, Value>> {
234 self.block(self.inner.job_resume(job_id))
235 }
236
237 pub fn job_cancel(&self, job_id: &str) -> Result<Map<String, Value>> {
239 self.block(self.inner.job_cancel(job_id))
240 }
241
242 pub fn job_dag(&self, job_id: &str) -> Result<Map<String, Value>> {
244 self.block(self.inner.job_dag(job_id))
245 }
246
247 pub fn job_guidance(
249 &self,
250 job_id: &str,
251 content: &str,
252 goal_id: Option<&str>,
253 ) -> Result<Map<String, Value>> {
254 self.block(self.inner.job_guidance(job_id, content, goal_id))
255 }
256
257 pub fn cron_add(&self, text: &str, priority: Option<i32>) -> Result<Map<String, Value>> {
259 self.block(self.inner.cron_add(text, priority))
260 }
261
262 pub fn cron_list(&self, status: Option<&str>) -> Result<Map<String, Value>> {
264 self.block(self.inner.cron_list(status))
265 }
266
267 pub fn cron_show(&self, job_id: &str) -> Result<Map<String, Value>> {
269 self.block(self.inner.cron_show(job_id))
270 }
271
272 pub fn cron_cancel(&self, job_id: &str) -> Result<Map<String, Value>> {
274 self.block(self.inner.cron_cancel(job_id))
275 }
276
277 pub fn memory_stats(&self, mode: &str) -> Result<Map<String, Value>> {
279 self.block(self.inner.memory_stats(mode))
280 }
281
282 pub fn request(&self, method: &str, params: Map<String, Value>) -> Result<Map<String, Value>> {
284 self.block(self.inner.request(method, params))
285 }
286}
287
288fn normalize_cron_add(result: Map<String, Value>) -> Map<String, Value> {
289 if result.contains_key("job") {
290 return result;
291 }
292 let job_id = result.get("job_id").or_else(|| result.get("id")).cloned();
293 if let Some(id) = job_id {
294 let mut job = result.clone();
295 job.insert("id".into(), id);
296 job.remove("job_id");
297 let mut out = Map::new();
298 out.insert("job".into(), Value::Object(job));
299 if result.get("duplicate").and_then(|v| v.as_bool()) == Some(true) {
300 out.insert("duplicate".into(), json!(true));
301 }
302 return out;
303 }
304 result
305}
306
307fn normalize_cron_show(result: Map<String, Value>) -> Map<String, Value> {
308 if result.contains_key("job") {
309 return result;
310 }
311 let job_id = result.get("job_id").or_else(|| result.get("id")).cloned();
312 let Some(id) = job_id else {
313 let mut out = Map::new();
314 out.insert("job".into(), Value::Null);
315 return out;
316 };
317 let mut job = result.clone();
318 job.insert("id".into(), id);
319 job.remove("job_id");
320 let mut out = Map::new();
321 out.insert("job".into(), Value::Object(job));
322 out
323}