//! Harness-facing adapter to the common node gRPC protocol. use crate::node::{ self, proto::{self, response_frame::Payload}, }; use crate::node_connection::Connection; use axum::{ Router, body::{Body, Bytes}, extract::{DefaultBodyLimit, State}, http::{HeaderMap, StatusCode}, response::{IntoResponse, Response}, routing::{get, post}, }; use std::{net::SocketAddr, time::Duration}; use subtle::ConstantTimeEq; #[derive(Clone)] pub struct Proxy { connection: Connection, token: String, } impl Proxy { pub async fn connect( address: SocketAddr, token: String, ) -> Result> { if token.len() < 32 || token.len() > 4096 || !token.bytes().all(|b| b.is_ascii_graphic()) { return Err("invalid node credential".into()); } let connection = Connection::start(address, token.clone())?; connection.wait_ready(Duration::from_secs(6)).await?; connection.client("responses.gateway.v1")?; Ok(Self { connection, token }) } pub fn router(self) -> Router { Router::new() .route("/v1/models", get(models)) .route("/node/status", get(connection_status)) .route("/v1/responses", post(respond)) .layer(DefaultBodyLimit::max(2 * 1024 * 1024)) .with_state(self) } fn auth(&self, h: &HeaderMap) -> bool { h.get("authorization") .and_then(|v| v.to_str().ok()) .and_then(|v| v.strip_prefix("Bearer ")) .is_some_and(|v| bool::from(v.as_bytes().ct_eq(self.token.as_bytes()))) } } fn failure(status: StatusCode, kind: &str) -> Response { ( status, axum::Json(serde_json::json!({"error":{"type":kind,"message":kind}})), ) .into_response() } async fn models(State(p): State, h: HeaderMap) -> Response { if !p.auth(&h) { return failure(StatusCode::UNAUTHORIZED, "unauthorized"); } let Ok(mut client) = p.connection.client("responses.gateway.v1") else { return failure(StatusCode::SERVICE_UNAVAILABLE, "node_not_ready"); }; let mut r = node::authorized(proto::Empty {}, &p.token).expect("validated credential"); r.set_timeout(Duration::from_secs(5)); match client.models(r).await { Ok(v) => ([("content-type", "application/json")], v.into_inner().json).into_response(), Err(_) => failure(StatusCode::BAD_GATEWAY, "node_unavailable"), } } async fn respond(State(p): State, h: HeaderMap, body: Bytes) -> Response { if !p.auth(&h) { return failure(StatusCode::UNAUTHORIZED, "unauthorized"); } let Ok(mut client) = p.connection.client("responses.gateway.v1") else { return failure(StatusCode::SERVICE_UNAVAILABLE, "node_not_ready"); }; let request = respond_request(body, &p.token); let mut stream = match client.respond(request).await { Ok(r) => r.into_inner(), Err(e) => return failure(refusal_status(&e), "node_request_failed"), }; let Some(headers) = read_headers(&mut stream).await else { return failure(StatusCode::BAD_GATEWAY, "missing_node_headers"); }; let Ok(code) = node_status(&headers) else { return failure(StatusCode::BAD_GATEWAY, "invalid_node_status"); }; build_response(code, headers, relay_body(stream)) } fn respond_request(body: Bytes, token: &str) -> tonic::Request { let mut request = node::authorized( proto::ResponseRequest { json: body.to_vec(), }, token, ) .expect("validated credential"); request.set_timeout(Duration::from_secs(86400)); request } /// A node that is out of capacity is a 429 for the harness; every other refusal is a bad gateway. fn refusal_status(e: &tonic::Status) -> StatusCode { if e.code() == tonic::Code::ResourceExhausted { StatusCode::TOO_MANY_REQUESTS } else { StatusCode::BAD_GATEWAY } } /// The first frame of a response must carry the headers. async fn read_headers( stream: &mut tonic::Streaming, ) -> Option { match stream.message().await { Ok(Some(proto::ResponseFrame { payload: Some(Payload::Headers(h)), })) => Some(h), _ => None, } } fn node_status(headers: &proto::ResponseHeaders) -> Result { u16::try_from(headers.status) .ok() .and_then(|s| StatusCode::from_u16(s).ok()) .ok_or(()) } type ByteStream = std::pin::Pin> + Send>>; /// The data frames up to exactly one end marker; a broken stream is never replayed. fn relay_body(mut stream: tonic::Streaming) -> ByteStream { let body = async_stream::try_stream! { let mut ended=false; while let Some(frame)=stream.message().await.map_err(|_|{ std::io::Error::other("node stream interrupted; do not replay") })? { match frame.payload { Some(Payload::Data(bytes)) if !ended=>{yield Bytes::from(bytes);}, Some(Payload::End(_)) if !ended=>ended=true, _=>Err(std::io::Error::other("invalid node frame order"))?, } } if !ended {Err(std::io::Error::other("missing node end marker"))?;} }; Box::pin(body) } fn build_response(code: StatusCode, headers: proto::ResponseHeaders, body: ByteStream) -> Response { let mut response = Response::builder().status(code); if !headers.content_type.is_empty() { response = response.header("content-type", headers.content_type); } if !headers.retry_after.is_empty() { response = response.header("retry-after", headers.retry_after); } response .body(Body::from_stream(body)) .unwrap_or_else(|_| failure(StatusCode::BAD_GATEWAY, "invalid_node_headers")) } async fn connection_status(State(p): State, h: HeaderMap) -> Response { if !p.auth(&h) { return failure(StatusCode::UNAUTHORIZED, "unauthorized"); } axum::Json(p.connection.status()).into_response() }