Skip to main content

jax_daemon/http_server/api/v0/bucket/
ping.rs

1use axum::extract::{Json, State};
2use axum::response::{IntoResponse, Response};
3use reqwest::{Client, RequestBuilder, Url};
4use serde::{Deserialize, Serialize};
5use uuid::Uuid;
6
7use common::crypto::PublicKey;
8
9use crate::http_server::api::client::ApiRequest;
10use crate::ServiceState;
11
12#[derive(Debug, Clone, Serialize, Deserialize, clap::Args)]
13pub struct PingRequest {
14    /// Bucket ID to ping about
15    #[arg(long)]
16    pub bucket_id: Uuid,
17
18    /// Public key of the peer to ping (hex-encoded)
19    #[arg(long)]
20    pub peer_public_key: String,
21}
22
23#[derive(Debug, Clone, Serialize, Deserialize)]
24pub struct PingResponse {
25    pub bucket_id: Uuid,
26    pub peer_public_key: String,
27    pub success: bool,
28    pub message: String,
29}
30
31pub async fn handler(
32    State(state): State<ServiceState>,
33    Json(req): Json<PingRequest>,
34) -> Result<impl IntoResponse, PingError> {
35    tracing::info!(
36        "PING API: Received ping request for bucket {} to peer {}",
37        req.bucket_id,
38        req.peer_public_key
39    );
40
41    // Parse the peer's public key from hex
42    let peer_public_key = PublicKey::from_hex(&req.peer_public_key)
43        .map_err(|e| PingError::InvalidPublicKey(e.to_string()))?;
44
45    tracing::info!("PING API: Parsed peer public key successfully");
46
47    // Dispatch ping job
48    use common::peer::sync::{PingPeerJob, SyncJob};
49    state
50        .peer()
51        .dispatch(SyncJob::PingPeer(PingPeerJob {
52            bucket_id: req.bucket_id,
53            peer_id: peer_public_key,
54        }))
55        .await
56        .map_err(|e| PingError::Failed(e.to_string()))?;
57
58    tracing::info!(
59        "PING API: Dispatched PingPeer job for bucket {} to peer {}",
60        req.bucket_id,
61        req.peer_public_key
62    );
63
64    Ok((
65        http::StatusCode::OK,
66        Json(PingResponse {
67            bucket_id: req.bucket_id,
68            peer_public_key: req.peer_public_key,
69            success: true,
70            message: "Ping job dispatched".to_string(),
71        }),
72    )
73        .into_response())
74}
75
76#[derive(Debug, thiserror::Error)]
77pub enum PingError {
78    #[error("Invalid public key: {0}")]
79    InvalidPublicKey(String),
80    #[error("Failed to dispatch ping: {0}")]
81    Failed(String),
82}
83
84impl IntoResponse for PingError {
85    fn into_response(self) -> Response {
86        match self {
87            PingError::InvalidPublicKey(msg) => (
88                http::StatusCode::BAD_REQUEST,
89                format!("Invalid public key: {}", msg),
90            )
91                .into_response(),
92            PingError::Failed(msg) => (
93                http::StatusCode::INTERNAL_SERVER_ERROR,
94                format!("Failed to ping: {}", msg),
95            )
96                .into_response(),
97        }
98    }
99}
100
101// Client implementation - builds request for this operation
102impl ApiRequest for PingRequest {
103    type Response = PingResponse;
104
105    fn build_request(self, base_url: &Url, client: &Client) -> RequestBuilder {
106        let full_url = base_url.join("/api/v0/bucket/ping").unwrap();
107        client.post(full_url).json(&self)
108    }
109}