zc2 0.0.48

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
//! Hub calls for `zc bench node`: submit a signed report, read the price
//! recommendation, flip the price mode. Same ureq style as `node_sync`.
use std::time::Duration;

use super::report::SignedReport;

#[derive(Debug, PartialEq)]
pub enum SubmitError {
    /// Worth trying again later: I/O failure, 5xx, 408, 429, and 404/405/501
    /// (the hub does not have this endpoint yet: brokers roll out before it).
    Retryable(String),
    /// The hub looked at it and said no (a 4xx other than 404/405/408/409/429). Sending
    /// the same bytes again cannot help; the scheduler re-measures later.
    Rejected(u16, String),
}

impl std::fmt::Display for SubmitError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SubmitError::Retryable(e) => write!(f, "{e} (will retry)"),
            SubmitError::Rejected(c, e) => write!(f, "hub rejected the report: HTTP {c} {e}"),
        }
    }
}

fn base(api_url: &str) -> &str {
    api_url.trim_end_matches('/')
}

/// `POST /api/broker/benchmarks` → the hub's 201 JSON.
pub fn post(
    api_url: &str,
    api_key: &str,
    report: &SignedReport,
) -> Result<serde_json::Value, SubmitError> {
    let body = serde_json::json!({
        "report_json": report.report_json,
        "signature": report.signature,
    })
    .to_string();
    let resp = ureq::post(&format!("{}/api/broker/benchmarks", base(api_url)))
        .config()
        .timeout_global(Some(Duration::from_secs(10)))
        .http_status_as_error(false)
        .build()
        .header("X-Broker-Api-Key", api_key)
        .header("Content-Type", "application/json")
        .send(body.as_str())
        .map_err(|e| SubmitError::Retryable(e.to_string()))?;
    let code = resp.status().as_u16();
    let text = resp.into_body().read_to_string().unwrap_or_default();
    match code {
        200..=299 => Ok(serde_json::from_str(&text).unwrap_or(serde_json::Value::Null)),
        // Already stored, or not newer than what the hub holds: delivered.
        // (A timed-out POST the hub did store comes back as 409 on the retry.)
        409 => Ok(serde_json::Value::Null),
        // 404/405/501: the route is not deployed on the hub yet (a zc-first
        // rollout). The saved report is resent later, not re-measured.
        404 | 405 | 408 | 429 | 500..=599 => Err(SubmitError::Retryable(format!("HTTP {code}"))),
        _ => Err(SubmitError::Rejected(
            code,
            text.chars().take(200).collect(),
        )),
    }
}

fn recommendation_url(api_url: &str, node_pubkey: &str) -> String {
    format!(
        "{}/api/pricing/node-recommendation?node={}",
        base(api_url),
        crate::dataset::urlencode(node_pubkey)
    )
}

/// `GET /api/pricing/node-recommendation?node=<pubkey>`.
pub fn recommendation(
    api_url: &str,
    api_key: &str,
    node_pubkey: &str,
) -> Result<serde_json::Value, String> {
    let url = recommendation_url(api_url, node_pubkey);
    let resp = ureq::get(&url)
        .config()
        .timeout_global(Some(Duration::from_secs(10)))
        .http_status_as_error(false)
        .build()
        .header("X-Broker-Api-Key", api_key)
        .call()
        .map_err(|e| e.to_string())?;
    let code = resp.status().as_u16();
    let text = resp
        .into_body()
        .read_to_string()
        .map_err(|e| e.to_string())?;
    if code != 200 {
        return Err(format!("recommendation HTTP {code}: {}", text.trim()));
    }
    serde_json::from_str(&text).map_err(|e| e.to_string())
}

