pub mod actions;
use std::convert::Infallible;
use std::net::SocketAddr;
use std::sync::Arc;
use bytes::Bytes;
use http_body_util::{BodyExt, Full, Limited};
use hyper::body::{Body, Incoming};
use hyper::server::conn::http1;
use hyper::service::service_fn;
use hyper::{Request, Response};
use hyper_util::rt::TokioIo;
use tokio::sync::mpsc;
use tracing::error;
use crate::llm::ollama_client::OllamaClient;
use crate::llm::ActionResult;
use crate::logging::emit::Log;
use crate::server::accept_bounded::{
accept_bounded, watch_idle, ConnectionActivity, ConnectionLimiter,
};
use crate::server::connection::ConnectionId;
use crate::server::SqsProtocol;
use crate::state::app_state::AppState;
use crate::{console_error, console_info};
pub const MAX_REQUEST_BYTES: usize = 4 * 1024 * 1024;
const FIRST_BYTE_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
const IDLE_BETWEEN_REQUESTS_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(180);
const MAX_CONNECTIONS: usize = crate::server::accept_bounded::DEFAULT_MAX_CONNECTIONS;
const CONNECTION_CAP_REFUSAL: &[u8] = b"HTTP/1.1 503 Service Unavailable\r\n\
Content-Length: 0\r\nRetry-After: 5\r\nConnection: close\r\n\r\n";
pub struct SqsServer;
impl SqsServer {
pub async fn spawn_with_llm_actions(
listen_addr: SocketAddr,
llm_client: OllamaClient,
app_state: Arc<AppState>,
status_tx: mpsc::UnboundedSender<String>,
_send_first: bool,
server_id: crate::state::ServerId,
) -> anyhow::Result<SocketAddr> {
let listener =
crate::server::socket_helpers::create_reusable_tcp_listener(listen_addr).await?;
let local_addr = listener.local_addr()?;
console_info!(status_tx, "SQS server listening on {}", local_addr);
let protocol = Arc::new(SqsProtocol::new());
let task_registrar = app_state.clone();
let limiter = ConnectionLimiter::new(MAX_CONNECTIONS);
let accept_handle = tokio::spawn(async move {
loop {
match accept_bounded(
&listener,
&limiter,
CONNECTION_CAP_REFUSAL,
"SQS",
Some(&status_tx),
)
.await
{
Ok((stream, remote_addr, permit)) => {
let connection_id =
ConnectionId::new(app_state.get_next_unified_id().await);
let local_addr_conn = stream.local_addr().unwrap_or(local_addr);
Log::new(Some(&status_tx)).info(format!(
"SQS connection {} from {}",
connection_id, remote_addr
));
use crate::state::server::{
ConnectionState as ServerConnectionState, ConnectionStatus,
ProtocolConnectionInfo,
};
let now = crate::utils::clock::Instant::now();
let conn_state = ServerConnectionState {
id: connection_id,
remote_addr,
local_addr: local_addr_conn,
bytes_sent: 0,
bytes_received: 0,
packets_sent: 0,
packets_received: 0,
last_activity: now,
status: ConnectionStatus::Active,
status_changed_at: now,
protocol_info: ProtocolConnectionInfo::empty(),
};
app_state
.add_connection_to_server(server_id, conn_state)
.await;
let _ = status_tx.send("__UPDATE_UI__".to_string());
let llm_client_clone = llm_client.clone();
let app_state_clone = app_state.clone();
let status_tx_clone = status_tx.clone();
let protocol_clone = protocol.clone();
let task_owner = app_state.clone();
task_owner
.spawn_server_task(server_id, async move {
let _permit = permit;
let spoke = matches!(
tokio::time::timeout(
FIRST_BYTE_READ_TIMEOUT,
stream.peek(&mut [0u8; 1]),
)
.await,
Ok(Ok(n)) if n > 0
);
if spoke {
let io = TokioIo::new(stream);
let status_for_service = status_tx_clone.clone();
let app_state_for_service = app_state_clone.clone();
let activity = Arc::new(ConnectionActivity::new());
let activity_for_service = Arc::clone(&activity);
let service = service_fn(move |req: Request<Incoming>| {
let llm_clone = llm_client_clone.clone();
let state_clone = app_state_for_service.clone();
let status_clone = status_for_service.clone();
let protocol_clone = protocol_clone.clone();
let activity = Arc::clone(&activity_for_service);
async move {
let _busy = activity.busy();
handle_sqs_request_with_llm(
req,
connection_id,
llm_clone,
state_clone,
status_clone,
protocol_clone,
server_id,
)
.await
}
});
let conn = http1::Builder::new().serve_connection(io, service);
tokio::pin!(conn);
tokio::select! {
result = &mut conn => {
if let Err(err) = result {
error!("Error serving SQS connection: {:?}", err);
}
}
_ = watch_idle(
Arc::clone(&activity),
IDLE_BETWEEN_REQUESTS_TIMEOUT,
) => {
Log::new(Some(&status_tx_clone)).debug(format!(
"SQS connection {} idle for {}s; closing",
connection_id,
IDLE_BETWEEN_REQUESTS_TIMEOUT.as_secs()
));
}
}
} else {
Log::new(Some(&status_tx_clone)).debug(format!(
"SQS peer {} sent no request within {}s; closing \
decision=fail_closed_first_byte_timeout",
remote_addr,
FIRST_BYTE_READ_TIMEOUT.as_secs()
));
}
app_state_clone
.close_connection_on_server(server_id, connection_id)
.await;
Log::new(Some(&status_tx_clone))
.info(format!("SQS connection {} closed", connection_id));
let _ = status_tx_clone.send("__UPDATE_UI__".to_string());
})
.await;
}
Err(e) => {
console_error!(status_tx, "Failed to accept SQS connection: {}", e);
break;
}
}
}
});
task_registrar
.register_server_task(server_id, accept_handle)
.await;
Ok(local_addr)
}
}
async fn handle_sqs_request_with_llm(
req: Request<Incoming>,
connection_id: ConnectionId,
llm_client: OllamaClient,
app_state: Arc<AppState>,
status_tx: mpsc::UnboundedSender<String>,
protocol: Arc<SqsProtocol>,
server_id: crate::state::ServerId,
) -> Result<Response<Full<Bytes>>, Infallible> {
let received = req.body().size_hint().lower();
let response = handle_sqs_request_inner(
req,
llm_client,
app_state.clone(),
status_tx.clone(),
protocol,
server_id,
)
.await;
let sent = response
.as_ref()
.ok()
.and_then(|resp| resp.body().size_hint().exact())
.unwrap_or(0);
app_state
.update_connection_stats(
server_id,
connection_id,
Some(received),
Some(sent),
Some(1),
Some(1),
)
.await;
let _ = status_tx.send("__UPDATE_UI__".to_string());
response
}
async fn handle_sqs_request_inner(
req: Request<Incoming>,
llm_client: OllamaClient,
app_state: Arc<AppState>,
status_tx: mpsc::UnboundedSender<String>,
protocol: Arc<SqsProtocol>,
server_id: crate::state::ServerId,
) -> Result<Response<Full<Bytes>>, Infallible> {
let method = req.method().to_string();
let uri = req.uri().to_string();
let operation = req
.headers()
.get("x-amz-target")
.and_then(|v| v.to_str().ok())
.and_then(|s| s.split('.').nth(1))
.unwrap_or("Unknown")
.to_string();
let body_bytes = match Limited::new(req.into_body(), MAX_REQUEST_BYTES)
.collect()
.await
{
Ok(collected) => collected.to_bytes(),
Err(e) => {
Log::new(Some(&status_tx)).warn(format!(
"SQS {} decision=fail_closed_body_rejected (limit {} bytes): {}",
operation, MAX_REQUEST_BYTES, e
));
return Ok(build_sqs_response(
413,
&new_request_id(),
serde_json::json!({
"__type": "InvalidParameterValue",
"message": "request body rejected",
})
.to_string(),
));
}
};
let body_str = String::from_utf8_lossy(&body_bytes).to_string();
Log::new(Some(&status_tx)).debug(format!(
"SQS request: {} {} operation={} ({} bytes)",
method,
uri,
operation,
body_bytes.len()
));
let queue_url = if !body_str.is_empty() {
serde_json::from_str::<serde_json::Value>(&body_str)
.ok()
.and_then(|v| v.get("QueueUrl").and_then(|q| q.as_str()).map(String::from))
} else {
None
};
Log::new(Some(&status_tx)).trace(format!("SQS request body: {}", body_str));
let event = crate::protocol::Event::new(
&actions::SQS_REQUEST_EVENT,
serde_json::json!({
"operation": operation,
"queue_url": queue_url,
"request_body": body_str,
}),
);
let llm_result = crate::llm::action_helper::call_llm(
&llm_client,
&app_state,
server_id,
None, &event,
protocol.as_ref(),
)
.await;
match llm_result {
Ok(execution_result) => {
for result in execution_result.protocol_results {
match result {
ActionResult::Custom { name, data } => {
if name == "sqs_response" {
let status =
data.get("status").and_then(|v| v.as_u64()).unwrap_or(200) as u16;
let body = data.get("body").and_then(|v| v.as_str()).unwrap_or("{}");
let decision = if (400..=599).contains(&status) {
"model_reject"
} else {
"model_answer"
};
let log = Log::new(Some(&status_tx));
log.debug(format!(
"SQS {} decision={} status={}",
operation, decision, status
));
log.trace(format!("SQS response body: {}", body));
let request_id = new_request_id();
return Ok(build_sqs_response(status, &request_id, body.to_string()));
}
}
_ => {
}
}
}
Log::new(Some(&status_tx)).warn(format!(
"SQS {} decision=fail_closed_no_action (no sqs_response action produced); \
answering 500 rather than an empty 200",
operation
));
let request_id = new_request_id();
Ok(build_sqs_response(
500,
&request_id,
serde_json::json!({
"__type": "InternalFailure",
"message": crate::utils::WireFailure::Unavailable.prefixed_text(),
})
.to_string(),
))
}
Err(e) => {
let failure = crate::utils::WireFailure::classify(&e);
Log::new(Some(&status_tx)).warn(format!(
"SQS {} decision=fail_closed_llm_error category={:?}: {}",
operation, failure, e
));
let (status, aws_type) = match failure {
crate::utils::WireFailure::Overloaded => (503, "ServiceUnavailable"),
crate::utils::WireFailure::Unavailable => (500, "InternalFailure"),
};
let mut response = build_sqs_response(
status,
&new_request_id(),
serde_json::json!({
"__type": aws_type,
"message": failure.text(),
})
.to_string(),
);
if failure == crate::utils::WireFailure::Overloaded {
response
.headers_mut()
.insert("Retry-After", hyper::header::HeaderValue::from_static("5"));
}
Ok(response)
}
}
}
fn build_sqs_response(status: u16, request_id: &str, body: String) -> Response<Full<Bytes>> {
let status = hyper::StatusCode::from_u16(status).unwrap_or_else(|_| {
error!("Invalid SQS status code {}, sending 500 instead", status);
hyper::StatusCode::INTERNAL_SERVER_ERROR
});
Response::builder()
.status(status)
.header("Content-Type", "application/x-amz-json-1.0")
.header("x-amzn-RequestId", request_id)
.body(Full::new(Bytes::from(body)))
.unwrap_or_else(|_| Response::new(Full::new(Bytes::from("{}"))))
}
fn new_request_id() -> String {
format!(
"{:x}",
crate::utils::clock::SystemTime::now()
.duration_since(crate::utils::clock::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0)
)
}