| 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 | 43× | pub fn json(&self) -> Result<serde_json::Value> { |
| 22 | 43× | serde_json::from_slice(&self.body).with_context(|| format!("not JSON: {}", String::from_utf8_lossy(&self.body))) |
| 23 | 43× | } |
| 24 | 33× | pub fn header(&self, name: &str) -> Option<&str> { |
| 25 | 42× | self.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str()) |
| 26 | 33× | } |
| 27 | | } |
| 28 | |
|
| 29 | | pub struct Client { |
| 30 | | socket: PathBuf, |
| 31 | | signer: Option<KeyPair>, |
| 32 | | } |
| 33 | |
|
| 34 | | impl Client { |
| 35 | 24× | pub fn new(socket: &Path, signer: Option<KeyPair>) -> Client { |
| 36 | 24× | Client { socket: socket.to_path_buf(), signer } |
| 37 | 24× | } |
| 38 | |
|
| 39 | | |
| 40 | 43× | pub async fn alive(socket: &Path) -> bool { |
| 41 | 43× | tokio::net::UnixStream::connect(socket).await.is_ok() |
| 42 | 43× | } |
| 43 | |
|
| 44 | | |
| 45 | 87× | pub async fn send(&self, method: &str, path: &str, headers: &[(&str, String)], body: Vec<u8>) -> Result<Response> { |
| 46 | 87× | let stream = tokio::net::UnixStream::connect(&self.socket) |
| 47 | 87× | .await |
| 48 | 87× | .with_context(|| format!("connecting to {} (is `spectra serve` running?)", self.socket.display()))?; |
| 49 | 87× | let (mut sender, conn) = hyper::client::conn::http1::handshake(hyper_util::rt::TokioIo::new(stream)).await?; |
| 50 | 87× | tokio::spawn(async move { |
| 51 | 87× | let _ = conn.await; |
| 52 | 87× | }); |
| 53 | | |
| 54 | | |
| 55 | 87× | let mut req = hyper::Request::builder().method(method).uri(path).header("host", "spectra").header("connection", "close"); |
| 56 | | |
| 57 | 152× | if !headers.iter().any(|(k, _)| k.eq_ignore_ascii_case("content-type")) { |
| 58 | 83× | req = req.header("content-type", "application/json"); |
| 59 | 83× | } |
| 60 | 153× | for (k, v) in headers { |
| 61 | 153× | req = req.header(*k, v); |
| 62 | 153× | } |
| 63 | 87× | if let Some(pair) = &self.signer { |
| 64 | 268× | for (k, v) in sign_headers(pair, &format!("{method} {path}"), &body) { |
| 65 | 268× | req = req.header(k, v); |
| 66 | 268× | } |
| 67 | 20× | } |
| 68 | 87× | let resp = sender.send_request(req.body(Full::new(Bytes::from(body)))?).await?; |
| 69 | 87× | let status = resp.status().as_u16(); |
| 70 | 437× | let headers = resp.headers().iter().map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string())).collect(); |
| 71 | 87× | let body = resp.into_body().collect().await?.to_bytes().to_vec(); |
| 72 | 87× | Ok(Response { status, headers, body }) |
| 73 | 87× | } |
| 74 | |
|
| 75 | | |
| 76 | 35× | pub async fn mcp(&self, version: &str, request: &serde_json::Value) -> Result<Response> { |
| 77 | 35× | let method = request.get("method").and_then(|m| m.as_str()).unwrap_or("").to_string(); |
| 78 | 35× | let mut headers = vec![ |
| 79 | 35× | ("accept", "application/json, text/event-stream".to_string()), |
| 80 | 35× | ("mcp-protocol-version", version.to_string()), |
| 81 | 35× | ("mcp-method", method.clone()), |
| 82 | | ]; |
| 83 | 35× | if let Some(name) = request.pointer("/params/name").or_else(|| request.pointer("/params/uri")).and_then(|n| n.as_str()) { |
| 84 | 26× | headers.push(("mcp-name", name.to_string())); |
| 85 | 26× | } |
| 86 | 35× | self.send("POST", "/mcp", &headers, serde_json::to_vec(request)?).await |
| 87 | 35× | } |
| 88 | | } |
| 89 | |
|
| 90 | | impl Client { |
| 91 | | |
| 92 | | |
| 93 | 0× | pub async fn stream(&self, path: &str, mut line: impl FnMut(&str) -> bool) -> Result<u16> { |
| 94 | 0× | let stream = tokio::net::UnixStream::connect(&self.socket) |
| 95 | 0× | .await |
| 96 | 0× | .with_context(|| format!("connecting to {} (is `spectra serve` running?)", self.socket.display()))?; |
| 97 | 0× | let (mut sender, conn) = hyper::client::conn::http1::handshake(hyper_util::rt::TokioIo::new(stream)).await?; |
| 98 | 0× | tokio::spawn(async move { |
| 99 | 0× | let _ = conn.await; |
| 100 | 0× | }); |
| 101 | 0× | let mut req = hyper::Request::builder().method("GET").uri(path).header("host", "spectra").header("connection", "close"); |
| 102 | 0× | if let Some(pair) = &self.signer { |
| 103 | 0× | for (k, v) in sign_headers(pair, &format!("GET {path}"), b"") { |
| 104 | 0× | req = req.header(k, v); |
| 105 | 0× | } |
| 106 | 0× | } |
| 107 | 0× | let resp = sender.send_request(req.body(Full::new(Bytes::new()))?).await?; |
| 108 | 0× | let status = resp.status().as_u16(); |
| 109 | 0× | let mut body = resp.into_body(); |
| 110 | 0× | let mut buf = String::new(); |
| 111 | 0× | while let Some(frame) = body.frame().await { |
| 112 | 0× | if let Ok(data) = frame?.into_data() { |
| 113 | 0× | buf.push_str(&String::from_utf8_lossy(&data)); |
| 114 | 0× | while let Some(i) = buf.find('\n') { |
| 115 | 0× | let l: String = buf.drain(..=i).collect(); |
| 116 | 0× | if !line(l.trim_end()) { |
| 117 | 0× | return Ok(status); |
| 118 | 0× | } |
| 119 | | } |
| 120 | 0× | } |
| 121 | | } |
| 122 | 0× | Ok(status) |
| 123 | 0× | } |
| 124 | | } |
| 125 | |
|
| 126 | |
|
| 127 | 67× | pub fn sign_headers(pair: &KeyPair, method_path: &str, body: &[u8]) -> Vec<(&'static str, String)> { |
| 128 | 67× | let p = Proof::sign(pair, method_path, body); |
| 129 | 67× | vec![ |
| 130 | 67× | ("spectra-key", p.sig.key.to_hex()), |
| 131 | 67× | ("spectra-time", p.time_ms.to_string()), |
| 132 | 67× | ("spectra-nonce", hex::encode(p.nonce)), |
| 133 | 67× | ("spectra-signature", hex::encode(oxy_core::cbor::encode(&p.sig.to_value()))), |
| 134 | | ] |
| 135 | 67× | } |
| 136 | |
|
| 137 | |
|
| 138 | |
|
| 139 | 23× | pub fn rpc_result(r: &Response) -> Result<serde_json::Value> { |
| 140 | 23× | let is_sse = r.header("content-type").is_some_and(|c| c.starts_with("text/event-stream")); |
| 141 | 23× | if !is_sse { |
| 142 | 18× | return r.json(); |
| 143 | 5× | } |
| 144 | 5× | let text = String::from_utf8_lossy(&r.body); |
| 145 | 5× | let last = text |
| 146 | 5× | .lines() |
| 147 | 5× | .rev() |
| 148 | 10× | .filter_map(|l| l.strip_prefix("data:")) |
| 149 | 5× | .map(str::trim) |
| 150 | 5× | .find(|l| !l.is_empty()) |
| 151 | 5× | .context("an SSE response with no data")?; |
| 152 | 5× | Ok(serde_json::from_str(last)?) |
| 153 | 23× | } |