/// `PUT /api/nodes/{pubkey}/price-mode` with `{"mode": "fixed"|"auto"}`. The
/// pubkey goes into the path as-is (it may hold `/`; the hub uses a path converter).
pub fn put_price_mode(
    api_url: &str,
    api_key: &str,
    node_pubkey: &str,
    mode: &str,
) -> Result<(), String> {
    let url = format!("{}/api/nodes/{}/price-mode", base(api_url), node_pubkey);
    let body = serde_json::json!({ "mode": mode }).to_string();
    let resp = ureq::put(&url)
        .config()
        .timeout_global(Some(Duration::from_secs(10)))
        .http_status_as_error(false)
        .build()
        .header("X-Broker-Api-Key", api_key)
        .header("Content-Type", "application/json")
        .send(body.as_str())
        .map_err(|e| e.to_string())?;
    let code = resp.status().as_u16();
    if (200..300).contains(&code) {
        Ok(())
    } else {
        Err(format!("price-mode HTTP {code}"))
    }
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    use std::io::{Read, Write};
    use std::net::TcpListener;

    /// Reads one whole request (headers plus the Content-Length body). Replying
    /// and closing with unread bytes makes the OS reset the connection, which
    /// the client reports as an I/O error instead of the status.
    fn read_request(s: &mut std::net::TcpStream) {
        let mut data = Vec::new();
        let mut buf = [0u8; 4096];
        loop {
            let Ok(n) = s.read(&mut buf) else { return };
            if n == 0 {
                return;
            }
            data.extend_from_slice(&buf[..n]);
            let Some(end) = data.windows(4).position(|w| w == b"\r\n\r\n") else {
                continue;
            };
            let head = String::from_utf8_lossy(&data[..end]).to_lowercase();
            let len = head
                .lines()
                .find_map(|l| l.strip_prefix("content-length:"))
                .and_then(|v| v.trim().parse::<usize>().ok())
                .unwrap_or(0);
            if data.len() >= end + 4 + len {
                return;
            }
        }
    }

    /// Answers each connection with the next canned status line, then closes.
    pub(crate) fn stub(statuses: Vec<&'static str>) -> String {
        let l = TcpListener::bind("127.0.0.1:0").unwrap();
        let url = format!("http://{}", l.local_addr().unwrap());
        std::thread::spawn(move || {
            for status in statuses {
                let Ok((mut s, _)) = l.accept() else { return };
                read_request(&mut s);
                let body = "{}";
                let _ = write!(
                    s,
                    "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
                    body.len()
                );
            }
        });
        url
    }

    #[test]
    fn a_409_counts_as_delivered_and_a_400_is_a_refusal() {
        let url = stub(vec![
            "409 Conflict",
            "400 Bad Request",
            "429 Too Many Requests",
        ]);
        assert_eq!(post(&url, "k", &signed()), Ok(serde_json::Value::Null));
        assert!(matches!(
            post(&url, "k", &signed()),
            Err(SubmitError::Rejected(400, _))
        ));
        assert!(matches!(
            post(&url, "k", &signed()),
            Err(SubmitError::Retryable(_))
        ));
    }

    #[test]
    fn a_missing_endpoint_is_retryable_not_a_refusal() {
        let url = stub(vec![
            "404 Not Found",
            "405 Method Not Allowed",
            "501 Not Implemented",
        ]);
        for _ in 0..3 {
            assert!(matches!(
                post(&url, "k", &signed()),
                Err(SubmitError::Retryable(_))
            ));
        }
    }

    #[test]
    fn recommendation_query_url_encodes_the_pubkey() {
        assert_eq!(
            recommendation_url("http://hub/", "ab+c/d=="),
            "http://hub/api/pricing/node-recommendation?node=ab%2Bc%2Fd%3D%3D"
        );
    }

    fn signed() -> SignedReport {
        SignedReport {
            report_json: "{}".into(),
            signature: "sig".into(),
        }
    }

    #[test]
    fn submit_maps_4xx_to_rejected_and_5xx_or_io_to_retryable() {
        let url = stub(vec![
            "403 Forbidden",
            "503 Service Unavailable",
            "201 Created",
        ]);
        assert!(matches!(
            post(&url, "k", &signed()),
            Err(SubmitError::Rejected(403, _))
        ));
        assert!(matches!(
            post(&url, "k", &signed()),
            Err(SubmitError::Retryable(_))
        ));
        assert!(post(&url, "k", &signed()).is_ok());
        // Nothing listening: an I/O error is retryable too.
        let dead = {
            let l = TcpListener::bind("127.0.0.1:0").unwrap();
            format!("http://{}", l.local_addr().unwrap())
        };
        assert!(matches!(
            post(&dead, "k", &signed()),
            Err(SubmitError::Retryable(_))
        ));
    }
}