mod api;
mod schedule;
use axum::middleware;
use axum::routing::post;
use axum::Router;
use clap::Parser;
use eclipse_web::app::{self, Shared};
use eclipse_web::startup::{self, Options};
use std::path::PathBuf;
#[derive(Parser)]
#[command(
name = "eclipse-gateway",
version,
about = "Dashboard, API and scheduled checks on one pid"
)]
struct Args {
#[arg(long, env = "ECLIPSE_CONFIG")]
config: Option<PathBuf>,
#[arg(long)]
host: Option<String>,
#[arg(long)]
port: Option<u16>,
#[arg(long, env = "ECLIPSE_PROFILE")]
profile: Option<String>,
}
fn gateway_router(state: Shared) -> Router {
let api = Router::new()
.route("/v1/chat/completions", post(api::chat_completions))
.layer(middleware::from_fn_with_state(
state.clone(),
app::guard_local_origin,
));
app::routes(state.clone()).merge(api).with_state(state)
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let args = Args::parse();
let opts = Options {
config: args.config,
host: args.host,
port: args.port,
profile: args.profile,
};
let prepared = startup::prepare(&opts).await?;
let state = prepared.state.clone();
let addr = prepared.addr;
schedule::spawn_model_probe(state.clone(), prepared.cfg.clone());
if let Some(dir) = eclipse_core::config::state_dir(&eclipse_core::config::process_env) {
schedule::spawn_upgrade_check(prepared.cfg.clone(), dir);
}
schedule::spawn_session_prune(state.clone(), prepared.cfg.clone());
startup::serve(
prepared,
gateway_router(state),
&format!("eclipse gateway on http://{addr} — dashboard, /v1/chat/completions, health"),
)
.await
}
#[cfg(test)]
mod tests {
use super::*;
use async_trait::async_trait;
use axum::body::Body;
use axum::http::{Request, StatusCode};
use eclipse_core::error::Result as CoreResult;
use eclipse_core::message::Message;
use eclipse_core::provider::ChatProvider;
use eclipse_core::runtime::Agent;
use eclipse_core::session::SessionStore;
use eclipse_core::tools::{ToolRegistry, ToolSpec};
use eclipse_web::app::AppState;
use std::sync::Arc;
use tower::ServiceExt;
const TOKEN: &str = "0123456789abcdef0123456789abcdef";
struct Canned;
#[async_trait]
impl ChatProvider for Canned {
async fn chat(&self, _: &[Message], _: &[ToolSpec]) -> CoreResult<Message> {
Ok(Message::assistant("canned reply"))
}
}
struct Unreachable;
#[async_trait]
impl ChatProvider for Unreachable {
async fn chat(&self, _: &[Message], _: &[ToolSpec]) -> CoreResult<Message> {
Err(eclipse_core::Error::provider(
"could not reach http://10.1.2.3:9/v1/chat/completions: connection refused",
))
}
}
struct Counting(Arc<std::sync::atomic::AtomicUsize>);
#[async_trait]
impl ChatProvider for Counting {
async fn chat(&self, _: &[Message], _: &[ToolSpec]) -> CoreResult<Message> {
self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
Ok(Message::assistant("canned reply"))
}
}
fn state(dir: &std::path::Path) -> Shared {
state_with(dir, Arc::new(Canned))
}
fn state_with(dir: &std::path::Path, provider: Arc<dyn ChatProvider>) -> Shared {
let store = SessionStore::new(dir.join("sessions"));
let agent = Arc::new(Agent::new(
provider,
Arc::new(ToolRegistry::default()),
store.clone(),
"sys".into(),
3,
));
Arc::new(AppState::new(
Some(agent),
store,
"test-<model>".into(),
None,
TOKEN.into(),
std::time::Duration::from_secs(3600),
))
}
fn req(body: serde_json::Value, bearer: Option<&str>) -> Request<Body> {
req_raw(&body.to_string(), bearer)
}
fn req_raw(body: &str, bearer: Option<&str>) -> Request<Body> {
let mut b = Request::post("/v1/chat/completions")
.header("host", "127.0.0.1:8787")
.header("content-type", "application/json");
if let Some(t) = bearer {
b = b.header("authorization", format!("Bearer {t}"));
}
b.body(Body::from(body.to_string())).unwrap()
}
async fn body_text(r: axum::response::Response) -> String {
let bytes = axum::body::to_bytes(r.into_body(), 64 * 1024)
.await
.unwrap_or_default();
String::from_utf8_lossy(&bytes).into_owned()
}
#[tokio::test]
async fn a_v1_call_with_the_bearer_token_gets_a_completion() {
let dir = tempfile::tempdir().unwrap();
let resp = gateway_router(state(dir.path()))
.oneshot(req(
serde_json::json!({"messages": [{"role": "user", "content": "hello"}]}),
Some(TOKEN),
))
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let v: serde_json::Value = serde_json::from_str(&body_text(resp).await).unwrap();
assert_eq!(v["object"], "chat.completion");
assert_eq!(v["choices"][0]["message"]["content"], "canned reply");
}
#[tokio::test]
async fn a_v1_call_that_asks_for_a_background_task_is_refused() {
let dir = tempfile::tempdir().unwrap();
let resp = gateway_router(state(dir.path()))
.oneshot(req(
serde_json::json!({"messages": [{"role": "user", "content": "/bg count the files"}]}),
Some(TOKEN),
))
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let said = body_text(resp).await;
assert!(said.contains("/bg"), "{said}");
assert!(said.contains("the gateway"), "{said}");
}
#[tokio::test]
async fn a_v1_call_leaves_a_session_tagged_as_the_api_s() {
let dir = tempfile::tempdir().unwrap();
let store = SessionStore::new(dir.path().join("sessions"));
let resp = gateway_router(state(dir.path()))
.oneshot(req(
serde_json::json!({"messages": [{"role": "user", "content": "hello"}]}),
Some(TOKEN),
))
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let sessions = store.list().unwrap();
assert_eq!(sessions.len(), 1, "the run wrote one: {}", sessions.len());
assert_eq!(sessions[0].origin, SessionStore::API_ORIGIN);
assert!(
sessions[0].subagent().is_none(),
"an API call is not a subagent"
);
}
#[tokio::test]
async fn the_v1_route_takes_the_same_concurrency_slot_as_the_dashboard() {
let dir = tempfile::tempdir().unwrap();
let st = state(dir.path());
let held: Vec<_> = (0..eclipse_web::app::MAX_CONCURRENT_CHATS)
.map(|n| {
st.try_chat_slot()
.unwrap_or_else(|| panic!("slot {n} is free"))
})
.collect();
let body = serde_json::json!({"messages": [{"role": "user", "content": "hello"}]});
let resp = gateway_router(st.clone())
.oneshot(req(body.clone(), Some(TOKEN)))
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::TOO_MANY_REQUESTS);
let text = body_text(resp).await;
assert!(text.contains("too many chats"), "{text}");
drop(held);
let resp = gateway_router(st)
.oneshot(req(body, Some(TOKEN)))
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn a_v1_call_without_a_bearer_token_is_refused() {
let dir = tempfile::tempdir().unwrap();
let resp = gateway_router(state(dir.path()))
.oneshot(req(
serde_json::json!({"messages": [{"role": "user", "content": "hello"}]}),
None,
))
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn a_body_that_will_not_parse_is_refused_for_its_token_not_its_json() {
let dir = tempfile::tempdir().unwrap();
let resp = gateway_router(state(dir.path()))
.oneshot(req_raw("{\"messages\": [", None))
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
let said = body_text(resp).await;
assert!(said.contains("auth_error"), "{said}");
let resp = gateway_router(state(dir.path()))
.oneshot(req_raw("{\"messages\": [", Some(TOKEN)))
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let v: serde_json::Value = serde_json::from_str(&body_text(resp).await).unwrap();
assert_eq!(v["error"]["type"], "invalid_request_error", "{v}");
assert!(
v["error"]["message"]
.as_str()
.unwrap_or("")
.contains("body"),
"{v}"
);
}
#[tokio::test]
async fn a_body_of_the_wrong_shape_is_a_400_in_the_openai_envelope() {
let dir = tempfile::tempdir().unwrap();
let wrong_shape = "{\"messages\": \"not a list\"}";
let resp = gateway_router(state(dir.path()))
.oneshot(req_raw(wrong_shape, None))
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
let resp = gateway_router(state(dir.path()))
.oneshot(req_raw(wrong_shape, Some(TOKEN)))
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let v: serde_json::Value = serde_json::from_str(&body_text(resp).await).unwrap();
assert_eq!(v["error"]["type"], "invalid_request_error", "{v}");
assert!(
v["error"]["message"]
.as_str()
.unwrap_or("")
.starts_with("the request body"),
"{v}"
);
}
#[tokio::test]
async fn a_backend_that_does_not_answer_is_a_502_without_its_address() {
let dir = tempfile::tempdir().unwrap();
let resp = gateway_router(state_with(dir.path(), Arc::new(Unreachable)))
.oneshot(req(
serde_json::json!({"messages": [{"role": "user", "content": "hello"}]}),
Some(TOKEN),
))
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_GATEWAY);
let said = body_text(resp).await;
let v: serde_json::Value = serde_json::from_str(&said).unwrap();
assert_eq!(v["error"]["type"], "server_error", "{said}");
assert!(!said.contains("10.1.2.3"), "the endpoint leaked: {said}");
assert!(
!said.contains("connection refused"),
"the backend's words leaked: {said}"
);
}
#[tokio::test]
async fn a_call_that_cannot_tag_its_session_is_refused_instead_of_run_untagged() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("sessions"), b"not a directory").unwrap();
let asked = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let resp = gateway_router(state_with(dir.path(), Arc::new(Counting(asked.clone()))))
.oneshot(req(
serde_json::json!({"messages": [{"role": "user", "content": "hello"}]}),
Some(TOKEN),
))
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
assert_eq!(
asked.load(std::sync::atomic::Ordering::SeqCst),
0,
"the model was asked for a call that could not be tagged"
);
let said = body_text(resp).await;
let v: serde_json::Value = serde_json::from_str(&said).unwrap();
assert_eq!(v["error"]["type"], "server_error", "{said}");
assert!(
!said.contains("not a directory") && !said.contains(dir.path().to_str().unwrap()),
"the store's complaint leaked: {said}"
);
}
#[tokio::test]
async fn a_v1_call_with_a_browser_cookie_only_is_refused() {
let dir = tempfile::tempdir().unwrap();
let mut r = req(
serde_json::json!({"messages": [{"role": "user", "content": "hello"}]}),
None,
);
r.headers_mut()
.insert("cookie", "eclipse_session=whatever".parse().unwrap());
let resp = gateway_router(state(dir.path())).oneshot(r).await.unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn a_v1_call_asking_for_a_stream_is_refused_honestly() {
let dir = tempfile::tempdir().unwrap();
let resp = gateway_router(state(dir.path()))
.oneshot(req(
serde_json::json!({"messages": [{"role": "user", "content": "hi"}], "stream": true}),
Some(TOKEN),
))
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn a_v1_call_asking_for_several_choices_is_refused() {
let dir = tempfile::tempdir().unwrap();
let resp = gateway_router(state(dir.path()))
.oneshot(req(
serde_json::json!({"messages": [{"role": "user", "content": "hi"}], "n": 3}),
Some(TOKEN),
))
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let body = axum::body::to_bytes(resp.into_body(), 8192).await.unwrap();
assert!(
String::from_utf8_lossy(&body).contains("n = 3 is not supported"),
"{}",
String::from_utf8_lossy(&body)
);
let resp = gateway_router(state(dir.path()))
.oneshot(req(
serde_json::json!({"messages": [{"role": "user", "content": "hi"}], "n": 1}),
Some(TOKEN),
))
.await
.unwrap();
assert_ne!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn a_v1_call_with_no_text_is_refused() {
let dir = tempfile::tempdir().unwrap();
let resp = gateway_router(state(dir.path()))
.oneshot(req(
serde_json::json!({"messages": [{"role": "user", "content": ""}]}),
Some(TOKEN),
))
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn the_dashboard_is_still_served_from_the_same_router() {
let dir = tempfile::tempdir().unwrap();
let resp = gateway_router(state(dir.path()))
.oneshot(
Request::get("/healthz")
.header("host", "127.0.0.1:8787")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
}