~ knotless Search/
↑↓ move↵ open⇧↵ all results

socialweb.computer/socialweb-computer-kcp

socialweb.computer: a compute market on atproto (kcp)

1 collaborator
0
0
56 lines · 2.6 KB Raw History
//! HTTP/1.1 to a bidder's iroh market endpoint (the `iroh` address of its market.offering record, an `endpoint...`
//! ticket) over atlibs-iroh's raw fetch (`iroh://<ticket>/<path>`: `dumbpipe connect <ticket>`, the listener and mux a
//! requester's market calls reach; prod bidders behind NAT offer iroh and webrtc only). Headers go on dumbpipe's stdin,
//! never its argv; the connection is end-to-end encrypted to the iroh node the ticket names. One client per process,
//! so its connections are reused.

use std::sync::OnceLock;
use std::time::Duration;

use serde_json::Value;

/// The ticket of an iroh market endpoint address (`endpoint...`, an `iroh://` prefix dropped); None: not one.
pub fn ticket(address: &str) -> Option<String> {
    let t = address.strip_prefix("iroh://").unwrap_or(address);
    matches!(atlibs_iroh::raw_url(&format!("iroh://{t}/")), Some(Ok(_))).then(|| t.to_string())
}

/// The market endpoint of an offering record's value: its https address where it has one (staging), else
/// `iroh://<ticket>` of its iroh one; None: neither.
pub fn market_base(offering: &Value) -> Option<String> {
    let endpoints: Vec<&Value> = offering["endpoints"].as_array().into_iter().flatten().collect();
    let of = |kind: &str| endpoints.iter().filter(|e| e["kind"] == kind).find_map(|e| e["address"].as_str());
    if let Some(u) = of("https").filter(|u| u.starts_with("https://")) {
        return Some(u.trim_end_matches('/').to_string());
    }
    of("iroh").and_then(ticket).map(|t| format!("iroh://{t}"))
}

/// One request to the iroh market endpoint `ticket`; `target` is the path and query. Status and body.
pub async fn request(
    ticket: &str,
    method: &str,
    target: &str,
    headers: Vec<(String, String)>,
    body: Vec<u8>,
    timeout: Duration,
) -> Result<(u16, Vec<u8>), String> {
    static IROH: OnceLock<atlibs_iroh::Iroh> = OnceLock::new();
    // a raw fetch uses no ssh key; the path is the host's iroh transport's
    let iroh = IROH.get_or_init(|| atlibs_iroh::Iroh::new(crate::home_tmp("iroh_ed25519")));
    let url = format!("iroh://{ticket}{target}");
    let r = tokio::time::timeout(timeout, iroh.http(method, &url, headers, body))
        .await
        .map_err(|_| format!("no response over iroh in {} s", timeout.as_secs()))??;
    Ok((r.status, r.body))
}

/// `?<params>` form-encoded, or "" for none.
pub fn query(params: &[(&str, &str)]) -> String {
    if params.is_empty() {
        return String::new();
    }
    let mut u = reqwest::Url::parse("http://q/").expect("a fixed URL");
    u.query_pairs_mut().extend_pairs(params);
    format!("?{}", u.query().unwrap_or_default())
}