mockforge_tui/api/
client.rs1use anyhow::{Context, Result};
4use reqwest::Client;
5use serde::de::DeserializeOwned;
6
7use super::models::*;
8
9#[derive(Clone)]
11pub struct MockForgeClient {
12 client: Client,
13 base_url: String,
14 token: Option<String>,
15}
16
17impl MockForgeClient {
18 pub fn new(base_url: String, token: Option<String>) -> Result<Self> {
20 let client = Client::builder()
21 .timeout(std::time::Duration::from_secs(10))
22 .build()
23 .context("failed to create HTTP client")?;
24
25 let base_url = base_url.trim_end_matches('/').to_string();
26
27 Ok(Self {
28 client,
29 base_url,
30 token,
31 })
32 }
33
34 pub fn base_url(&self) -> &str {
36 &self.base_url
37 }
38
39 fn get(&self, path: &str) -> reqwest::RequestBuilder {
41 let url = format!("{}{path}", self.base_url);
42 let mut req = self.client.get(&url);
43 if let Some(ref token) = self.token {
44 req = req.bearer_auth(token);
45 }
46 req
47 }
48
49 fn post<T: serde::Serialize>(&self, path: &str, body: &T) -> reqwest::RequestBuilder {
51 let url = format!("{}{path}", self.base_url);
52 let mut req = self.client.post(&url).json(body);
53 if let Some(ref token) = self.token {
54 req = req.bearer_auth(token);
55 }
56 req
57 }
58
59 async fn get_api<T: DeserializeOwned>(&self, path: &str) -> Result<T> {
61 let resp = self.get(path).send().await.with_context(|| format!("GET {path}"))?;
62
63 let status = resp.status();
64 if !status.is_success() {
65 anyhow::bail!("HTTP {status} from {path}");
66 }
67
68 let ct = resp
70 .headers()
71 .get(reqwest::header::CONTENT_TYPE)
72 .and_then(|v| v.to_str().ok())
73 .unwrap_or("");
74 if ct.contains("text/html") {
75 anyhow::bail!("endpoint {path} not available (got HTML)");
76 }
77
78 let body = resp.text().await.with_context(|| format!("read body from {path}"))?;
79
80 let envelope: ApiResponse<T> = serde_json::from_str(&body)
81 .with_context(|| format!("deserialise response from {path}"))?;
82
83 if envelope.success {
84 envelope.data.context("API returned success but no data")
85 } else {
86 anyhow::bail!("API error: {}", envelope.error.unwrap_or_else(|| "unknown".into()))
87 }
88 }
89
90 async fn get_raw<T: DeserializeOwned>(&self, path: &str) -> Result<T> {
92 let resp = self.get(path).send().await.with_context(|| format!("GET {path}"))?;
93
94 let status = resp.status();
95 if !status.is_success() {
96 anyhow::bail!("HTTP {status} from {path}");
97 }
98
99 let ct = resp
100 .headers()
101 .get(reqwest::header::CONTENT_TYPE)
102 .and_then(|v| v.to_str().ok())
103 .unwrap_or("");
104 if ct.contains("text/html") {
105 anyhow::bail!("endpoint {path} not available (got HTML)");
106 }
107
108 let body = resp.text().await.with_context(|| format!("read body from {path}"))?;
109
110 serde_json::from_str(&body).with_context(|| format!("deserialise response from {path}"))
111 }
112
113 async fn post_api(&self, path: &str, body: &serde_json::Value) -> Result<String> {
115 let resp = self.post(path, body).send().await.with_context(|| format!("POST {path}"))?;
116
117 let status = resp.status();
118 if !status.is_success() {
119 anyhow::bail!("HTTP {status} from {path}");
120 }
121
122 let ct = resp
123 .headers()
124 .get(reqwest::header::CONTENT_TYPE)
125 .and_then(|v| v.to_str().ok())
126 .unwrap_or("");
127 if ct.contains("text/html") {
128 anyhow::bail!("endpoint {path} not available");
129 }
130
131 let body_text = resp.text().await.context("read POST response body")?;
132 let envelope: ApiResponse<String> = serde_json::from_str(&body_text)
133 .with_context(|| format!("deserialise response from {path}"))?;
134
135 if envelope.success {
136 Ok(envelope.data.unwrap_or_default())
137 } else {
138 anyhow::bail!("API error: {}", envelope.error.unwrap_or_else(|| "unknown".into()))
139 }
140 }
141
142 pub async fn get_dashboard(&self) -> Result<DashboardData> {
145 self.get_api("/__mockforge/dashboard").await
146 }
147
148 pub async fn get_routes(&self) -> Result<Vec<RouteInfo>> {
149 let resp = self
151 .get("/__mockforge/routes")
152 .send()
153 .await
154 .context("GET /__mockforge/routes")?;
155
156 let status = resp.status();
157 if !status.is_success() {
158 anyhow::bail!("HTTP {status} from /__mockforge/routes");
159 }
160
161 let ct = resp
162 .headers()
163 .get(reqwest::header::CONTENT_TYPE)
164 .and_then(|v| v.to_str().ok())
165 .unwrap_or("");
166 if ct.contains("text/html") {
167 anyhow::bail!("endpoint /__mockforge/routes not available");
168 }
169
170 let body = resp.text().await.context("read routes response")?;
171
172 if let Ok(envelope) = serde_json::from_str::<ApiResponse<Vec<RouteInfo>>>(&body) {
174 if envelope.success {
175 return envelope.data.context("routes: no data");
176 }
177 }
178
179 if let Ok(wrapper) = serde_json::from_str::<RoutesWrapper>(&body) {
181 return Ok(wrapper.routes);
182 }
183
184 serde_json::from_str::<Vec<RouteInfo>>(&body).context("deserialise routes response")
186 }
187
188 pub async fn get_logs(&self, limit: Option<u32>) -> Result<Vec<RequestLog>> {
189 let path = match limit {
190 Some(n) => format!("/__mockforge/logs?limit={n}"),
191 None => "/__mockforge/logs".into(),
192 };
193 self.get_api(&path).await
194 }
195
196 pub async fn get_metrics(&self) -> Result<MetricsData> {
197 self.get_api("/__mockforge/metrics").await
198 }
199
200 pub async fn get_config(&self) -> Result<ConfigState> {
201 self.get_api("/__mockforge/config").await
202 }
203
204 pub async fn get_health(&self) -> Result<HealthCheck> {
205 self.get_raw("/__mockforge/health").await
206 }
207
208 pub async fn get_server_info(&self) -> Result<ServerInfo> {
209 let resp = self
211 .get("/__mockforge/server-info")
212 .send()
213 .await
214 .context("GET /__mockforge/server-info")?;
215
216 let status = resp.status();
217 if !status.is_success() {
218 anyhow::bail!("HTTP {status} from /__mockforge/server-info");
219 }
220
221 let ct = resp
222 .headers()
223 .get(reqwest::header::CONTENT_TYPE)
224 .and_then(|v| v.to_str().ok())
225 .unwrap_or("");
226 if ct.contains("text/html") {
227 anyhow::bail!("endpoint /__mockforge/server-info not available");
228 }
229
230 let body = resp.text().await.context("read server-info response")?;
231
232 if let Ok(envelope) = serde_json::from_str::<ApiResponse<ServerInfo>>(&body) {
234 if envelope.success {
235 return envelope.data.context("server-info: no data");
236 }
237 }
238
239 serde_json::from_str::<ServerInfo>(&body).context("deserialise server-info response")
241 }
242
243 pub async fn get_plugins(&self) -> Result<Vec<PluginInfo>> {
244 let resp = self
246 .get("/__mockforge/plugins")
247 .send()
248 .await
249 .context("GET /__mockforge/plugins")?;
250
251 let status = resp.status();
252 if !status.is_success() {
253 anyhow::bail!("HTTP {status} from /__mockforge/plugins");
254 }
255
256 let ct = resp
257 .headers()
258 .get(reqwest::header::CONTENT_TYPE)
259 .and_then(|v| v.to_str().ok())
260 .unwrap_or("");
261 if ct.contains("text/html") {
262 anyhow::bail!("endpoint /__mockforge/plugins not available");
263 }
264
265 let body = resp.text().await.context("read plugins response")?;
266
267 if let Ok(envelope) = serde_json::from_str::<ApiResponse<Vec<PluginInfo>>>(&body) {
269 if envelope.success {
270 return envelope.data.context("plugins: no data");
271 }
272 }
273
274 if let Ok(envelope) = serde_json::from_str::<ApiResponse<PluginsWrapper>>(&body) {
276 if envelope.success {
277 return Ok(envelope.data.map(|w| w.plugins).unwrap_or_default());
278 }
279 }
280
281 Ok(Vec::new())
282 }
283
284 pub async fn get_fixtures(&self) -> Result<Vec<FixtureInfo>> {
285 self.get_api("/__mockforge/fixtures").await
286 }
287
288 pub async fn get_smoke_tests(&self) -> Result<Vec<SmokeTestResult>> {
289 self.get_api("/__mockforge/smoke").await
290 }
291
292 pub async fn run_smoke_tests(&self) -> Result<Vec<SmokeTestResult>> {
293 self.get_api("/__mockforge/smoke/run").await
294 }
295
296 pub async fn get_workspaces(&self) -> Result<Vec<WorkspaceInfo>> {
297 self.get_api("/__mockforge/workspaces").await
298 }
299
300 pub async fn get_chaos_status(&self) -> Result<serde_json::Value> {
303 self.get_api("/__mockforge/chaos").await
304 }
305
306 pub async fn toggle_chaos(&self, enabled: bool) -> Result<String> {
307 self.post_api("/__mockforge/chaos/toggle", &serde_json::json!({ "enabled": enabled }))
308 .await
309 }
310
311 pub async fn get_chaos_scenarios(&self) -> Result<serde_json::Value> {
312 self.get_api("/__mockforge/chaos/scenarios/predefined").await
313 }
314
315 pub async fn start_chaos_scenario(&self, name: &str) -> Result<String> {
316 self.post_api(&format!("/__mockforge/chaos/scenarios/{name}"), &serde_json::json!({}))
317 .await
318 }
319
320 pub async fn stop_chaos_scenario(&self, name: &str) -> Result<String> {
321 let url = format!("{}/__mockforge/chaos/scenarios/{name}", self.base_url);
322 let resp = self.client.delete(&url).send().await.context("DELETE chaos/scenarios stop")?;
323
324 let status = resp.status();
325 if !status.is_success() {
326 anyhow::bail!("HTTP {status} from chaos stop");
327 }
328
329 let body = resp.text().await.context("read chaos stop response")?;
330 let envelope: ApiResponse<String> =
331 serde_json::from_str(&body).context("deserialise chaos stop response")?;
332 if envelope.success {
333 Ok(envelope.data.unwrap_or_default())
334 } else {
335 anyhow::bail!(
336 "stop scenario failed: {}",
337 envelope.error.unwrap_or_else(|| "unknown".into())
338 )
339 }
340 }
341
342 pub async fn get_time_travel_status(&self) -> Result<TimeTravelStatus> {
343 self.get_raw("/__mockforge/time-travel/status").await
345 }
346
347 pub async fn get_chains(&self) -> Result<Vec<ChainInfo>> {
348 self.get_api("/__mockforge/chains").await
349 }
350
351 pub async fn get_audit_logs(&self) -> Result<Vec<AuditEntry>> {
352 self.get_api("/__mockforge/audit/logs").await
353 }
354
355 pub async fn get_analytics_summary(&self) -> Result<AnalyticsSummary> {
356 self.get_api("/__mockforge/analytics/summary").await
357 }
358
359 pub async fn get_federation_peers(&self) -> Result<Vec<FederationPeer>> {
362 self.get_api("/__mockforge/federation/peers").await
363 }
364
365 pub async fn get_contract_diff_captures(&self) -> Result<Vec<ContractDiffCapture>> {
366 let resp = self
368 .get("/__mockforge/contract-diff/captures")
369 .send()
370 .await
371 .context("GET /__mockforge/contract-diff/captures")?;
372
373 let status = resp.status();
374 if !status.is_success() {
375 anyhow::bail!("HTTP {status} from contract-diff/captures");
376 }
377
378 let ct = resp
379 .headers()
380 .get(reqwest::header::CONTENT_TYPE)
381 .and_then(|v| v.to_str().ok())
382 .unwrap_or("");
383 if ct.contains("text/html") {
384 anyhow::bail!("endpoint contract-diff/captures not available");
385 }
386
387 let body = resp.text().await.context("read contract-diff response")?;
388
389 if let Ok(wrapper) = serde_json::from_str::<ContractDiffWrapper>(&body) {
391 return Ok(wrapper.captures);
392 }
393
394 if let Ok(envelope) = serde_json::from_str::<ApiResponse<Vec<ContractDiffCapture>>>(&body) {
396 if envelope.success {
397 return envelope.data.context("contract-diff: no data");
398 }
399 }
400
401 serde_json::from_str::<Vec<ContractDiffCapture>>(&body)
403 .context("deserialise contract-diff response")
404 }
405
406 pub async fn get_vbr_status(&self) -> Result<serde_json::Value> {
409 self.get_api("/__mockforge/vbr/status").await
410 }
411
412 pub async fn update_latency(&self, config: &LatencyConfig) -> Result<String> {
415 self.post_api("/__mockforge/config/latency", &serde_json::to_value(config)?)
416 .await
417 }
418
419 pub async fn update_faults(&self, config: &FaultConfig) -> Result<String> {
420 self.post_api("/__mockforge/config/faults", &serde_json::to_value(config)?)
421 .await
422 }
423
424 pub async fn update_proxy(&self, config: &ProxyConfig) -> Result<String> {
425 self.post_api("/__mockforge/config/proxy", &serde_json::to_value(config)?).await
426 }
427
428 pub async fn verify(&self, query: &serde_json::Value) -> Result<VerificationResult> {
431 let resp = self
432 .post("/__mockforge/verification/verify", query)
433 .send()
434 .await
435 .context("POST verification/verify")?;
436
437 let status = resp.status();
438 if !status.is_success() {
439 anyhow::bail!("HTTP {status} from verification/verify");
440 }
441
442 let body = resp.text().await.context("read verification response")?;
443 let envelope: ApiResponse<VerificationResult> =
444 serde_json::from_str(&body).context("deserialise verification response")?;
445
446 if envelope.success {
447 envelope.data.context("verification returned no data")
448 } else {
449 anyhow::bail!(
450 "verification failed: {}",
451 envelope.error.unwrap_or_else(|| "unknown".into())
452 )
453 }
454 }
455
456 pub async fn enable_time_travel(&self) -> Result<String> {
459 self.post_api("/__mockforge/time-travel/enable", &serde_json::json!({})).await
460 }
461
462 pub async fn disable_time_travel(&self) -> Result<String> {
463 self.post_api("/__mockforge/time-travel/disable", &serde_json::json!({})).await
464 }
465
466 pub async fn execute_chain(&self, id: &str) -> Result<serde_json::Value> {
469 let path = format!("/__mockforge/chains/{id}/execute");
470 let resp = self
471 .post(&path, &serde_json::json!({}))
472 .send()
473 .await
474 .with_context(|| format!("POST {path}"))?;
475
476 let status = resp.status();
477 if !status.is_success() {
478 anyhow::bail!("HTTP {status} from {path}");
479 }
480
481 let body = resp.text().await.context("read chain execution response")?;
482 let envelope: ApiResponse<serde_json::Value> =
483 serde_json::from_str(&body).context("deserialise chain execution response")?;
484
485 if envelope.success {
486 envelope.data.context("chain execution returned no data")
487 } else {
488 anyhow::bail!(
489 "chain execution failed: {}",
490 envelope.error.unwrap_or_else(|| "unknown".into())
491 )
492 }
493 }
494
495 pub async fn get_import_history(&self) -> Result<serde_json::Value> {
498 self.get_api("/__mockforge/import/history").await
499 }
500
501 pub async fn clear_import_history(&self) -> Result<String> {
502 self.post_api("/__mockforge/import/history/clear", &serde_json::json!({})).await
503 }
504
505 pub async fn get_recorder_status(&self) -> Result<serde_json::Value> {
508 self.get_api("/__mockforge/recorder/status").await
509 }
510
511 pub async fn toggle_recorder(&self, enable: bool) -> Result<String> {
512 let path = if enable {
513 "/__mockforge/recorder/start"
514 } else {
515 "/__mockforge/recorder/stop"
516 };
517 self.post_api(path, &serde_json::json!({})).await
518 }
519
520 pub async fn activate_workspace(&self, workspace_id: &str) -> Result<String> {
523 self.post_api(
524 &format!("/__mockforge/workspaces/{workspace_id}/activate"),
525 &serde_json::json!({}),
526 )
527 .await
528 }
529
530 pub async fn get_world_state(&self) -> Result<serde_json::Value> {
533 self.get_api("/__mockforge/world-state").await
534 }
535
536 pub async fn ping(&self) -> bool {
540 self.get("/__mockforge/health")
541 .timeout(std::time::Duration::from_secs(3))
542 .send()
543 .await
544 .is_ok()
545 }
546}
547
548#[cfg(test)]
549mod tests {
550 use super::*;
551
552 #[test]
553 fn client_strips_trailing_slash() {
554 let client = MockForgeClient::new("http://localhost:9080/".into(), None).unwrap();
555 assert_eq!(client.base_url(), "http://localhost:9080");
556 }
557
558 #[test]
559 fn client_preserves_clean_url() {
560 let client = MockForgeClient::new("http://localhost:9080".into(), None).unwrap();
561 assert_eq!(client.base_url(), "http://localhost:9080");
562 }
563}