Files
leleka/desktop-core/src/node_proxy.rs
T
Pavlo Ratushnyi 4013e0c9bd
Desktop foundation / core (ubuntu-latest) (push) Failing after 28s
Desktop foundation / core (macos-latest) (push) Canceled after 0s
Desktop foundation / core (windows-latest) (push) Canceled after 0s
Linux / verify (push) Canceled after 0s
Linux / keyless-cuda (push) Canceled after 0s
Linux / static-cuda-package (push) Canceled after 0s
Linux / hosted-cuda-package (push) Canceled after 0s
Linux / linux-static-cli (push) Canceled after 0s
Linux / linux-cli-container (push) Canceled after 0s
Linux / release-cli (push) Canceled after 0s
Import tracked Strata Next source snapshot
2026-10-05 18:15:08 +02:00

144 lines
5.2 KiB
Rust

//! 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<Self, Box<dyn std::error::Error>> {
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<Proxy>, 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<Proxy>, 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 mut request = node::authorized(
proto::ResponseRequest {
json: body.to_vec(),
},
&p.token,
)
.expect("validated credential");
request.set_timeout(Duration::from_secs(86400));
let mut stream = match client.respond(request).await {
Ok(r) => r.into_inner(),
Err(e) => {
return failure(
if e.code() == tonic::Code::ResourceExhausted {
StatusCode::TOO_MANY_REQUESTS
} else {
StatusCode::BAD_GATEWAY
},
"node_request_failed",
);
}
};
let headers = match stream.message().await {
Ok(Some(proto::ResponseFrame {
payload: Some(Payload::Headers(h)),
})) => h,
_ => return failure(StatusCode::BAD_GATEWAY, "missing_node_headers"),
};
let Ok(code) = u16::try_from(headers.status)
.ok()
.and_then(|s| StatusCode::from_u16(s).ok())
.ok_or(())
else {
return failure(StatusCode::BAD_GATEWAY, "invalid_node_status");
};
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"))?;}
};
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(Box::pin(body)
as std::pin::Pin<
Box<dyn futures_util::Stream<Item = Result<Bytes, std::io::Error>> + Send>,
>))
.unwrap_or_else(|_| failure(StatusCode::BAD_GATEWAY, "invalid_node_headers"))
}
async fn connection_status(State(p): State<Proxy>, h: HeaderMap) -> Response {
if !p.auth(&h) {
return failure(StatusCode::UNAUTHORIZED, "unauthorized");
}
axum::Json(p.connection.status()).into_response()
}