Skip to main content

taskfast_cli/cmd/events/
schema.rs

1// SPDX-License-Identifier: MIT
2//! `taskfast events schema` — fetch the AsyncAPI 2.6 spec for the event stream.
3//!
4//! The spec is generated at server boot from the canonical
5//! `WebhookDelivery.build_payload/2` registry (see
6//! `lib/task_fast_web/async_api.ex`) so there is exactly one source of
7//! truth for the 13 event types. `--event <name>` narrows the output to
8//! one message schema; default prints the full document.
9
10use clap::Parser;
11use serde_json::json;
12
13use super::super::{CmdError, CmdResult, Ctx};
14use crate::envelope::Envelope;
15
16use taskfast_client::ClientInfo;
17use taskfast_client::Error as ClientError;
18
19#[derive(Debug, Parser)]
20pub struct SchemaArgs {
21    /// Restrict output to a single event type's message schema.
22    /// Name matches the AsyncAPI `components.messages.<Camel>` key
23    /// (e.g. `TaskAssigned`, `BidAccepted`).
24    #[arg(long)]
25    pub event: Option<String>,
26}
27
28pub async fn run(ctx: &Ctx, args: SchemaArgs) -> CmdResult {
29    // Schema is public (no X-API-Key required on the server), but we reuse
30    // the inner reqwest client so timeouts + TLS config match every other call.
31    // Falls back to a bare reqwest::Client when no api_key is configured.
32    let base = format!("{}/asyncapi.json", ctx.base_url().trim_end_matches('/'));
33    let http = match ctx.client() {
34        Ok(c) => c.inner().client().clone(),
35        Err(_) => reqwest::Client::new(),
36    };
37
38    let resp = http
39        .get(&base)
40        .send()
41        .await
42        .map_err(|e| CmdError::from(ClientError::from(e)))?;
43
44    let status = resp.status();
45    let body = resp
46        .text()
47        .await
48        .map_err(|e| CmdError::Network(e.to_string()))?;
49
50    if !status.is_success() {
51        return Err(CmdError::Server(format!(
52            "GET /asyncapi.json → HTTP {}: {}",
53            status.as_u16(),
54            body
55        )));
56    }
57
58    let spec: serde_json::Value = serde_json::from_str(&body)
59        .map_err(|e| CmdError::Decode(format!("asyncapi response not JSON: {e}")))?;
60
61    let data = match args.event {
62        None => spec,
63        Some(ref key) => spec
64            .get("components")
65            .and_then(|c| c.get("messages"))
66            .and_then(|m| m.get(key))
67            .cloned()
68            .ok_or_else(|| CmdError::Validation {
69                code: "unknown_event".into(),
70                message: format!(
71                    "no message named {key:?} in components.messages — run without --event to list all"
72                ),
73            })
74            .map(|msg| json!({ "event": key, "message": msg }))?,
75    };
76
77    Ok(Envelope::success(ctx.environment, ctx.dry_run, data))
78}