pub mod a2a_node;
pub mod a2a_pack_routes;
#[cfg(feature = "agentic-worker")]
pub(crate) mod a2a_pack_source;
pub mod adapt_events_email;
pub mod adapt_timer;
pub mod agent_node;
pub mod approval_http;
pub(crate) mod approval_token;
#[cfg(all(feature = "agentic-worker", feature = "greentic-llm-backend"))]
pub(crate) mod artifact_reader_wiring;
#[cfg(feature = "agentic-worker")]
pub(crate) mod aw_backends;
pub mod card_nav;
pub mod component_invoker;
pub mod contract_cache;
pub mod contract_introspection;
pub mod dispatch_listener;
pub mod engine;
#[cfg(feature = "agentic-worker")]
pub(crate) mod run_context_policy;
pub mod run_context_routes;
#[cfg(feature = "agentic-worker")]
pub(crate) mod user_ledger_policy;
pub mod user_ledger_routes;
#[cfg(all(feature = "agentic-worker", feature = "greentic-llm-backend"))]
pub(crate) mod ext_llm_port;
#[cfg(feature = "agentic-worker")]
pub mod ext_artifact_port;
pub mod flow_adapter;
#[cfg(feature = "agentic-worker")]
pub mod flow_invoker;
pub mod graph_node;
pub mod i18n;
pub mod invocation;
#[cfg(feature = "agentic-worker")]
pub mod knowledge_corpus;
#[cfg(feature = "agentic-worker")]
pub mod knowledge_ext;
#[cfg(feature = "agentic-worker")]
pub mod knowledge_index;
pub mod mcp_node;
pub mod mcp_pack_routes;
#[cfg(feature = "agentic-worker")]
pub mod mcp_warm_listener;
#[cfg(feature = "agentic-worker")]
pub mod media_node;
#[cfg(feature = "agentic-worker")]
pub mod media_render;
pub mod mocks;
pub mod nested_flow;
pub mod operala_node;
#[cfg(feature = "operala-in-process")]
pub mod operala_tools;
pub mod playbook_invoker;
pub mod playbook_turn;
#[cfg(feature = "operala-in-process")]
pub(crate) mod metered_llm;
pub mod operator;
#[cfg(feature = "agentic-worker")]
pub mod pack_extensions;
pub mod remote_dispatch;
#[cfg(feature = "agentic-worker")]
pub mod runtime_ext;
pub mod runtime_session_resumer;
pub mod schema_validator;
#[cfg(feature = "agentic-worker")]
pub(crate) mod sorla_node;
pub mod sorla_pack_routes;
#[cfg(feature = "agentic-worker")]
pub(crate) mod sorla_pack_source;
#[cfg(feature = "agentic-worker")]
pub mod sorla_route;
#[cfg(feature = "agentic-worker")]
pub mod sorx_invoker;
pub mod templating;
use std::net::SocketAddr;
use std::sync::Arc;
use anyhow::Result;
use axum::response::IntoResponse as _;
use axum::routing::{get, post};
use axum::{Router, serve};
use tokio::net::TcpListener;
use crate::host::RunnerHost;
use crate::http::{self, admin, auth::AdminAuth, health::HealthState};
use crate::routing::TenantRouting;
use crate::runtime::ActivePacks;
use crate::sql::SqlGateway;
use crate::watcher::PackReloadHandle;
pub struct HostServer {
addr: SocketAddr,
router: Router,
_state: ServerState,
}
impl HostServer {
pub fn new(
port: u16,
active: Arc<ActivePacks>,
routing: TenantRouting,
health: Arc<HealthState>,
reload: Option<PackReloadHandle>,
admin: AdminAuth,
host: Arc<RunnerHost>,
) -> Result<Self> {
Self::with_sql(port, active, routing, health, reload, admin, host, None)
}
#[allow(clippy::too_many_arguments)]
pub fn with_sql(
port: u16,
active: Arc<ActivePacks>,
routing: TenantRouting,
health: Arc<HealthState>,
reload: Option<PackReloadHandle>,
admin: AdminAuth,
host: Arc<RunnerHost>,
sql_gateway: Option<SqlGateway>,
) -> Result<Self> {
let addr = SocketAddr::from(([0, 0, 0, 0], port));
let sql = sql_gateway
.unwrap_or_else(|| SqlGateway::new(std::collections::HashMap::new(), String::new()));
let state = ServerState {
active,
routing,
health,
reload,
admin,
#[cfg(feature = "agentic-worker")]
stream_observers: host.stream_observers(),
#[cfg(feature = "agentic-worker")]
ext_runtime: crate::runner::agent_node::build_ext_runtime(
std::sync::Arc::new(crate::runner::agent_node::EnvSecretsBackend),
None,
None,
None,
&[],
),
host,
sql,
};
let router = router(state.clone());
Ok(Self {
addr,
router,
_state: state,
})
}
pub async fn serve(self) -> Result<()> {
self.serve_with_shutdown(std::future::pending::<()>()).await
}
pub async fn serve_with_shutdown<F>(self, shutdown: F) -> Result<()>
where
F: std::future::Future<Output = ()> + Send + 'static,
{
tracing::info!(addr = %self.addr, "starting host server");
if !self._state.admin.operator_protected() {
tracing::warn!(
addr = %self.addr,
"POST /operator/op/invoke is UNAUTHENTICATED and bound to {}: set OPERATOR_TOKEN \
(or ADMIN_TOKEN) to require a bearer token",
self.addr
);
}
let listener = TcpListener::bind(self.addr).await?;
serve(
listener,
self.router
.into_make_service_with_connect_info::<SocketAddr>(),
)
.with_graceful_shutdown(shutdown)
.await?;
Ok(())
}
}
pub(crate) fn router(state: ServerState) -> Router {
with_request_timeout(
base_router(state),
request_timeout_from_raw(std::env::var(REQUEST_TIMEOUT_ENV).ok().as_deref()),
)
}
pub(crate) const REQUEST_TIMEOUT_ENV: &str = "GREENTIC_HTTP_REQUEST_TIMEOUT_SECS";
const DEFAULT_REQUEST_TIMEOUT_SECS: u64 = 60;
const LONG_RUNNING_PATHS: &[&str] = &["/agent/chat", "/agent/chat/stream", "/operator/op/invoke"];
pub(crate) fn is_long_running_path(path: &str) -> bool {
LONG_RUNNING_PATHS.contains(&path)
}
pub(crate) fn request_timeout_from_raw(raw: Option<&str>) -> Option<std::time::Duration> {
let secs = raw
.and_then(|v| v.trim().parse::<u64>().ok())
.unwrap_or(DEFAULT_REQUEST_TIMEOUT_SECS);
(secs > 0).then(|| std::time::Duration::from_secs(secs))
}
pub(crate) fn with_request_timeout(router: Router, timeout: Option<std::time::Duration>) -> Router {
let Some(timeout) = timeout else {
return router;
};
router.layer(axum::middleware::from_fn(
move |req: axum::extract::Request, next: axum::middleware::Next| async move {
if is_long_running_path(req.uri().path()) {
return next.run(req).await;
}
match tokio::time::timeout(timeout, next.run(req)).await {
Ok(response) => response,
Err(_) => axum::http::StatusCode::REQUEST_TIMEOUT.into_response(),
}
},
))
}
fn base_router(state: ServerState) -> Router {
let operator_routes = Router::new()
.route("/operator/op/invoke", post(operator::invoke))
.route_layer(axum::middleware::from_fn_with_state(
state.clone(),
crate::http::auth::require_operator,
));
let router = Router::new()
.merge(operator_routes)
.route("/healthz", get(http::health::handler))
.route("/admin/packs/status", get(admin::status))
.route("/admin/packs/reload", post(admin::reload))
.route("/agent/chat", post(crate::http::agent_chat::agent_chat));
#[cfg(feature = "agentic-worker")]
let router = router
.route(
"/agent/chat/stream",
post(crate::http::agent_chat::agent_chat_stream),
)
.route("/admin/capabilities", get(admin::capabilities));
router
.route(
"/sql/{conn}/schema",
get(crate::sql::routes::schema_handler),
)
.route("/sql/{conn}/query", post(crate::sql::routes::query_handler))
.with_state(state)
}
#[derive(Clone)]
pub struct ServerState {
pub active: Arc<ActivePacks>,
pub routing: TenantRouting,
pub health: Arc<HealthState>,
pub reload: Option<PackReloadHandle>,
pub admin: AdminAuth,
pub host: Arc<RunnerHost>,
pub sql: SqlGateway,
#[cfg(feature = "agentic-worker")]
pub stream_observers: crate::http::agent_stream::StreamObserverRegistry,
#[cfg(feature = "agentic-worker")]
pub ext_runtime: Option<std::sync::Arc<greentic_ext_runtime::ExtensionRuntime>>,
}
impl ServerState {
#[cfg(all(test, feature = "agentic-worker"))]
pub(crate) fn for_test() -> Self {
let host = RunnerHost::for_test();
Self {
active: Arc::new(ActivePacks::new()),
routing: TenantRouting::new(crate::routing::RoutingConfig::default()),
health: Arc::new(HealthState::new()),
reload: None,
admin: AdminAuth::default(),
#[cfg(feature = "agentic-worker")]
stream_observers: host.stream_observers(),
#[cfg(feature = "agentic-worker")]
ext_runtime: None,
host,
sql: SqlGateway::new(std::collections::HashMap::new(), String::new()),
}
}
}
impl axum::extract::FromRef<ServerState> for SqlGateway {
fn from_ref(state: &ServerState) -> Self {
state.sql.clone()
}
}
#[cfg(test)]
mod request_timeout_tests {
use super::*;
use axum::body::Body;
use axum::http::{Request, StatusCode};
use std::time::Duration;
use tower::ServiceExt as _;
#[test]
fn timeout_env_resolution() {
assert_eq!(
request_timeout_from_raw(None),
Some(Duration::from_secs(60))
);
assert_eq!(
request_timeout_from_raw(Some("5")),
Some(Duration::from_secs(5))
);
assert_eq!(request_timeout_from_raw(Some("0")), None);
assert_eq!(
request_timeout_from_raw(Some("junk")),
Some(Duration::from_secs(60))
);
}
fn slow_app(timeout: Option<Duration>) -> Router {
let slow = || async {
tokio::time::sleep(Duration::from_millis(400)).await;
"done"
};
let app = Router::new()
.route("/slow", get(slow))
.route("/agent/chat", get(slow))
.route("/agent/chat/stream", get(slow))
.route("/operator/op/invoke", get(slow))
.route("/admin/packs/status", get(slow));
with_request_timeout(app, timeout)
}
async fn status(app: Router, path: &str) -> Result<StatusCode> {
let req = Request::builder().uri(path).body(Body::empty())?;
Ok(app.oneshot(req).await?.status())
}
#[tokio::test]
async fn slow_handler_times_out_with_408() -> Result<()> {
let app = slow_app(Some(Duration::from_millis(50)));
assert_eq!(status(app, "/slow").await?, StatusCode::REQUEST_TIMEOUT);
Ok(())
}
#[tokio::test]
async fn long_running_routes_are_exempt() -> Result<()> {
for path in ["/agent/chat", "/agent/chat/stream", "/operator/op/invoke"] {
let app = slow_app(Some(Duration::from_millis(50)));
assert_eq!(status(app, path).await?, StatusCode::OK, "{path}");
assert!(is_long_running_path(path));
}
Ok(())
}
#[tokio::test]
async fn admin_route_is_not_exempt() -> Result<()> {
let app = slow_app(Some(Duration::from_millis(50)));
assert_eq!(
status(app, "/admin/packs/status").await?,
StatusCode::REQUEST_TIMEOUT
);
assert!(!is_long_running_path("/admin/packs/status"));
assert!(!is_long_running_path("/healthz"));
Ok(())
}
#[tokio::test]
async fn disabled_timeout_lets_slow_handlers_finish() -> Result<()> {
assert_eq!(status(slow_app(None), "/slow").await?, StatusCode::OK);
Ok(())
}
}
#[cfg(all(test, feature = "agentic-worker"))]
mod router_tests {
use super::*;
use axum::body::Body;
use axum::extract::ConnectInfo;
use axum::http::{Request, StatusCode};
use tower::ServiceExt as _;
fn loopback() -> ConnectInfo<SocketAddr> {
ConnectInfo("127.0.0.1:8080".parse::<SocketAddr>().unwrap())
}
async fn operator_status(
admin: crate::http::auth::AdminAuth,
bearer: Option<&str>,
) -> StatusCode {
let mut state = ServerState::for_test();
state.admin = admin;
let mut req = Request::builder()
.method("POST")
.uri("/operator/op/invoke")
.extension(loopback());
if let Some(b) = bearer {
req = req.header("authorization", format!("Bearer {b}"));
}
router(state)
.oneshot(req.body(Body::empty()).unwrap())
.await
.unwrap()
.status()
}
#[tokio::test]
async fn operator_invoke_requires_token_when_configured() {
let admin =
crate::http::auth::AdminAuth::default().with_operator_token(Some("op-secret".into()));
assert_eq!(
operator_status(admin.clone(), None).await,
StatusCode::UNAUTHORIZED
);
assert_eq!(
operator_status(admin.clone(), Some("wrong")).await,
StatusCode::UNAUTHORIZED
);
assert_ne!(
operator_status(admin, Some("op-secret")).await,
StatusCode::UNAUTHORIZED
);
}
#[tokio::test]
async fn operator_invoke_open_without_token() {
assert_ne!(
operator_status(crate::http::auth::AdminAuth::default(), None).await,
StatusCode::UNAUTHORIZED
);
}
#[tokio::test]
async fn assembled_router_serves_admin_packs_status() {
let app = router(ServerState::for_test());
let response = app
.oneshot(
Request::builder()
.uri("/admin/packs/status")
.extension(loopback())
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
#[tokio::test]
async fn assembled_router_serves_admin_capabilities() {
let app = router(ServerState::for_test());
let response = app
.oneshot(
Request::builder()
.uri("/admin/capabilities")
.extension(loopback())
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let body = http_body_util::BodyExt::collect(response.into_body())
.await
.unwrap()
.to_bytes();
let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
assert_eq!(body, serde_json::json!({ "capabilities": [] }));
}
}