| 1 | |
|
| 2 | |
|
| 3 | |
|
| 4 | |
|
| 5 | | use anyhow::{Context, Result}; |
| 6 | | use http_body_util::{BodyExt, Full}; |
| 7 | | use hyper::body::Bytes; |
| 8 | | use spectra_core::keys::KeyPair; |
| 9 | | use spectra_core::proof::Proof; |
| 10 | | use std::path::{Path, PathBuf}; |
| 11 | |
|
| 12 | |
|
| 13 | | #[derive(Debug)] |
| 14 | | pub struct Response { |
| 15 | | pub status: u16, |
| 16 | | pub headers: Vec<(String, String)>, |
| 17 | | pub body: Vec<u8>, |
| 18 | | } |
| 19 | |
|
| 20 | | impl Response { |
| 21 | 6× | pub fn json(&self) -> Result<serde_json::Value> { |
| 22 | 6× | serde_json::from_slice(&self.body).with_context(|| format!("not JSON: {}", String::from_utf8_lossy(&self.body))) |
| 23 | 6× | } |
| 24 | 1× | pub fn header(&self, name: &str) -> Option<&str> { |
| 25 | 1× | self.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str()) |
| 26 | 1× | } |
| 27 | | } |
| 28 | |
|
| 29 | | pub struct Client { |
| 30 | | socket: PathBuf, |
| 31 | | signer: Option<KeyPair>, |
| 32 | | } |
| 33 | |
|
| 34 | | impl Client { |
| 35 | 8× | pub fn new(socket: &Path, signer: Option<KeyPair>) -> Client { |
| 36 | 8× | Client { socket: socket.to_path_buf(), signer } |
| 37 | 8× | } |
| 38 | |
|
| 39 | | |
| 40 | 18× | pub async fn alive(socket: &Path) -> bool { |
| 41 | 18× | tokio::net::UnixStream::connect(socket).await.is_ok() |
| 42 | 18× | } |
| 43 | |
|
| 44 | | |
| 45 | 15× | pub async fn send(&self, method: &str, path: &str, headers: &[(&str, String)], body: Vec<u8>) -> Result<Response> { |
| 46 | 15× | let stream = tokio::net::UnixStream::connect(&self.socket) |
| 47 | 15× | .await |
| 48 | 15× | .with_context(|| format!("connecting to {} (is `spectra serve` running?)", self.socket.display()))?; |
| 49 | 15× | let (mut sender, conn) = hyper::client::conn::http1::handshake(hyper_util::rt::TokioIo::new(stream)).await?; |
| 50 | 15× | tokio::spawn(async move { |
| 51 | 15× | let _ = conn.await; |
| 52 | 13× | }); |
| 53 | 15× | let mut req = |
| 54 | 15× | hyper::Request::builder().method(method).uri(path).header("host", "spectra").header("content-type", "application/json"); |
| 55 | 34× | for (k, v) in headers { |
| 56 | 34× | req = req.header(*k, v); |
| 57 | 34× | } |
| 58 | 15× | if let Some(pair) = &self.signer { |
| 59 | 56× | for (k, v) in sign_headers(pair, &format!("{method} {path}"), &body) { |
| 60 | 56× | req = req.header(k, v); |
| 61 | 56× | } |
| 62 | 1× | } |
| 63 | 15× | let resp = sender.send_request(req.body(Full::new(Bytes::from(body)))?).await?; |
| 64 | 15× | let status = resp.status().as_u16(); |
| 65 | 43× | let headers = resp.headers().iter().map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string())).collect(); |
| 66 | 15× | let body = resp.into_body().collect().await?.to_bytes().to_vec(); |
| 67 | 15× | Ok(Response { status, headers, body }) |
| 68 | 15× | } |
| 69 | |
|
| 70 | | |
| 71 | 9× | pub async fn mcp(&self, version: &str, request: &serde_json::Value) -> Result<Response> { |
| 72 | 9× | let method = request.get("method").and_then(|m| m.as_str()).unwrap_or("").to_string(); |
| 73 | 9× | let mut headers = vec![ |
| 74 | 9× | ("accept", "application/json, text/event-stream".to_string()), |
| 75 | 9× | ("mcp-protocol-version", version.to_string()), |
| 76 | 9× | ("mcp-method", method.clone()), |
| 77 | | ]; |
| 78 | 9× | if let Some(name) = request.pointer("/params/name").or_else(|| request.pointer("/params/uri")).and_then(|n| n.as_str()) { |
| 79 | 1× | headers.push(("mcp-name", name.to_string())); |
| 80 | 8× | } |
| 81 | 9× | self.send("POST", "/mcp", &headers, serde_json::to_vec(request)?).await |
| 82 | 9× | } |
| 83 | | } |
| 84 | |
|
| 85 | |
|
| 86 | 14× | pub fn sign_headers(pair: &KeyPair, method_path: &str, body: &[u8]) -> Vec<(&'static str, String)> { |
| 87 | 14× | let p = Proof::sign(pair, method_path, body); |
| 88 | 14× | vec![ |
| 89 | 14× | ("spectra-key", p.sig.key.to_hex()), |
| 90 | 14× | ("spectra-time", p.time_ms.to_string()), |
| 91 | 14× | ("spectra-nonce", hex::encode(p.nonce)), |
| 92 | 14× | ("spectra-signature", hex::encode(oxy_core::cbor::encode(&p.sig.to_value()))), |
| 93 | | ] |
| 94 | 14× | } |
| 95 | |
|
| 96 | |
|
| 97 | |
|
| 98 | 1× | pub fn rpc_result(r: &Response) -> Result<serde_json::Value> { |
| 99 | 1× | let is_sse = r.header("content-type").is_some_and(|c| c.starts_with("text/event-stream")); |
| 100 | 1× | if !is_sse { |
| 101 | 1× | return r.json(); |
| 102 | 0× | } |
| 103 | 0× | let text = String::from_utf8_lossy(&r.body); |
| 104 | 0× | let last = text |
| 105 | 0× | .lines() |
| 106 | 0× | .rev() |
| 107 | 0× | .filter_map(|l| l.strip_prefix("data:")) |
| 108 | 0× | .map(str::trim) |
| 109 | 0× | .find(|l| !l.is_empty()) |
| 110 | 0× | .context("an SSE response with no data")?; |
| 111 | 0× | Ok(serde_json::from_str(last)?) |
| 112 | 1× | } |