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_probe_error(e, &base_url).await);
76    }
77    Ok((latency_ms, "GET /agents/me", base_url, true))
78}
79
80/// gh#145: a 404 from a server that just answered at the HTTP layer means
81/// the host is not in the server's `:api_hosts` rewrite list, so the request
82/// never reached the API routes — a configuration trap, not a dead endpoint.
83/// Diagnose it explicitly (the server's 404 page carries no hint, and a raw
84/// HTML body must not leak into the message). Pairs with the server-side
85/// `:api_hosts` issue Akuja-Inc/taskfast#1163.
86async 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    // Any HTTP response — even 4xx/5xx — proves the host is reachable and
121    // speaking HTTP. Status-code semantics need an authenticated probe.
122    let _ = resp.status();
123
124    Ok((latency_ms, "GET /", base_url, false))
125}