Skip to main content

taskfast_cli/cmd/
ping.rs

1// SPDX-License-Identifier: MIT
2//! `taskfast ping` — fast liveness probe.
3//!
4//! Two modes, chosen by whether an API key is present:
5//!
6//! * **Authenticated** (key present): `GET /agents/me` — validates
7//!   network reachability, base URL, *and* key in one round-trip.
8//! * **Anonymous** (no key): raw `GET` on the configured base URL —
9//!   reachability only. Any HTTP response from the host counts as a pong;
10//!   only a transport failure is an error. No TaskFast endpoint is
11//!   unauthenticated, so the weaker signal is intentional.
12//!
13//! Both modes are **single-attempt** — the client's [`RetryPolicy`] is
14//! bypassed on purpose. A diagnostic that silently retries hides the
15//! signal the operator asked for ("is the server up *right now*?").
16//!
17//! Envelope `data` shape:
18//! ```json
19//! {
20//!   "pong": true,
21//!   "latency_ms": 42,
22//!   "endpoint": "GET /agents/me",
23//!   "base_url": "http://localhost:4000",
24//!   "authenticated": true
25//! }
26//! ```
27//!
28//! [`RetryPolicy`]: taskfast_client::RetryPolicy
29
30use 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
41/// Connect timeout for the anonymous probe — short on purpose so `ping`
42/// fails fast when the host is unreachable.
43const ANON_CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
44/// Total request timeout for the anonymous probe.
45const 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_api_error(e).await.into());
76    }
77    Ok((latency_ms, "GET /agents/me", base_url, true))
78}
79
80async fn probe_anonymous(ctx: &Ctx) -> Result<(u64, &'static str, String, bool), CmdError> {
81    let base_url = ctx.base_url().to_string();
82    let http = reqwest::Client::builder()
83        .connect_timeout(ANON_CONNECT_TIMEOUT)
84        .timeout(ANON_REQUEST_TIMEOUT)
85        .build()
86        .map_err(|e| CmdError::Network(e.to_string()))?;
87
88    let started = Instant::now();
89    let resp = http
90        .get(&base_url)
91        .send()
92        .await
93        .map_err(|e| CmdError::Network(e.to_string()))?;
94    let latency_ms = started.elapsed().as_millis() as u64;
95
96    // Any HTTP response — even 4xx/5xx — proves the host is reachable and
97    // speaking HTTP. Status-code semantics need an authenticated probe.
98    let _ = resp.status();
99
100    Ok((latency_ms, "GET /", base_url, false))
101}