1use std::{collections::HashMap, future::Future, pin::Pin, sync::Arc};
5
6use axum::{
7 Json,
8 body::Bytes,
9 http::{Method, StatusCode},
10 response::{IntoResponse, Response},
11};
12use parking_lot::RwLock;
13use serde::{Deserialize, Serialize};
14use serde_json::{Value, json};
15
16pub type EngineRouteCallback =
18 Arc<dyn Fn(Value) -> Pin<Box<dyn Future<Output = anyhow::Result<Value>> + Send>> + Send + Sync>;
19
20#[derive(Serialize)]
21pub struct EngineHttpRequest {
22 pub method: String,
23 pub path: String,
25 pub body: Value,
26}
27
28#[derive(Deserialize)]
29pub struct EngineHttpResponse {
30 pub status: u16,
31 pub body: Value,
32}
33
34pub type EngineHttpCallback = Arc<
35 dyn Fn(
36 EngineHttpRequest,
37 ) -> Pin<Box<dyn Future<Output = anyhow::Result<EngineHttpResponse>> + Send>>
38 + Send
39 + Sync,
40>;
41
42#[derive(Clone)]
43enum Handler {
44 Legacy(EngineRouteCallback),
45 Http(EngineHttpCallback),
46}
47
48#[derive(Clone, Default)]
50pub struct EngineRouteRegistry {
51 routes: Arc<RwLock<HashMap<String, Handler>>>,
52}
53
54impl EngineRouteRegistry {
55 pub fn new() -> Self {
56 Self::default()
57 }
58
59 pub fn register(&self, route: &str, callback: EngineRouteCallback) {
60 if self
61 .routes
62 .write()
63 .insert(route.to_owned(), Handler::Legacy(callback))
64 .is_some()
65 {
66 tracing::warn!(route, "Overwriting already-registered engine route");
67 }
68 }
69
70 pub fn get(&self, route: &str) -> Option<EngineRouteCallback> {
71 match self.routes.read().get(route) {
72 Some(Handler::Legacy(callback)) => Some(Arc::clone(callback)),
73 _ => None,
74 }
75 }
76
77 pub fn routes(&self) -> Vec<String> {
78 self.routes.read().keys().cloned().collect()
79 }
80
81 pub fn register_http(&self, name: String, callback: EngineHttpCallback) -> anyhow::Result<()> {
83 anyhow::ensure!(
84 !name.is_empty()
85 && name
86 .bytes()
87 .all(|c| c.is_ascii_alphanumeric() || c == b'_' || c == b'-'),
88 "handler name must be a nonempty URL segment"
89 );
90 let mut routes = self.routes.write();
91 let prefix = format!("{name}/");
92 anyhow::ensure!(
93 !routes
94 .keys()
95 .any(|key| key == &name || key.starts_with(&prefix)),
96 "engine route namespace already registered"
97 );
98 routes.insert(name, Handler::Http(callback));
99 Ok(())
100 }
101
102 pub fn unregister_http(&self, name: &str) {
103 let mut routes = self.routes.write();
104 if matches!(routes.get(name), Some(Handler::Http(_))) {
105 routes.remove(name);
106 }
107 }
108
109 fn get_http(&self, path: &str) -> Option<(EngineHttpCallback, String)> {
110 let (name, suffix) = path.split_once('/').unwrap_or((path, ""));
111 match self.routes.read().get(name) {
112 Some(Handler::Http(callback)) => Some((Arc::clone(callback), suffix.to_owned())),
113 _ => None,
114 }
115 }
116}
117
118fn parse_json(body: &[u8], empty: Value) -> Result<Value, serde_json::Error> {
119 if body.is_empty() {
120 return Ok(empty);
121 }
122 serde_json::from_slice(body)
123}
124
125fn invalid_json(error: serde_json::Error) -> Response {
126 (
127 StatusCode::BAD_REQUEST,
128 Json(json!({"error":"Invalid JSON", "message":error.to_string()})),
129 )
130 .into_response()
131}
132
133pub(crate) async fn dispatch(
134 registry: &EngineRouteRegistry,
135 path: String,
136 method: Method,
137 body: Bytes,
138) -> Response {
139 if let Some(callback) = registry.get(&path) {
141 let payload = match parse_json(&body, json!({})) {
142 Ok(value) => value,
143 Err(error) => return invalid_json(error),
144 };
145 return match callback(payload).await {
146 Ok(response) => (StatusCode::OK, response.to_string()).into_response(),
147 Err(error) => {
148 tracing::error!(path, %error, "Engine route handler failed");
149 (
150 StatusCode::INTERNAL_SERVER_ERROR,
151 json!({"error":"Handler error", "message":error.to_string()}).to_string(),
152 )
153 .into_response()
154 }
155 };
156 }
157 let Some((callback, relative_path)) = registry.get_http(&path) else {
158 if let Err(error) = parse_json(&body, Value::Null) {
159 return invalid_json(error);
160 }
161 return (
162 StatusCode::NOT_FOUND,
163 json!({"error":"Route not found", "message":format!("Route /engine/{path} not found")})
164 .to_string(),
165 )
166 .into_response();
167 };
168 if body.len() > 64 * 1024 {
169 return StatusCode::PAYLOAD_TOO_LARGE.into_response();
170 }
171 let payload = match parse_json(&body, Value::Null) {
172 Ok(value) => value,
173 Err(error) => return invalid_json(error),
174 };
175 match callback(EngineHttpRequest {
176 method: method.to_string(),
177 path: relative_path,
178 body: payload,
179 })
180 .await
181 {
182 Ok(response) => match StatusCode::from_u16(response.status) {
183 Ok(status) if (200..600).contains(&response.status) => {
184 (status, Json(response.body)).into_response()
185 }
186 _ => {
187 tracing::error!(path, "Engine HTTP handler returned an invalid status");
188 StatusCode::INTERNAL_SERVER_ERROR.into_response()
189 }
190 },
191 Err(error) => {
192 tracing::error!(path, %error, "Engine HTTP handler failed");
193 StatusCode::INTERNAL_SERVER_ERROR.into_response()
194 }
195 }
196}
197
198#[cfg(test)]
199mod tests {
200 use super::*;
201 use axum::{
202 Router,
203 body::{Body, to_bytes},
204 extract::{Path, State},
205 http::Request,
206 routing::any,
207 };
208 use tower::ServiceExt;
209
210 fn router(registry: EngineRouteRegistry) -> Router {
211 Router::new()
212 .route(
213 "/engine/{*path}",
214 any(
215 |State(registry): State<EngineRouteRegistry>,
216 Path(path): Path<String>,
217 method: Method,
218 body: Bytes| async move {
219 dispatch(®istry, path, method, body).await
220 },
221 ),
222 )
223 .with_state(registry)
224 }
225
226 #[tokio::test]
227 async fn test_registry_basic() {
228 let registry = EngineRouteRegistry::new();
229
230 let callback: EngineRouteCallback =
232 Arc::new(|body| Box::pin(async move { Ok(serde_json::json!({"echo": body})) }));
233
234 registry.register("test", callback);
235
236 assert!(registry.get("test").is_some());
238 assert!(registry.get("nonexistent").is_none());
239
240 let routes = registry.routes();
242 assert_eq!(routes.len(), 1);
243 assert!(routes.contains(&"test".to_string()));
244 }
245
246 #[tokio::test]
247 async fn test_callback_execution() {
248 let registry = EngineRouteRegistry::new();
249
250 let callback: EngineRouteCallback = Arc::new(|body| {
251 Box::pin(async move {
252 let input = body.get("input").and_then(|v| v.as_str()).unwrap_or("");
253 Ok(serde_json::json!({
254 "output": format!("processed: {}", input)
255 }))
256 })
257 });
258
259 registry.register("process", callback);
260
261 let cb = registry.get("process").unwrap();
263 let result = cb(serde_json::json!({"input": "test"})).await.unwrap();
264
265 assert_eq!(result["output"], "processed: test");
266 }
267
268 #[tokio::test]
269 async fn test_clone_shares_routes() {
270 let registry = EngineRouteRegistry::new();
271
272 let callback: EngineRouteCallback =
273 Arc::new(|_| Box::pin(async { Ok(serde_json::json!({"ok": true})) }));
274 registry.register("test", callback);
275
276 let cloned = registry.clone();
278
279 assert!(registry.get("test").is_some());
281 assert!(cloned.get("test").is_some());
282
283 let callback2: EngineRouteCallback =
285 Arc::new(|_| Box::pin(async { Ok(serde_json::json!({"ok": false})) }));
286 cloned.register("test2", callback2);
287
288 assert!(registry.get("test2").is_some());
290 }
291 #[tokio::test]
292 async fn http_handlers_preserve_methods_status_and_registration_lifetime() {
293 let registry = EngineRouteRegistry::default();
294 registry
295 .register_http(
296 "planner".into(),
297 Arc::new(|request| {
298 Box::pin(async move {
299 assert_eq!(request.path, "config");
300 let status = match request.method.as_str() {
301 "GET" => 200,
302 "PATCH" if request.body["expected_revision"] == 3 => 202,
303 "PATCH" => 409,
304 _ => 405,
305 };
306 Ok(EngineHttpResponse {
307 status,
308 body: request.body,
309 })
310 })
311 }),
312 )
313 .unwrap();
314 let app = router(registry.clone());
315 for (method, path, body, expected) in [
316 ("GET", "/engine/planner/config", "", 200),
317 (
318 "PATCH",
319 "/engine/planner/config",
320 r#"{"expected_revision":3}"#,
321 202,
322 ),
323 ("PATCH", "/engine/planner/config", "{}", 409),
324 ("DELETE", "/engine/planner/config", "", 405),
325 ("GET", "/engine/missing/config", "", 404),
326 ("PATCH", "/engine/planner/config", "{", 400),
327 ] {
328 let response = app
329 .clone()
330 .oneshot(
331 Request::builder()
332 .method(method)
333 .uri(path)
334 .body(Body::from(body))
335 .unwrap(),
336 )
337 .await
338 .unwrap();
339 assert_eq!(response.status().as_u16(), expected);
340 if expected == 400 {
341 assert_eq!(response.headers()["content-type"], "application/json");
342 let body = to_bytes(response.into_body(), 1024).await.unwrap();
343 let error: Value = serde_json::from_slice(&body).unwrap();
344 assert_eq!(error["error"], "Invalid JSON");
345 assert!(error["message"].as_str().is_some());
346 }
347 }
348 let response = app
349 .clone()
350 .oneshot(
351 Request::builder()
352 .method("PATCH")
353 .uri("/engine/planner/config")
354 .body(Body::from("x".repeat(65537)))
355 .unwrap(),
356 )
357 .await
358 .unwrap();
359 assert_eq!(response.status(), StatusCode::PAYLOAD_TOO_LARGE);
360 registry.unregister_http("planner");
361 let response = app
362 .oneshot(
363 Request::builder()
364 .uri("/engine/planner/config")
365 .body(Body::empty())
366 .unwrap(),
367 )
368 .await
369 .unwrap();
370 assert_eq!(response.status(), StatusCode::NOT_FOUND);
371 }
372 #[tokio::test]
373 async fn legacy_payloads_are_not_interpreted_as_http_envelopes() {
374 let registry = EngineRouteRegistry::new();
375 registry.register("legacy", Arc::new(|body| Box::pin(async move { Ok(body) })));
376 let app = router(registry);
377 let payload = json!({"status":418, "body":{"value":7}});
378 let response = app
379 .oneshot(
380 Request::builder()
381 .method("POST")
382 .uri("/engine/legacy")
383 .body(Body::from(payload.to_string()))
384 .unwrap(),
385 )
386 .await
387 .unwrap();
388 assert_eq!(response.status(), StatusCode::OK);
389 let body = to_bytes(response.into_body(), 1024).await.unwrap();
390 assert_eq!(serde_json::from_slice::<Value>(&body).unwrap(), payload);
391 }
392}