Skip to content
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 60 additions & 12 deletions src/commands/cmd_serve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ fn run_serve(
// Decision checkpoints get their own endpoint: rac_server is LLM-only,
// so a decision model reference serves POST /v1/decisions in-process.
if !reference.is_empty() && is_decision_reference(reference) {
return run_serve_decisions(options, reference, host, port);
return run_serve_decisions(options, reference, host, port, cors);
}

let model = match ensure_model_ready(
Expand Down Expand Up @@ -327,12 +327,30 @@ fn parse_head(head: &[u8]) -> Result<(String, String, usize), String> {
/// Best-effort response on a nonblocking connection, with one size-dependent
/// absolute write budget shared by the headers and body. Progress never
/// renews it; responses that cannot finish within the capped budget close.
/// When `cors` is set, every response carries the same headers the SDK's LLM
/// server adds in its pre-routing handler, error responses included.
#[cfg(wally_has_server)]
fn write_response(stream: &mut std::net::TcpStream, status: u16, reason: &str, body: &str) {
fn write_response(
stream: &mut std::net::TcpStream,
status: u16,
reason: &str,
body: &str,
cors: bool,
) {
use std::io::{ErrorKind, Write};
let cors_headers = if cors {
"Access-Control-Allow-Origin: *\r\nAccess-Control-Allow-Methods: GET, POST, OPTIONS\r\nAccess-Control-Allow-Headers: Content-Type, Authorization\r\n"
} else {
""
};
// RFC 9110 section 8.6 forbids Content-Length on 204, even when zero.
let content_length = if status == 204 {
String::new()
} else {
format!("Content-Length: {}\r\n", body.len())
};
let head = format!(
"HTTP/1.1 {status} {reason}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
body.len()
"HTTP/1.1 {status} {reason}\r\nContent-Type: application/json\r\n{content_length}Connection: close\r\n{cors_headers}\r\n"
);
let transfer =
std::time::Duration::from_secs_f64(body.len() as f64 / SERVE_WRITE_BYTES_PER_SECOND as f64);
Expand Down Expand Up @@ -369,6 +387,7 @@ fn json_error(message: &str) -> String {
fn handle_decisions_connection(
stream: &mut std::net::TcpStream,
loaded: &crate::commands::cmd_decisions::LoadedDecisions,
cors: bool,
) {
let header_deadline = std::time::Instant::now() + SERVE_HEADER_TIMEOUT;
let mut raw: Vec<u8> = Vec::new();
Expand All @@ -384,6 +403,7 @@ fn handle_decisions_connection(
431,
"Request Header Fields Too Large",
&json_error("headers too large"),
cors,
);
return;
}
Expand All @@ -397,6 +417,7 @@ fn handle_decisions_connection(
408,
"Request Timeout",
&json_error("request timed out"),
cors,
);
return;
}
Expand All @@ -406,18 +427,24 @@ fn handle_decisions_connection(
let (method, path, length) = match parse_head(&raw[..head_end]) {
Ok(parsed) => parsed,
Err(message) => {
write_response(stream, 400, "Bad Request", &json_error(&message));
write_response(stream, 400, "Bad Request", &json_error(&message), cors);
return;
}
};
// Preflight, before any method/path routing, the way the SDK's LLM server
// answers it. Without --cors, OPTIONS keeps falling through to the 404.
if cors && method == "OPTIONS" {
write_response(stream, 204, "No Content", "", cors);
return;
}
if path == "/health" && method == "GET" {
let mut json = crate::io::output::JsonWriter::new();
json.begin_object().field_str("status", "ok").end_object();
write_response(stream, 200, "OK", json.str());
write_response(stream, 200, "OK", json.str(), cors);
return;
}
if method != "POST" || path != "/v1/decisions" {
write_response(stream, 404, "Not Found", &json_error("not found"));
write_response(stream, 404, "Not Found", &json_error("not found"), cors);
return;
}
if length > MAX_SERVE_BODY_BYTES {
Expand All @@ -426,6 +453,7 @@ fn handle_decisions_connection(
413,
"Content Too Large",
&json_error("request body exceeds 1 MiB"),
cors,
);
return;
}
Expand All @@ -441,6 +469,7 @@ fn handle_decisions_connection(
408,
"Request Timeout",
&json_error("request timed out"),
cors,
);
return;
}
Expand All @@ -454,6 +483,7 @@ fn handle_decisions_connection(
400,
"Bad Request",
&json_error("truncated request body"),
cors,
);
return;
}
Expand All @@ -466,6 +496,7 @@ fn handle_decisions_connection(
400,
"Bad Request",
&json_error("invalid request JSON"),
cors,
);
return;
}
Expand All @@ -480,6 +511,7 @@ fn handle_decisions_connection(
"request has fields the decisions contract does not define: {}",
unknown.join(", ")
)),
cors,
);
return;
}
Expand All @@ -493,12 +525,13 @@ fn handle_decisions_connection(
&json_error(&format!(
"request does not match the decisions contract: {error}"
)),
cors,
);
return;
}
};
if let Err(error) = crate::commands::cmd_decisions::validate(&request) {
write_response(stream, 400, "Bad Request", &json_error(&error));
write_response(stream, 400, "Bad Request", &json_error(&error), cors);
return;
}
if SERVE_STOP.load(Ordering::SeqCst) {
Expand All @@ -513,19 +546,34 @@ fn handle_decisions_connection(
200,
"OK",
&crate::io::json::dump(&response.to_json()),
cors,
);
}
Err(message) => {
write_response(stream, 500, "Internal Server Error", &json_error(&message));
write_response(
stream,
500,
"Internal Server Error",
&json_error(&message),
cors,
);
}
}
}

/// Serve a local decision checkpoint over HTTP: one model loaded once, then
/// POST /v1/decisions per request plus GET /health. Mirrors the CLI's
/// validation so the same body behaves the same in both.
/// validation so the same body behaves the same in both. `--cors` adds the
/// same headers the SDK's LLM server applies and answers preflight before
/// routing.
#[cfg(wally_has_server)]
fn run_serve_decisions(options: &GlobalOptions, reference: &str, host: &str, port: u16) -> i32 {
fn run_serve_decisions(
options: &GlobalOptions,
reference: &str,
host: &str,
port: u16,
cors: bool,
) -> i32 {
if bootstrap::bootstrap(options).is_err() {
return 1;
}
Expand Down Expand Up @@ -574,7 +622,7 @@ fn run_serve_decisions(options: &GlobalOptions, reference: &str, host: &str, por
error_line(&format!("could not set connection non-blocking: {error}"));
continue;
}
handle_decisions_connection(&mut stream, &loaded);
handle_decisions_connection(&mut stream, &loaded, cors);
}
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
std::thread::sleep(std::time::Duration::from_millis(50));
Expand Down
Loading