1use std::time::{Duration, Instant};
31
32use clap::Parser;
33use serde_json::json;
34
35use super::{CmdError, CmdResult, Ctx};
36use crate::envelope::Envelope;
37
38use taskfast_client::map_api_error;
39use taskfast_client::ClientInfo;
40
41const ANON_CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
44const ANON_REQUEST_TIMEOUT: Duration = Duration::from_secs(10);
46
47#[derive(Debug, Parser)]
48pub struct Args;
49
50pub async fn run(ctx: &Ctx, _args: Args) -> CmdResult {
51 let (latency_ms, endpoint, base_url, authenticated) = match ctx.api_key.as_deref() {
52 Some(_) => probe_authenticated(ctx).await?,
53 None => probe_anonymous(ctx).await?,
54 };
55
56 let data = json!({
57 "pong": true,
58 "latency_ms": latency_ms,
59 "endpoint": endpoint,
60 "base_url": base_url,
61 "authenticated": authenticated,
62 });
63 Ok(Envelope::success(ctx.environment, ctx.dry_run, data))
64}
65
66async fn probe_authenticated(ctx: &Ctx) -> Result<(u64, &'static str, String, bool), CmdError> {
67 let client = ctx.client()?;
68 let base_url = client.inner().baseurl().to_string();
69
70 let started = Instant::now();
71 let result = client.inner().get_agent_profile().await;
72 let latency_ms = started.elapsed().as_millis() as u64;
73
74 if let Err(e) = result {
75 return Err(map_probe_error(e, &base_url).await);
76 }
77 Ok((latency_ms, "GET /agents/me", base_url, true))
78}
79
80async fn map_probe_error(e: taskfast_client::api::Error<()>, base_url: &str) -> CmdError {
87 if let taskfast_client::api::Error::UnexpectedResponse(resp) = &e {
88 if resp.status() == reqwest::StatusCode::NOT_FOUND {
89 return CmdError::Validation {
90 code: "not_found".into(),
91 message: format!(
92 "GET /agents/me returned 404 from {base_url}: the server is reachable \
93 but did not rewrite this host to its /api routes (it only rewrites \
94 hosts in its :api_hosts list). Point --api-base/TASKFAST_API at the \
95 api.<domain> host for this environment (e.g. https://api.taskfast.app), \
96 or use 127.0.0.1 against a local dev server."
97 ),
98 };
99 }
100 }
101 map_api_error(e).await.into()
102}
103
104async fn probe_anonymous(ctx: &Ctx) -> Result<(u64, &'static str, String, bool), CmdError> {
105 let base_url = ctx.base_url().to_string();
106 let http = reqwest::Client::builder()
107 .connect_timeout(ANON_CONNECT_TIMEOUT)
108 .timeout(ANON_REQUEST_TIMEOUT)
109 .build()
110 .map_err(|e| CmdError::Network(e.to_string()))?;
111
112 let started = Instant::now();
113 let resp = http
114 .get(&base_url)
115 .send()
116 .await
117 .map_err(|e| CmdError::Network(e.to_string()))?;
118 let latency_ms = started.elapsed().as_millis() as u64;
119
120 let _ = resp.status();
123
124 Ok((latency_ms, "GET /", base_url, false))
125}