1use base64::Engine;
17use bytes::Bytes;
18use futures_util::{SinkExt, StreamExt};
19use http::{Method, Request, Response, StatusCode, Uri};
20use http_body::Body;
21use http_body_util::{BodyExt, Full};
22use hyper::body::Incoming;
23use hyper::server::conn::http1;
24use hyper::upgrade::Upgraded;
25use hyper_util::rt::TokioIo;
26use hyper_util::service::TowerToHyperService;
27use ranvier_core::event::{EventSink, EventSource};
28use ranvier_core::prelude::*;
29use ranvier_runtime::Axon;
30use serde::Serialize;
31use serde::de::DeserializeOwned;
32use sha1::{Digest, Sha1};
33use std::collections::HashMap;
34use std::convert::Infallible;
35use std::future::Future;
36use std::net::SocketAddr;
37use std::pin::Pin;
38use std::sync::Arc;
39use std::time::Duration;
40use tokio::net::TcpListener;
41use tokio::sync::Mutex;
42use tokio_tungstenite::WebSocketStream;
43use tokio_tungstenite::tungstenite::{Error as WsWireError, Message as WsWireMessage};
44use tower::util::BoxCloneService;
45use tower::{Layer, Service, ServiceExt, service_fn};
46use tower_http::compression::CompressionLayer;
47use tower_http::services::{ServeDir, ServeFile};
48use tracing::Instrument;
49
50use crate::response::{HttpResponse, IntoResponse, outcome_to_response_with_error};
51
52pub struct Ranvier;
57
58impl Ranvier {
59 pub fn http<R>() -> HttpIngress<R>
61 where
62 R: ranvier_core::transition::ResourceRequirement + Clone,
63 {
64 HttpIngress::new()
65 }
66}
67
68type RouteHandler<R> = Arc<
70 dyn Fn(Request<Incoming>, &R) -> Pin<Box<dyn Future<Output = HttpResponse> + Send>>
71 + Send
72 + Sync,
73>;
74
75type BoxHttpService = BoxCloneService<Request<Incoming>, HttpResponse, Infallible>;
76type ServiceLayer = Arc<dyn Fn(BoxHttpService) -> BoxHttpService + Send + Sync>;
77type LifecycleHook = Arc<dyn Fn() + Send + Sync>;
78type BusInjector = Arc<dyn Fn(&Request<Incoming>, &mut Bus) + Send + Sync>;
79type WsSessionFuture = Pin<Box<dyn Future<Output = ()> + Send>>;
80type WsSessionHandler<R> =
81 Arc<dyn Fn(WebSocketConnection, Arc<R>, Bus) -> WsSessionFuture + Send + Sync>;
82type HealthCheckFuture = Pin<Box<dyn Future<Output = Result<(), String>> + Send>>;
83type HealthCheckFn<R> = Arc<dyn Fn(Arc<R>) -> HealthCheckFuture + Send + Sync>;
84const REQUEST_ID_HEADER: &str = "x-request-id";
85const WS_UPGRADE_TOKEN: &str = "websocket";
86const WS_GUID: &str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
87
88#[derive(Clone)]
89struct NamedHealthCheck<R> {
90 name: String,
91 check: HealthCheckFn<R>,
92}
93
94#[derive(Clone)]
95struct HealthConfig<R> {
96 health_path: Option<String>,
97 readiness_path: Option<String>,
98 liveness_path: Option<String>,
99 checks: Vec<NamedHealthCheck<R>>,
100}
101
102impl<R> Default for HealthConfig<R> {
103 fn default() -> Self {
104 Self {
105 health_path: None,
106 readiness_path: None,
107 liveness_path: None,
108 checks: Vec::new(),
109 }
110 }
111}
112
113#[derive(Clone, Default)]
114struct StaticAssetsConfig {
115 mounts: Vec<StaticMount>,
116 spa_fallback: Option<String>,
117 cache_control: Option<String>,
118 enable_compression: bool,
119}
120
121#[derive(Clone)]
122struct StaticMount {
123 route_prefix: String,
124 directory: String,
125}
126
127#[derive(Serialize)]
128struct HealthReport {
129 status: &'static str,
130 probe: &'static str,
131 checks: Vec<HealthCheckReport>,
132}
133
134#[derive(Serialize)]
135struct HealthCheckReport {
136 name: String,
137 status: &'static str,
138 #[serde(skip_serializing_if = "Option::is_none")]
139 error: Option<String>,
140}
141
142#[derive(Clone)]
143struct TimeoutService {
144 inner: BoxHttpService,
145 timeout: Duration,
146}
147
148impl Service<Request<Incoming>> for TimeoutService {
149 type Response = HttpResponse;
150 type Error = Infallible;
151 type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
152
153 fn poll_ready(
154 &mut self,
155 cx: &mut std::task::Context<'_>,
156 ) -> std::task::Poll<Result<(), Self::Error>> {
157 self.inner.poll_ready(cx)
158 }
159
160 fn call(&mut self, req: Request<Incoming>) -> Self::Future {
161 let timeout = self.timeout;
162 let fut = self.inner.call(req);
163 Box::pin(async move {
164 match tokio::time::timeout(timeout, fut).await {
165 Ok(response) => response,
166 Err(_) => Ok(Response::builder()
167 .status(StatusCode::REQUEST_TIMEOUT)
168 .body(Full::new(Bytes::from("Request Timeout")).map_err(|never| match never {}).boxed())
169 .unwrap()),
170 }
171 })
172 }
173}
174
175#[derive(Clone)]
176struct RequestIdService {
177 inner: BoxHttpService,
178}
179
180impl Service<Request<Incoming>> for RequestIdService {
181 type Response = HttpResponse;
182 type Error = Infallible;
183 type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
184
185 fn poll_ready(
186 &mut self,
187 cx: &mut std::task::Context<'_>,
188 ) -> std::task::Poll<Result<(), Self::Error>> {
189 self.inner.poll_ready(cx)
190 }
191
192 fn call(&mut self, req: Request<Incoming>) -> Self::Future {
193 let mut req = req;
194 let request_id = req
195 .headers()
196 .get(REQUEST_ID_HEADER)
197 .cloned()
198 .unwrap_or_else(|| {
199 http::HeaderValue::from_str(&uuid::Uuid::new_v4().to_string())
200 .unwrap_or_else(|_| http::HeaderValue::from_static("request-id-unavailable"))
201 });
202
203 req.headers_mut()
204 .insert(REQUEST_ID_HEADER, request_id.clone());
205
206 let fut = self.inner.call(req);
207 Box::pin(async move {
208 let mut response = fut.await?;
209 response.headers_mut().insert(REQUEST_ID_HEADER, request_id);
210 Ok(response)
211 })
212 }
213}
214
215fn to_service_layer<L>(layer: L) -> ServiceLayer
216where
217 L: Layer<BoxHttpService> + Clone + Send + Sync + 'static,
218 L::Service: Service<Request<Incoming>, Response = HttpResponse, Error = Infallible>
219 + Clone
220 + Send
221 + 'static,
222 <L::Service as Service<Request<Incoming>>>::Future: Send + 'static,
223{
224 Arc::new(move |service: BoxHttpService| BoxCloneService::new(layer.clone().layer(service)))
225}
226
227#[derive(Clone, Debug, Default, PartialEq, Eq)]
228pub struct PathParams {
229 values: HashMap<String, String>,
230}
231
232#[derive(Clone, Debug, PartialEq, Eq)]
234pub struct HttpRouteDescriptor {
235 method: Method,
236 path_pattern: String,
237}
238
239impl HttpRouteDescriptor {
240 pub fn new(method: Method, path_pattern: impl Into<String>) -> Self {
241 Self {
242 method,
243 path_pattern: path_pattern.into(),
244 }
245 }
246
247 pub fn method(&self) -> &Method {
248 &self.method
249 }
250
251 pub fn path_pattern(&self) -> &str {
252 &self.path_pattern
253 }
254}
255
256#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
258pub struct WebSocketSessionContext {
259 connection_id: uuid::Uuid,
260 path: String,
261 query: Option<String>,
262}
263
264impl WebSocketSessionContext {
265 pub fn connection_id(&self) -> uuid::Uuid {
266 self.connection_id
267 }
268
269 pub fn path(&self) -> &str {
270 &self.path
271 }
272
273 pub fn query(&self) -> Option<&str> {
274 self.query.as_deref()
275 }
276}
277
278#[derive(Clone, Debug, PartialEq, Eq)]
280pub enum WebSocketEvent {
281 Text(String),
282 Binary(Vec<u8>),
283 Ping(Vec<u8>),
284 Pong(Vec<u8>),
285 Close,
286}
287
288impl WebSocketEvent {
289 pub fn text(value: impl Into<String>) -> Self {
290 Self::Text(value.into())
291 }
292
293 pub fn binary(value: impl Into<Vec<u8>>) -> Self {
294 Self::Binary(value.into())
295 }
296
297 pub fn json<T>(value: &T) -> Result<Self, serde_json::Error>
298 where
299 T: Serialize,
300 {
301 let text = serde_json::to_string(value)?;
302 Ok(Self::Text(text))
303 }
304}
305
306#[derive(Debug, thiserror::Error)]
307pub enum WebSocketError {
308 #[error("websocket wire error: {0}")]
309 Wire(#[from] WsWireError),
310 #[error("json serialization failed: {0}")]
311 JsonSerialize(#[source] serde_json::Error),
312 #[error("json deserialization failed: {0}")]
313 JsonDeserialize(#[source] serde_json::Error),
314 #[error("expected text or binary frame for json payload")]
315 NonDataFrame,
316}
317
318type WsServerStream = WebSocketStream<TokioIo<Upgraded>>;
319type WsServerSink = futures_util::stream::SplitSink<WsServerStream, WsWireMessage>;
320type WsServerSource = futures_util::stream::SplitStream<WsServerStream>;
321
322pub struct WebSocketConnection {
324 sink: Mutex<WsServerSink>,
325 source: Mutex<WsServerSource>,
326 session: WebSocketSessionContext,
327}
328
329impl WebSocketConnection {
330 fn new(stream: WsServerStream, session: WebSocketSessionContext) -> Self {
331 let (sink, source) = stream.split();
332 Self {
333 sink: Mutex::new(sink),
334 source: Mutex::new(source),
335 session,
336 }
337 }
338
339 pub fn session(&self) -> &WebSocketSessionContext {
340 &self.session
341 }
342
343 pub async fn send(&self, event: WebSocketEvent) -> Result<(), WebSocketError> {
344 let mut sink = self.sink.lock().await;
345 sink.send(event.into_wire_message()).await?;
346 Ok(())
347 }
348
349 pub async fn send_json<T>(&self, value: &T) -> Result<(), WebSocketError>
350 where
351 T: Serialize,
352 {
353 let event = WebSocketEvent::json(value).map_err(WebSocketError::JsonSerialize)?;
354 self.send(event).await
355 }
356
357 pub async fn next_json<T>(&mut self) -> Result<Option<T>, WebSocketError>
358 where
359 T: DeserializeOwned,
360 {
361 let Some(event) = self.recv_event().await? else {
362 return Ok(None);
363 };
364 match event {
365 WebSocketEvent::Text(text) => serde_json::from_str(&text)
366 .map(Some)
367 .map_err(WebSocketError::JsonDeserialize),
368 WebSocketEvent::Binary(bytes) => serde_json::from_slice(&bytes)
369 .map(Some)
370 .map_err(WebSocketError::JsonDeserialize),
371 _ => Err(WebSocketError::NonDataFrame),
372 }
373 }
374
375 async fn recv_event(&mut self) -> Result<Option<WebSocketEvent>, WsWireError> {
376 let mut source = self.source.lock().await;
377 while let Some(item) = source.next().await {
378 let message = item?;
379 if let Some(event) = WebSocketEvent::from_wire_message(message) {
380 return Ok(Some(event));
381 }
382 }
383 Ok(None)
384 }
385}
386
387impl WebSocketEvent {
388 fn from_wire_message(message: WsWireMessage) -> Option<Self> {
389 match message {
390 WsWireMessage::Text(value) => Some(Self::Text(value.to_string())),
391 WsWireMessage::Binary(value) => Some(Self::Binary(value.to_vec())),
392 WsWireMessage::Ping(value) => Some(Self::Ping(value.to_vec())),
393 WsWireMessage::Pong(value) => Some(Self::Pong(value.to_vec())),
394 WsWireMessage::Close(_) => Some(Self::Close),
395 WsWireMessage::Frame(_) => None,
396 }
397 }
398
399 fn into_wire_message(self) -> WsWireMessage {
400 match self {
401 Self::Text(value) => WsWireMessage::Text(value.into()),
402 Self::Binary(value) => WsWireMessage::Binary(value.into()),
403 Self::Ping(value) => WsWireMessage::Ping(value.into()),
404 Self::Pong(value) => WsWireMessage::Pong(value.into()),
405 Self::Close => WsWireMessage::Close(None),
406 }
407 }
408}
409
410#[async_trait::async_trait]
411impl EventSource<WebSocketEvent> for WebSocketConnection {
412 async fn next_event(&mut self) -> Option<WebSocketEvent> {
413 match self.recv_event().await {
414 Ok(event) => event,
415 Err(error) => {
416 tracing::warn!(ranvier.ws.error = %error, "websocket source read failed");
417 None
418 }
419 }
420 }
421}
422
423#[async_trait::async_trait]
424impl EventSink<WebSocketEvent> for WebSocketConnection {
425 type Error = WebSocketError;
426
427 async fn send_event(&self, event: WebSocketEvent) -> Result<(), Self::Error> {
428 self.send(event).await
429 }
430}
431
432#[async_trait::async_trait]
433impl EventSink<String> for WebSocketConnection {
434 type Error = WebSocketError;
435
436 async fn send_event(&self, event: String) -> Result<(), Self::Error> {
437 self.send(WebSocketEvent::Text(event)).await
438 }
439}
440
441#[async_trait::async_trait]
442impl EventSink<Vec<u8>> for WebSocketConnection {
443 type Error = WebSocketError;
444
445 async fn send_event(&self, event: Vec<u8>) -> Result<(), Self::Error> {
446 self.send(WebSocketEvent::Binary(event)).await
447 }
448}
449
450impl PathParams {
451 pub fn new(values: HashMap<String, String>) -> Self {
452 Self { values }
453 }
454
455 pub fn get(&self, key: &str) -> Option<&str> {
456 self.values.get(key).map(String::as_str)
457 }
458
459 pub fn as_map(&self) -> &HashMap<String, String> {
460 &self.values
461 }
462
463 pub fn into_inner(self) -> HashMap<String, String> {
464 self.values
465 }
466}
467
468#[derive(Clone, Debug, PartialEq, Eq)]
469enum RouteSegment {
470 Static(String),
471 Param(String),
472 Wildcard(String),
473}
474
475#[derive(Clone, Debug, PartialEq, Eq)]
476struct RoutePattern {
477 raw: String,
478 segments: Vec<RouteSegment>,
479}
480
481impl RoutePattern {
482 fn parse(path: &str) -> Self {
483 let segments = path_segments(path)
484 .into_iter()
485 .map(|segment| {
486 if let Some(name) = segment.strip_prefix(':') {
487 if !name.is_empty() {
488 return RouteSegment::Param(name.to_string());
489 }
490 }
491 if let Some(name) = segment.strip_prefix('*') {
492 if !name.is_empty() {
493 return RouteSegment::Wildcard(name.to_string());
494 }
495 }
496 RouteSegment::Static(segment.to_string())
497 })
498 .collect();
499
500 Self {
501 raw: path.to_string(),
502 segments,
503 }
504 }
505
506 fn match_path(&self, path: &str) -> Option<PathParams> {
507 let mut params = HashMap::new();
508 let path_segments = path_segments(path);
509 let mut pattern_index = 0usize;
510 let mut path_index = 0usize;
511
512 while pattern_index < self.segments.len() {
513 match &self.segments[pattern_index] {
514 RouteSegment::Static(expected) => {
515 let actual = path_segments.get(path_index)?;
516 if actual != expected {
517 return None;
518 }
519 pattern_index += 1;
520 path_index += 1;
521 }
522 RouteSegment::Param(name) => {
523 let actual = path_segments.get(path_index)?;
524 params.insert(name.clone(), (*actual).to_string());
525 pattern_index += 1;
526 path_index += 1;
527 }
528 RouteSegment::Wildcard(name) => {
529 let remaining = path_segments[path_index..].join("/");
530 params.insert(name.clone(), remaining);
531 pattern_index += 1;
532 path_index = path_segments.len();
533 break;
534 }
535 }
536 }
537
538 if pattern_index == self.segments.len() && path_index == path_segments.len() {
539 Some(PathParams::new(params))
540 } else {
541 None
542 }
543 }
544}
545
546#[derive(Clone)]
547struct RouteEntry<R> {
548 method: Method,
549 pattern: RoutePattern,
550 handler: RouteHandler<R>,
551 layers: Arc<Vec<ServiceLayer>>,
552 apply_global_layers: bool,
553}
554
555fn path_segments(path: &str) -> Vec<&str> {
556 if path == "/" {
557 return Vec::new();
558 }
559
560 path.trim_matches('/')
561 .split('/')
562 .filter(|segment| !segment.is_empty())
563 .collect()
564}
565
566fn normalize_route_path(path: String) -> String {
567 if path.is_empty() {
568 return "/".to_string();
569 }
570 if path.starts_with('/') {
571 path
572 } else {
573 format!("/{path}")
574 }
575}
576
577fn find_matching_route<'a, R>(
578 routes: &'a [RouteEntry<R>],
579 method: &Method,
580 path: &str,
581) -> Option<(&'a RouteEntry<R>, PathParams)> {
582 for entry in routes {
583 if &entry.method != method {
584 continue;
585 }
586 if let Some(params) = entry.pattern.match_path(path) {
587 return Some((entry, params));
588 }
589 }
590 None
591}
592
593fn header_contains_token(
594 headers: &http::HeaderMap,
595 name: http::header::HeaderName,
596 token: &str,
597) -> bool {
598 headers
599 .get(name)
600 .and_then(|value| value.to_str().ok())
601 .map(|value| {
602 value
603 .split(',')
604 .any(|part| part.trim().eq_ignore_ascii_case(token))
605 })
606 .unwrap_or(false)
607}
608
609fn websocket_session_from_request(req: &Request<Incoming>) -> WebSocketSessionContext {
610 WebSocketSessionContext {
611 connection_id: uuid::Uuid::new_v4(),
612 path: req.uri().path().to_string(),
613 query: req.uri().query().map(str::to_string),
614 }
615}
616
617fn websocket_accept_key(client_key: &str) -> String {
618 let mut hasher = Sha1::new();
619 hasher.update(client_key.as_bytes());
620 hasher.update(WS_GUID.as_bytes());
621 let digest = hasher.finalize();
622 base64::engine::general_purpose::STANDARD.encode(digest)
623}
624
625fn websocket_bad_request(message: &'static str) -> HttpResponse {
626 Response::builder()
627 .status(StatusCode::BAD_REQUEST)
628 .body(Full::new(Bytes::from(message)).map_err(|never| match never {}).boxed())
629 .unwrap_or_else(|_| Response::new(Full::new(Bytes::new()).map_err(|never| match never {}).boxed()))
630}
631
632fn websocket_upgrade_response(
633 req: &mut Request<Incoming>,
634) -> Result<(HttpResponse, hyper::upgrade::OnUpgrade), HttpResponse> {
635 if req.method() != Method::GET {
636 return Err(websocket_bad_request(
637 "WebSocket upgrade requires GET method",
638 ));
639 }
640
641 if !header_contains_token(req.headers(), http::header::CONNECTION, "upgrade") {
642 return Err(websocket_bad_request(
643 "Missing Connection: upgrade header for WebSocket",
644 ));
645 }
646
647 if !header_contains_token(req.headers(), http::header::UPGRADE, WS_UPGRADE_TOKEN) {
648 return Err(websocket_bad_request("Missing Upgrade: websocket header"));
649 }
650
651 if let Some(version) = req.headers().get("sec-websocket-version") {
652 if version != "13" {
653 return Err(websocket_bad_request(
654 "Unsupported Sec-WebSocket-Version (expected 13)",
655 ));
656 }
657 }
658
659 let Some(client_key) = req
660 .headers()
661 .get("sec-websocket-key")
662 .and_then(|value| value.to_str().ok())
663 else {
664 return Err(websocket_bad_request(
665 "Missing Sec-WebSocket-Key header for WebSocket",
666 ));
667 };
668
669 let accept_key = websocket_accept_key(client_key);
670 let on_upgrade = hyper::upgrade::on(req);
671 let response = Response::builder()
672 .status(StatusCode::SWITCHING_PROTOCOLS)
673 .header(http::header::UPGRADE, WS_UPGRADE_TOKEN)
674 .header(http::header::CONNECTION, "Upgrade")
675 .header("sec-websocket-accept", accept_key)
676 .body(Full::new(Bytes::new()).map_err(|never| match never {}).boxed())
677 .unwrap_or_else(|_| Response::new(Full::new(Bytes::new()).map_err(|never| match never {}).boxed()));
678
679 Ok((response, on_upgrade))
680}
681
682pub struct HttpIngress<R = ()> {
688 addr: Option<String>,
690 routes: Vec<RouteEntry<R>>,
692 fallback: Option<RouteHandler<R>>,
694 layers: Vec<ServiceLayer>,
696 on_start: Option<LifecycleHook>,
698 on_shutdown: Option<LifecycleHook>,
700 graceful_shutdown_timeout: Duration,
702 bus_injectors: Vec<BusInjector>,
704 static_assets: StaticAssetsConfig,
706 health: HealthConfig<R>,
708 _phantom: std::marker::PhantomData<R>,
709}
710
711impl<R> HttpIngress<R>
712where
713 R: ranvier_core::transition::ResourceRequirement + Clone + Send + Sync + 'static,
714{
715 pub fn new() -> Self {
717 Self {
718 addr: None,
719 routes: Vec::new(),
720 fallback: None,
721 layers: Vec::new(),
722 on_start: None,
723 on_shutdown: None,
724 graceful_shutdown_timeout: Duration::from_secs(30),
725 bus_injectors: Vec::new(),
726 static_assets: StaticAssetsConfig::default(),
727 health: HealthConfig::default(),
728 _phantom: std::marker::PhantomData,
729 }
730 }
731
732 pub fn bind(mut self, addr: impl Into<String>) -> Self {
734 self.addr = Some(addr.into());
735 self
736 }
737
738 pub fn on_start<F>(mut self, callback: F) -> Self
740 where
741 F: Fn() + Send + Sync + 'static,
742 {
743 self.on_start = Some(Arc::new(callback));
744 self
745 }
746
747 pub fn on_shutdown<F>(mut self, callback: F) -> Self
749 where
750 F: Fn() + Send + Sync + 'static,
751 {
752 self.on_shutdown = Some(Arc::new(callback));
753 self
754 }
755
756 pub fn graceful_shutdown(mut self, timeout: Duration) -> Self {
758 self.graceful_shutdown_timeout = timeout;
759 self
760 }
761
762 pub fn layer<L>(mut self, layer: L) -> Self
767 where
768 L: Layer<BoxHttpService> + Clone + Send + Sync + 'static,
769 L::Service: Service<Request<Incoming>, Response = HttpResponse, Error = Infallible>
770 + Clone
771 + Send
772 + 'static,
773 <L::Service as Service<Request<Incoming>>>::Future: Send + 'static,
774 {
775 self.layers.push(to_service_layer(layer));
776 self
777 }
778
779 pub fn timeout_layer(mut self, timeout: Duration) -> Self {
782 self.layers.push(Arc::new(move |service: BoxHttpService| {
783 BoxCloneService::new(TimeoutService {
784 inner: service,
785 timeout,
786 })
787 }));
788 self
789 }
790
791 pub fn request_id_layer(mut self) -> Self {
795 self.layers.push(Arc::new(move |service: BoxHttpService| {
796 BoxCloneService::new(RequestIdService { inner: service })
797 }));
798 self
799 }
800
801 pub fn bus_injector<F>(mut self, injector: F) -> Self
806 where
807 F: Fn(&Request<Incoming>, &mut Bus) + Send + Sync + 'static,
808 {
809 self.bus_injectors.push(Arc::new(injector));
810 self
811 }
812
813 pub fn route_descriptors(&self) -> Vec<HttpRouteDescriptor> {
815 let mut descriptors = self
816 .routes
817 .iter()
818 .map(|entry| HttpRouteDescriptor::new(entry.method.clone(), entry.pattern.raw.clone()))
819 .collect::<Vec<_>>();
820
821 if let Some(path) = &self.health.health_path {
822 descriptors.push(HttpRouteDescriptor::new(Method::GET, path.clone()));
823 }
824 if let Some(path) = &self.health.readiness_path {
825 descriptors.push(HttpRouteDescriptor::new(Method::GET, path.clone()));
826 }
827 if let Some(path) = &self.health.liveness_path {
828 descriptors.push(HttpRouteDescriptor::new(Method::GET, path.clone()));
829 }
830
831 descriptors
832 }
833
834 pub fn serve_dir(
838 mut self,
839 route_prefix: impl Into<String>,
840 directory: impl Into<String>,
841 ) -> Self {
842 self.static_assets.mounts.push(StaticMount {
843 route_prefix: normalize_route_path(route_prefix.into()),
844 directory: directory.into(),
845 });
846 if self.static_assets.cache_control.is_none() {
847 self.static_assets.cache_control = Some("public, max-age=3600".to_string());
848 }
849 self
850 }
851
852 pub fn spa_fallback(mut self, file_path: impl Into<String>) -> Self {
856 self.static_assets.spa_fallback = Some(file_path.into());
857 self
858 }
859
860 pub fn static_cache_control(mut self, cache_control: impl Into<String>) -> Self {
862 self.static_assets.cache_control = Some(cache_control.into());
863 self
864 }
865
866 pub fn compression_layer(mut self) -> Self {
868 self.static_assets.enable_compression = true;
869 self
870 }
871
872 pub fn ws<H, Fut>(mut self, path: impl Into<String>, handler: H) -> Self
879 where
880 H: Fn(WebSocketConnection, Arc<R>, Bus) -> Fut + Send + Sync + 'static,
881 Fut: Future<Output = ()> + Send + 'static,
882 {
883 let path_str: String = path.into();
884 let ws_handler: WsSessionHandler<R> = Arc::new(move |connection, resources, bus| {
885 Box::pin(handler(connection, resources, bus))
886 });
887 let bus_injectors = Arc::new(self.bus_injectors.clone());
888 let path_for_pattern = path_str.clone();
889 let path_for_handler = path_str;
890
891 let route_handler: RouteHandler<R> =
892 Arc::new(move |mut req: Request<Incoming>, res: &R| {
893 let ws_handler = ws_handler.clone();
894 let bus_injectors = bus_injectors.clone();
895 let resources = Arc::new(res.clone());
896 let path = path_for_handler.clone();
897
898 Box::pin(async move {
899 let request_id = uuid::Uuid::new_v4().to_string();
900 let span = tracing::info_span!(
901 "WebSocketUpgrade",
902 ranvier.ws.path = %path,
903 ranvier.ws.request_id = %request_id
904 );
905
906 async move {
907 let mut bus = Bus::new();
908 for injector in bus_injectors.iter() {
909 injector(&req, &mut bus);
910 }
911
912 let session = websocket_session_from_request(&req);
913 bus.insert(session.clone());
914
915 let (response, on_upgrade) = match websocket_upgrade_response(&mut req) {
916 Ok(result) => result,
917 Err(error_response) => return error_response,
918 };
919
920 tokio::spawn(async move {
921 match on_upgrade.await {
922 Ok(upgraded) => {
923 let stream = WebSocketStream::from_raw_socket(
924 TokioIo::new(upgraded),
925 tokio_tungstenite::tungstenite::protocol::Role::Server,
926 None,
927 )
928 .await;
929 let connection = WebSocketConnection::new(stream, session);
930 ws_handler(connection, resources, bus).await;
931 }
932 Err(error) => {
933 tracing::warn!(
934 ranvier.ws.path = %path,
935 ranvier.ws.error = %error,
936 "websocket upgrade failed"
937 );
938 }
939 }
940 });
941
942 response
943 }
944 .instrument(span)
945 .await
946 }) as Pin<Box<dyn Future<Output = HttpResponse> + Send>>
947 });
948
949 self.routes.push(RouteEntry {
950 method: Method::GET,
951 pattern: RoutePattern::parse(&path_for_pattern),
952 handler: route_handler,
953 layers: Arc::new(Vec::new()),
954 apply_global_layers: true,
955 });
956
957 self
958 }
959
960 pub fn health_endpoint(mut self, path: impl Into<String>) -> Self {
965 self.health.health_path = Some(normalize_route_path(path.into()));
966 self
967 }
968
969 pub fn health_check<F, Fut, Err>(mut self, name: impl Into<String>, check: F) -> Self
973 where
974 F: Fn(Arc<R>) -> Fut + Send + Sync + 'static,
975 Fut: Future<Output = Result<(), Err>> + Send + 'static,
976 Err: ToString + Send + 'static,
977 {
978 if self.health.health_path.is_none() {
979 self.health.health_path = Some("/health".to_string());
980 }
981
982 let check_fn: HealthCheckFn<R> = Arc::new(move |resources: Arc<R>| {
983 let fut = check(resources);
984 Box::pin(async move { fut.await.map_err(|error| error.to_string()) })
985 });
986
987 self.health.checks.push(NamedHealthCheck {
988 name: name.into(),
989 check: check_fn,
990 });
991 self
992 }
993
994 pub fn readiness_liveness(
996 mut self,
997 readiness_path: impl Into<String>,
998 liveness_path: impl Into<String>,
999 ) -> Self {
1000 self.health.readiness_path = Some(normalize_route_path(readiness_path.into()));
1001 self.health.liveness_path = Some(normalize_route_path(liveness_path.into()));
1002 self
1003 }
1004
1005 pub fn readiness_liveness_default(self) -> Self {
1007 self.readiness_liveness("/ready", "/live")
1008 }
1009
1010 pub fn route<Out, E>(self, path: impl Into<String>, circuit: Axon<(), Out, E, R>) -> Self
1012 where
1013 Out: IntoResponse + Send + Sync + 'static,
1014 E: Send + 'static + std::fmt::Debug,
1015 {
1016 self.route_method(Method::GET, path, circuit)
1017 }
1018 pub fn route_method<Out, E>(
1027 self,
1028 method: Method,
1029 path: impl Into<String>,
1030 circuit: Axon<(), Out, E, R>,
1031 ) -> Self
1032 where
1033 Out: IntoResponse + Send + Sync + 'static,
1034 E: Send + 'static + std::fmt::Debug,
1035 {
1036 self.route_method_with_error(method, path, circuit, |error| {
1037 (
1038 StatusCode::INTERNAL_SERVER_ERROR,
1039 format!("Error: {:?}", error),
1040 ).into_response()
1041 })
1042 }
1043
1044 pub fn route_method_with_error<Out, E, H>(
1045 self,
1046 method: Method,
1047 path: impl Into<String>,
1048 circuit: Axon<(), Out, E, R>,
1049 error_handler: H,
1050 ) -> Self
1051 where
1052 Out: IntoResponse + Send + Sync + 'static,
1053 E: Send + 'static + std::fmt::Debug,
1054 H: Fn(&E) -> HttpResponse + Send + Sync + 'static,
1055 {
1056 self.route_method_with_error_and_layers(
1057 method,
1058 path,
1059 circuit,
1060 error_handler,
1061 Arc::new(Vec::new()),
1062 true,
1063 )
1064 }
1065
1066 pub fn route_method_with_layer<Out, E, L>(
1067 self,
1068 method: Method,
1069 path: impl Into<String>,
1070 circuit: Axon<(), Out, E, R>,
1071 layer: L,
1072 ) -> Self
1073 where
1074 Out: IntoResponse + Send + Sync + 'static,
1075 E: Send + 'static + std::fmt::Debug,
1076 L: Layer<BoxHttpService> + Clone + Send + Sync + 'static,
1077 L::Service: Service<Request<Incoming>, Response = HttpResponse, Error = Infallible>
1078 + Clone
1079 + Send
1080 + 'static,
1081 <L::Service as Service<Request<Incoming>>>::Future: Send + 'static,
1082 {
1083 self.route_method_with_error_and_layers(
1084 method,
1085 path,
1086 circuit,
1087 |error| {
1088 (
1089 StatusCode::INTERNAL_SERVER_ERROR,
1090 format!("Error: {:?}", error),
1091 ).into_response()
1092 },
1093 Arc::new(vec![to_service_layer(layer)]),
1094 true,
1095 )
1096 }
1097
1098 pub fn route_method_with_layer_override<Out, E, L>(
1099 self,
1100 method: Method,
1101 path: impl Into<String>,
1102 circuit: Axon<(), Out, E, R>,
1103 layer: L,
1104 ) -> Self
1105 where
1106 Out: IntoResponse + Send + Sync + 'static,
1107 E: Send + 'static + std::fmt::Debug,
1108 L: Layer<BoxHttpService> + Clone + Send + Sync + 'static,
1109 L::Service: Service<Request<Incoming>, Response = HttpResponse, Error = Infallible>
1110 + Clone
1111 + Send
1112 + 'static,
1113 <L::Service as Service<Request<Incoming>>>::Future: Send + 'static,
1114 {
1115 self.route_method_with_error_and_layers(
1116 method,
1117 path,
1118 circuit,
1119 |error| {
1120 (
1121 StatusCode::INTERNAL_SERVER_ERROR,
1122 format!("Error: {:?}", error),
1123 ).into_response()
1124 },
1125 Arc::new(vec![to_service_layer(layer)]),
1126 false,
1127 )
1128 }
1129
1130 fn route_method_with_error_and_layers<Out, E, H>(
1131 mut self,
1132 method: Method,
1133 path: impl Into<String>,
1134 circuit: Axon<(), Out, E, R>,
1135 error_handler: H,
1136 route_layers: Arc<Vec<ServiceLayer>>,
1137 apply_global_layers: bool,
1138 ) -> Self
1139 where
1140 Out: IntoResponse + Send + Sync + 'static,
1141 E: Send + 'static + std::fmt::Debug,
1142 H: Fn(&E) -> HttpResponse + Send + Sync + 'static,
1143 {
1144 let path_str: String = path.into();
1145 let circuit = Arc::new(circuit);
1146 let error_handler = Arc::new(error_handler);
1147 let route_bus_injectors = Arc::new(self.bus_injectors.clone());
1148 let path_for_pattern = path_str.clone();
1149 let path_for_handler = path_str;
1150 let method_for_pattern = method.clone();
1151 let method_for_handler = method;
1152
1153 let handler: RouteHandler<R> = Arc::new(move |req: Request<Incoming>, res: &R| {
1154 let circuit = circuit.clone();
1155 let error_handler = error_handler.clone();
1156 let route_bus_injectors = route_bus_injectors.clone();
1157 let res = res.clone();
1158 let path = path_for_handler.clone();
1159 let method = method_for_handler.clone();
1160
1161 Box::pin(async move {
1162 let request_id = uuid::Uuid::new_v4().to_string();
1163 let span = tracing::info_span!(
1164 "HTTPRequest",
1165 ranvier.http.method = %method,
1166 ranvier.http.path = %path,
1167 ranvier.http.request_id = %request_id
1168 );
1169
1170 async move {
1171 let mut bus = Bus::new();
1172 for injector in route_bus_injectors.iter() {
1173 injector(&req, &mut bus);
1174 }
1175 let result = circuit.execute((), &res, &mut bus).await;
1176 outcome_to_response_with_error(result, |error| error_handler(error))
1177 }
1178 .instrument(span)
1179 .await
1180 }) as Pin<Box<dyn Future<Output = HttpResponse> + Send>>
1181 });
1182
1183 self.routes.push(RouteEntry {
1184 method: method_for_pattern,
1185 pattern: RoutePattern::parse(&path_for_pattern),
1186 handler,
1187 layers: route_layers,
1188 apply_global_layers,
1189 });
1190 self
1191 }
1192
1193 pub fn get<Out, E>(self, path: impl Into<String>, circuit: Axon<(), Out, E, R>) -> Self
1194 where
1195 Out: IntoResponse + Send + Sync + 'static,
1196 E: Send + 'static + std::fmt::Debug,
1197 {
1198 self.route_method(Method::GET, path, circuit)
1199 }
1200
1201 pub fn get_with_error<Out, E, H>(
1202 self,
1203 path: impl Into<String>,
1204 circuit: Axon<(), Out, E, R>,
1205 error_handler: H,
1206 ) -> Self
1207 where
1208 Out: IntoResponse + Send + Sync + 'static,
1209 E: Send + 'static + std::fmt::Debug,
1210 H: Fn(&E) -> HttpResponse + Send + Sync + 'static,
1211 {
1212 self.route_method_with_error(Method::GET, path, circuit, error_handler)
1213 }
1214
1215 pub fn get_with_layer<Out, E, L>(
1216 self,
1217 path: impl Into<String>,
1218 circuit: Axon<(), Out, E, R>,
1219 layer: L,
1220 ) -> Self
1221 where
1222 Out: IntoResponse + Send + Sync + 'static,
1223 E: Send + 'static + std::fmt::Debug,
1224 L: Layer<BoxHttpService> + Clone + Send + Sync + 'static,
1225 L::Service: Service<Request<Incoming>, Response = HttpResponse, Error = Infallible>
1226 + Clone
1227 + Send
1228 + 'static,
1229 <L::Service as Service<Request<Incoming>>>::Future: Send + 'static,
1230 {
1231 self.route_method_with_layer(Method::GET, path, circuit, layer)
1232 }
1233
1234 pub fn get_with_layer_override<Out, E, L>(
1235 self,
1236 path: impl Into<String>,
1237 circuit: Axon<(), Out, E, R>,
1238 layer: L,
1239 ) -> Self
1240 where
1241 Out: IntoResponse + Send + Sync + 'static,
1242 E: Send + 'static + std::fmt::Debug,
1243 L: Layer<BoxHttpService> + Clone + Send + Sync + 'static,
1244 L::Service: Service<Request<Incoming>, Response = HttpResponse, Error = Infallible>
1245 + Clone
1246 + Send
1247 + 'static,
1248 <L::Service as Service<Request<Incoming>>>::Future: Send + 'static,
1249 {
1250 self.route_method_with_layer_override(Method::GET, path, circuit, layer)
1251 }
1252
1253 pub fn post<Out, E>(self, path: impl Into<String>, circuit: Axon<(), Out, E, R>) -> Self
1254 where
1255 Out: IntoResponse + Send + Sync + 'static,
1256 E: Send + 'static + std::fmt::Debug,
1257 {
1258 self.route_method(Method::POST, path, circuit)
1259 }
1260
1261 pub fn put<Out, E>(self, path: impl Into<String>, circuit: Axon<(), Out, E, R>) -> Self
1262 where
1263 Out: IntoResponse + Send + Sync + 'static,
1264 E: Send + 'static + std::fmt::Debug,
1265 {
1266 self.route_method(Method::PUT, path, circuit)
1267 }
1268
1269 pub fn delete<Out, E>(self, path: impl Into<String>, circuit: Axon<(), Out, E, R>) -> Self
1270 where
1271 Out: IntoResponse + Send + Sync + 'static,
1272 E: Send + 'static + std::fmt::Debug,
1273 {
1274 self.route_method(Method::DELETE, path, circuit)
1275 }
1276
1277 pub fn patch<Out, E>(self, path: impl Into<String>, circuit: Axon<(), Out, E, R>) -> Self
1278 where
1279 Out: IntoResponse + Send + Sync + 'static,
1280 E: Send + 'static + std::fmt::Debug,
1281 {
1282 self.route_method(Method::PATCH, path, circuit)
1283 }
1284
1285 pub fn fallback<Out, E>(mut self, circuit: Axon<(), Out, E, R>) -> Self
1296 where
1297 Out: IntoResponse + Send + Sync + 'static,
1298 E: Send + 'static + std::fmt::Debug,
1299 {
1300 let circuit = Arc::new(circuit);
1301 let fallback_bus_injectors = Arc::new(self.bus_injectors.clone());
1302
1303 let handler: RouteHandler<R> = Arc::new(move |req: Request<Incoming>, res: &R| {
1304 let circuit = circuit.clone();
1305 let fallback_bus_injectors = fallback_bus_injectors.clone();
1306 let res = res.clone();
1307 Box::pin(async move {
1308 let request_id = uuid::Uuid::new_v4().to_string();
1309 let span = tracing::info_span!(
1310 "HTTPRequest",
1311 ranvier.http.method = "FALLBACK",
1312 ranvier.http.request_id = %request_id
1313 );
1314
1315 async move {
1316 let mut bus = Bus::new();
1317 for injector in fallback_bus_injectors.iter() {
1318 injector(&req, &mut bus);
1319 }
1320 let result = circuit.execute((), &res, &mut bus).await;
1321
1322 match result {
1323 Outcome::Next(output) => {
1324 let mut response = output.into_response();
1325 *response.status_mut() = StatusCode::NOT_FOUND;
1326 response
1327 }
1328 _ => Response::builder()
1329 .status(StatusCode::NOT_FOUND)
1330 .body(Full::new(Bytes::from("Not Found")).map_err(|never| match never {}).boxed())
1331 .unwrap(),
1332 }
1333 }
1334 .instrument(span)
1335 .await
1336 }) as Pin<Box<dyn Future<Output = HttpResponse> + Send>>
1337 });
1338
1339 self.fallback = Some(handler);
1340 self
1341 }
1342
1343 pub async fn run(self, resources: R) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
1345 self.run_with_shutdown_signal(resources, shutdown_signal())
1346 .await
1347 }
1348
1349 async fn run_with_shutdown_signal<S>(
1350 self,
1351 resources: R,
1352 shutdown_signal: S,
1353 ) -> Result<(), Box<dyn std::error::Error + Send + Sync>>
1354 where
1355 S: Future<Output = ()> + Send,
1356 {
1357 let addr_str = self.addr.as_deref().unwrap_or("127.0.0.1:3000");
1358 let addr: SocketAddr = addr_str.parse()?;
1359
1360 let routes = Arc::new(self.routes);
1361 let fallback = self.fallback;
1362 let layers = Arc::new(self.layers);
1363 let health = Arc::new(self.health);
1364 let static_assets = Arc::new(self.static_assets);
1365 let on_start = self.on_start;
1366 let on_shutdown = self.on_shutdown;
1367 let graceful_shutdown_timeout = self.graceful_shutdown_timeout;
1368 let resources = Arc::new(resources);
1369
1370 let listener = TcpListener::bind(addr).await?;
1371 tracing::info!("Ranvier HTTP Ingress listening on http://{}", addr);
1372 if let Some(callback) = on_start.as_ref() {
1373 callback();
1374 }
1375
1376 tokio::pin!(shutdown_signal);
1377 let mut connections = tokio::task::JoinSet::new();
1378
1379 loop {
1380 tokio::select! {
1381 _ = &mut shutdown_signal => {
1382 tracing::info!("Shutdown signal received. Draining in-flight connections.");
1383 break;
1384 }
1385 accept_result = listener.accept() => {
1386 let (stream, _) = accept_result?;
1387 let io = TokioIo::new(stream);
1388
1389 let routes = routes.clone();
1390 let fallback = fallback.clone();
1391 let resources = resources.clone();
1392 let layers = layers.clone();
1393 let health = health.clone();
1394 let static_assets = static_assets.clone();
1395
1396 connections.spawn(async move {
1397 let service = build_http_service(
1398 routes,
1399 fallback,
1400 resources,
1401 layers,
1402 health,
1403 static_assets,
1404 );
1405 let hyper_service = TowerToHyperService::new(service);
1406 if let Err(err) = http1::Builder::new()
1407 .serve_connection(io, hyper_service)
1408 .with_upgrades()
1409 .await
1410 {
1411 tracing::error!("Error serving connection: {:?}", err);
1412 }
1413 });
1414 }
1415 Some(join_result) = connections.join_next(), if !connections.is_empty() => {
1416 if let Err(err) = join_result {
1417 tracing::warn!("Connection task join error: {:?}", err);
1418 }
1419 }
1420 }
1421 }
1422
1423 let _timed_out = drain_connections(&mut connections, graceful_shutdown_timeout).await;
1424
1425 drop(resources);
1426 if let Some(callback) = on_shutdown.as_ref() {
1427 callback();
1428 }
1429
1430 Ok(())
1431 }
1432
1433 pub fn into_raw_service(self, resources: R) -> RawIngressService<R> {
1449 let routes = Arc::new(self.routes);
1450 let fallback = self.fallback;
1451 let layers = Arc::new(self.layers);
1452 let health = Arc::new(self.health);
1453 let static_assets = Arc::new(self.static_assets);
1454 let resources = Arc::new(resources);
1455
1456 RawIngressService {
1457 routes,
1458 fallback,
1459 layers,
1460 health,
1461 static_assets,
1462 resources,
1463 }
1464 }
1465}
1466
1467fn build_http_service<R>(
1468 routes: Arc<Vec<RouteEntry<R>>>,
1469 fallback: Option<RouteHandler<R>>,
1470 resources: Arc<R>,
1471 layers: Arc<Vec<ServiceLayer>>,
1472 health: Arc<HealthConfig<R>>,
1473 static_assets: Arc<StaticAssetsConfig>,
1474) -> BoxHttpService
1475where
1476 R: ranvier_core::transition::ResourceRequirement + Clone + Send + Sync + 'static,
1477{
1478 let base_service = service_fn(move |req: Request<Incoming>| {
1479 let routes = routes.clone();
1480 let fallback = fallback.clone();
1481 let resources = resources.clone();
1482 let layers = layers.clone();
1483 let health = health.clone();
1484 let static_assets = static_assets.clone();
1485
1486 async move {
1487 let mut req = req;
1488 let method = req.method().clone();
1489 let path = req.uri().path().to_string();
1490
1491 if let Some(response) =
1492 maybe_handle_health_request(&method, &path, &health, resources.clone()).await
1493 {
1494 return Ok::<_, Infallible>(response.into_response());
1495 }
1496
1497 if let Some((entry, params)) = find_matching_route(routes.as_slice(), &method, &path) {
1498 req.extensions_mut().insert(params);
1499 let effective_layers = if entry.apply_global_layers {
1500 merge_layers(&layers, &entry.layers)
1501 } else {
1502 entry.layers.clone()
1503 };
1504
1505 if effective_layers.is_empty() {
1506 Ok::<_, Infallible>((entry.handler)(req, &resources).await)
1507 } else {
1508 let route_service = build_route_service(
1509 entry.handler.clone(),
1510 resources.clone(),
1511 effective_layers,
1512 );
1513 route_service.oneshot(req).await
1514 }
1515 } else {
1516 let req =
1517 match maybe_handle_static_request(req, &method, &path, static_assets.as_ref())
1518 .await
1519 {
1520 Ok(req) => req,
1521 Err(response) => return Ok(response),
1522 };
1523
1524 if let Some(ref fb) = fallback {
1525 if layers.is_empty() {
1526 Ok(fb(req, &resources).await)
1527 } else {
1528 let fallback_service =
1529 build_route_service(fb.clone(), resources.clone(), layers.clone());
1530 fallback_service.oneshot(req).await
1531 }
1532 } else {
1533 Ok(Response::builder()
1534 .status(StatusCode::NOT_FOUND)
1535 .body(Full::new(Bytes::from("Not Found")).map_err(|never| match never {}).boxed())
1536 .unwrap())
1537 }
1538 }
1539 }
1540 });
1541
1542 BoxCloneService::new(base_service)
1543}
1544
1545fn build_route_service<R>(
1546 handler: RouteHandler<R>,
1547 resources: Arc<R>,
1548 layers: Arc<Vec<ServiceLayer>>,
1549) -> BoxHttpService
1550where
1551 R: ranvier_core::transition::ResourceRequirement + Clone + Send + Sync + 'static,
1552{
1553 let base_service = service_fn(move |req: Request<Incoming>| {
1554 let handler = handler.clone();
1555 let resources = resources.clone();
1556 async move { Ok::<_, Infallible>(handler(req, &resources).await) }
1557 });
1558
1559 let mut service = BoxCloneService::new(base_service);
1560 for layer in layers.iter() {
1561 service = layer(service);
1562 }
1563 service
1564}
1565
1566fn merge_layers(
1567 global_layers: &Arc<Vec<ServiceLayer>>,
1568 route_layers: &Arc<Vec<ServiceLayer>>,
1569) -> Arc<Vec<ServiceLayer>> {
1570 if global_layers.is_empty() {
1571 return route_layers.clone();
1572 }
1573 if route_layers.is_empty() {
1574 return global_layers.clone();
1575 }
1576
1577 let mut combined = Vec::with_capacity(global_layers.len() + route_layers.len());
1578 combined.extend(global_layers.iter().cloned());
1579 combined.extend(route_layers.iter().cloned());
1580 Arc::new(combined)
1581}
1582
1583async fn maybe_handle_health_request<R>(
1584 method: &Method,
1585 path: &str,
1586 health: &HealthConfig<R>,
1587 resources: Arc<R>,
1588) -> Option<HttpResponse>
1589where
1590 R: ranvier_core::transition::ResourceRequirement + Clone + Send + Sync + 'static,
1591{
1592 if method != Method::GET {
1593 return None;
1594 }
1595
1596 if let Some(liveness_path) = health.liveness_path.as_ref() {
1597 if path == liveness_path {
1598 return Some(health_json_response("liveness", true, Vec::new()));
1599 }
1600 }
1601
1602 if let Some(readiness_path) = health.readiness_path.as_ref() {
1603 if path == readiness_path {
1604 let (healthy, checks) = run_named_health_checks(&health.checks, resources).await;
1605 return Some(health_json_response("readiness", healthy, checks));
1606 }
1607 }
1608
1609 if let Some(health_path) = health.health_path.as_ref() {
1610 if path == health_path {
1611 let (healthy, checks) = run_named_health_checks(&health.checks, resources).await;
1612 return Some(health_json_response("health", healthy, checks));
1613 }
1614 }
1615
1616 None
1617}
1618
1619async fn maybe_handle_static_request(
1620 req: Request<Incoming>,
1621 method: &Method,
1622 path: &str,
1623 static_assets: &StaticAssetsConfig,
1624) -> Result<Request<Incoming>, HttpResponse> {
1625 if method != Method::GET && method != Method::HEAD {
1626 return Ok(req);
1627 }
1628
1629 if let Some(mount) = static_assets
1630 .mounts
1631 .iter()
1632 .find(|mount| strip_mount_prefix(path, &mount.route_prefix).is_some())
1633 {
1634 let accept_encoding = req.headers().get(http::header::ACCEPT_ENCODING).cloned();
1635 let Some(stripped_path) = strip_mount_prefix(path, &mount.route_prefix) else {
1636 return Ok(req);
1637 };
1638 let rewritten = rewrite_request_path(req, &stripped_path);
1639 let service = ServeDir::new(&mount.directory);
1640 let response = match service.oneshot(rewritten).await {
1641 Ok(response) => response,
1642 Err(_) => {
1643 return Err(Response::builder()
1644 .status(StatusCode::INTERNAL_SERVER_ERROR)
1645 .body(Full::new(Bytes::from("Failed to serve static asset")).map_err(|never| match never {}).boxed())
1646 .unwrap_or_else(|_| Response::new(Full::new(Bytes::new()).map_err(|never| match never {}).boxed())));
1647 }
1648 };
1649 let response =
1650 collect_static_response(response, static_assets.cache_control.as_deref()).await;
1651 let response = maybe_compress_static_response(
1652 response,
1653 accept_encoding,
1654 static_assets.enable_compression,
1655 )
1656 .await;
1657 let (parts, body) = response.into_parts();
1658 return Err(Response::from_parts(parts, body.map_err(|never| match never {}).boxed()));
1659 }
1660
1661 if let Some(spa_file) = static_assets.spa_fallback.as_ref() {
1662 if looks_like_spa_request(path) {
1663 let accept_encoding = req.headers().get(http::header::ACCEPT_ENCODING).cloned();
1664 let service = ServeFile::new(spa_file);
1665 let response = match service.oneshot(req).await {
1666 Ok(response) => response,
1667 Err(_) => {
1668 return Err(Response::builder()
1669 .status(StatusCode::INTERNAL_SERVER_ERROR)
1670 .body(Full::new(Bytes::from("Failed to serve SPA fallback")).map_err(|never| match never {}).boxed())
1671 .unwrap_or_else(|_| Response::new(Full::new(Bytes::new()).map_err(|never| match never {}).boxed())));
1672 }
1673 };
1674 let response =
1675 collect_static_response(response, static_assets.cache_control.as_deref()).await;
1676 let response = maybe_compress_static_response(
1677 response,
1678 accept_encoding,
1679 static_assets.enable_compression,
1680 )
1681 .await;
1682 let (parts, body) = response.into_parts();
1683 return Err(Response::from_parts(parts, body.map_err(|never| match never {}).boxed()));
1684 }
1685 }
1686
1687 Ok(req)
1688}
1689
1690fn strip_mount_prefix(path: &str, prefix: &str) -> Option<String> {
1691 let normalized_prefix = if prefix == "/" {
1692 "/"
1693 } else {
1694 prefix.trim_end_matches('/')
1695 };
1696
1697 if normalized_prefix == "/" {
1698 return Some(path.to_string());
1699 }
1700
1701 if path == normalized_prefix {
1702 return Some("/".to_string());
1703 }
1704
1705 let with_slash = format!("{normalized_prefix}/");
1706 path.strip_prefix(&with_slash)
1707 .map(|stripped| format!("/{}", stripped))
1708}
1709
1710fn rewrite_request_path(mut req: Request<Incoming>, new_path: &str) -> Request<Incoming> {
1711 let query = req.uri().query().map(str::to_string);
1712 let path_and_query = match query {
1713 Some(query) => format!("{new_path}?{query}"),
1714 None => new_path.to_string(),
1715 };
1716
1717 let mut parts = req.uri().clone().into_parts();
1718 if let Ok(parsed_path_and_query) = path_and_query.parse() {
1719 parts.path_and_query = Some(parsed_path_and_query);
1720 if let Ok(uri) = Uri::from_parts(parts) {
1721 *req.uri_mut() = uri;
1722 }
1723 }
1724
1725 req
1726}
1727
1728async fn collect_static_response<B>(
1729 response: Response<B>,
1730 cache_control: Option<&str>,
1731) -> Response<Full<Bytes>>
1732where
1733 B: Body<Data = Bytes> + Send + 'static,
1734 B::Error: std::fmt::Display,
1735{
1736 let status = response.status();
1737 let headers = response.headers().clone();
1738 let body = response.into_body();
1739 let collected = body.collect().await;
1740
1741 let bytes = match collected {
1742 Ok(value) => value.to_bytes(),
1743 Err(error) => Bytes::from(error.to_string()),
1744 };
1745
1746 let mut builder = Response::builder().status(status);
1747 for (name, value) in headers.iter() {
1748 builder = builder.header(name, value);
1749 }
1750
1751 let mut response = builder
1752 .body(Full::new(bytes))
1753 .unwrap_or_else(|_| Response::new(Full::new(Bytes::new())));
1754
1755 if status == StatusCode::OK {
1756 if let Some(value) = cache_control {
1757 if !response.headers().contains_key(http::header::CACHE_CONTROL) {
1758 if let Ok(header_value) = http::HeaderValue::from_str(value) {
1759 response
1760 .headers_mut()
1761 .insert(http::header::CACHE_CONTROL, header_value);
1762 }
1763 }
1764 }
1765 }
1766
1767 response
1768}
1769
1770fn looks_like_spa_request(path: &str) -> bool {
1771 let tail = path.rsplit('/').next().unwrap_or_default();
1772 !tail.contains('.')
1773}
1774
1775async fn maybe_compress_static_response(
1776 response: Response<Full<Bytes>>,
1777 accept_encoding: Option<http::HeaderValue>,
1778 enable_compression: bool,
1779) -> Response<Full<Bytes>> {
1780 if !enable_compression {
1781 return response;
1782 }
1783
1784 let Some(accept_encoding) = accept_encoding else {
1785 return response;
1786 };
1787
1788 let mut request = Request::builder()
1789 .uri("/")
1790 .body(Full::new(Bytes::new()))
1791 .unwrap_or_else(|_| Request::new(Full::new(Bytes::new())));
1792 request
1793 .headers_mut()
1794 .insert(http::header::ACCEPT_ENCODING, accept_encoding);
1795
1796 let service = CompressionLayer::new().layer(service_fn({
1797 let response = response.clone();
1798 move |_req: Request<Full<Bytes>>| {
1799 let response = response.clone();
1800 async move { Ok::<_, Infallible>(response) }
1801 }
1802 }));
1803
1804 match service.oneshot(request).await {
1805 Ok(compressed) => collect_static_response(compressed, None).await,
1806 Err(_) => response,
1807 }
1808}
1809
1810async fn run_named_health_checks<R>(
1811 checks: &[NamedHealthCheck<R>],
1812 resources: Arc<R>,
1813) -> (bool, Vec<HealthCheckReport>)
1814where
1815 R: ranvier_core::transition::ResourceRequirement + Clone + Send + Sync + 'static,
1816{
1817 let mut reports = Vec::with_capacity(checks.len());
1818 let mut healthy = true;
1819
1820 for check in checks {
1821 match (check.check)(resources.clone()).await {
1822 Ok(()) => reports.push(HealthCheckReport {
1823 name: check.name.clone(),
1824 status: "ok",
1825 error: None,
1826 }),
1827 Err(error) => {
1828 healthy = false;
1829 reports.push(HealthCheckReport {
1830 name: check.name.clone(),
1831 status: "error",
1832 error: Some(error),
1833 });
1834 }
1835 }
1836 }
1837
1838 (healthy, reports)
1839}
1840
1841fn health_json_response(
1842 probe: &'static str,
1843 healthy: bool,
1844 checks: Vec<HealthCheckReport>,
1845) -> HttpResponse {
1846 let status_code = if healthy {
1847 StatusCode::OK
1848 } else {
1849 StatusCode::SERVICE_UNAVAILABLE
1850 };
1851 let status = if healthy { "ok" } else { "degraded" };
1852 let payload = HealthReport {
1853 status,
1854 probe,
1855 checks,
1856 };
1857
1858 let body = serde_json::to_vec(&payload)
1859 .unwrap_or_else(|_| br#"{"status":"error","probe":"health"}"#.to_vec());
1860
1861 Response::builder()
1862 .status(status_code)
1863 .header(http::header::CONTENT_TYPE, "application/json")
1864 .body(Full::new(Bytes::from(body)).map_err(|never| match never {}).boxed())
1865 .unwrap()
1866}
1867
1868async fn shutdown_signal() {
1869 #[cfg(unix)]
1870 {
1871 use tokio::signal::unix::{SignalKind, signal};
1872
1873 match signal(SignalKind::terminate()) {
1874 Ok(mut terminate) => {
1875 tokio::select! {
1876 _ = tokio::signal::ctrl_c() => {}
1877 _ = terminate.recv() => {}
1878 }
1879 }
1880 Err(err) => {
1881 tracing::warn!("Failed to install SIGTERM handler: {:?}", err);
1882 if let Err(ctrl_c_err) = tokio::signal::ctrl_c().await {
1883 tracing::warn!("Failed to listen for Ctrl+C: {:?}", ctrl_c_err);
1884 }
1885 }
1886 }
1887 }
1888
1889 #[cfg(not(unix))]
1890 {
1891 if let Err(err) = tokio::signal::ctrl_c().await {
1892 tracing::warn!("Failed to listen for Ctrl+C: {:?}", err);
1893 }
1894 }
1895}
1896
1897async fn drain_connections(
1898 connections: &mut tokio::task::JoinSet<()>,
1899 graceful_shutdown_timeout: Duration,
1900) -> bool {
1901 if connections.is_empty() {
1902 return false;
1903 }
1904
1905 let drain_result = tokio::time::timeout(graceful_shutdown_timeout, async {
1906 while let Some(join_result) = connections.join_next().await {
1907 if let Err(err) = join_result {
1908 tracing::warn!("Connection task join error during shutdown: {:?}", err);
1909 }
1910 }
1911 })
1912 .await;
1913
1914 if drain_result.is_err() {
1915 tracing::warn!(
1916 "Graceful shutdown timeout reached ({:?}). Aborting remaining connections.",
1917 graceful_shutdown_timeout
1918 );
1919 connections.abort_all();
1920 while let Some(join_result) = connections.join_next().await {
1921 if let Err(err) = join_result {
1922 tracing::warn!("Connection task abort join error: {:?}", err);
1923 }
1924 }
1925 true
1926 } else {
1927 false
1928 }
1929}
1930
1931impl<R> Default for HttpIngress<R>
1932where
1933 R: ranvier_core::transition::ResourceRequirement + Clone + Send + Sync + 'static,
1934{
1935 fn default() -> Self {
1936 Self::new()
1937 }
1938}
1939
1940#[derive(Clone)]
1942pub struct RawIngressService<R> {
1943 routes: Arc<Vec<RouteEntry<R>>>,
1944 fallback: Option<RouteHandler<R>>,
1945 layers: Arc<Vec<ServiceLayer>>,
1946 health: Arc<HealthConfig<R>>,
1947 static_assets: Arc<StaticAssetsConfig>,
1948 resources: Arc<R>,
1949}
1950
1951impl<R> Service<Request<Incoming>> for RawIngressService<R>
1952where
1953 R: ranvier_core::transition::ResourceRequirement + Clone + Send + Sync + 'static,
1954{
1955 type Response = HttpResponse;
1956 type Error = Infallible;
1957 type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
1958
1959 fn poll_ready(
1960 &mut self,
1961 _cx: &mut std::task::Context<'_>,
1962 ) -> std::task::Poll<Result<(), Self::Error>> {
1963 std::task::Poll::Ready(Ok(()))
1964 }
1965
1966 fn call(&mut self, req: Request<Incoming>) -> Self::Future {
1967 let routes = self.routes.clone();
1968 let fallback = self.fallback.clone();
1969 let layers = self.layers.clone();
1970 let health = self.health.clone();
1971 let static_assets = self.static_assets.clone();
1972 let resources = self.resources.clone();
1973
1974 Box::pin(async move {
1975 let service =
1976 build_http_service(routes, fallback, resources, layers, health, static_assets);
1977 service.oneshot(req).await
1978 })
1979 }
1980}
1981
1982#[cfg(test)]
1983mod tests {
1984 use super::*;
1985 use async_trait::async_trait;
1986 use futures_util::{SinkExt, StreamExt};
1987 use ranvier_observe::{HttpMetrics, HttpMetricsLayer, IncomingTraceContext, TraceContextLayer};
1988 use serde::Deserialize;
1989 use std::fs;
1990 use std::sync::atomic::{AtomicBool, Ordering};
1991 use tempfile::tempdir;
1992 use tokio::io::{AsyncReadExt, AsyncWriteExt};
1993 use tokio_tungstenite::tungstenite::Message as WsClientMessage;
1994 use tokio_tungstenite::tungstenite::client::IntoClientRequest;
1995
1996 async fn connect_with_retry(addr: std::net::SocketAddr) -> tokio::net::TcpStream {
1997 let deadline = tokio::time::Instant::now() + Duration::from_secs(2);
1998
1999 loop {
2000 match tokio::net::TcpStream::connect(addr).await {
2001 Ok(stream) => return stream,
2002 Err(error) => {
2003 if tokio::time::Instant::now() >= deadline {
2004 panic!("connect server: {error}");
2005 }
2006 tokio::time::sleep(Duration::from_millis(25)).await;
2007 }
2008 }
2009 }
2010 }
2011
2012 #[test]
2013 fn route_pattern_matches_static_path() {
2014 let pattern = RoutePattern::parse("/orders/list");
2015 let params = pattern.match_path("/orders/list").expect("should match");
2016 assert!(params.into_inner().is_empty());
2017 }
2018
2019 #[test]
2020 fn route_pattern_matches_param_segments() {
2021 let pattern = RoutePattern::parse("/orders/:id/items/:item_id");
2022 let params = pattern
2023 .match_path("/orders/42/items/sku-123")
2024 .expect("should match");
2025 assert_eq!(params.get("id"), Some("42"));
2026 assert_eq!(params.get("item_id"), Some("sku-123"));
2027 }
2028
2029 #[test]
2030 fn route_pattern_matches_wildcard_segment() {
2031 let pattern = RoutePattern::parse("/assets/*path");
2032 let params = pattern
2033 .match_path("/assets/css/theme/light.css")
2034 .expect("should match");
2035 assert_eq!(params.get("path"), Some("css/theme/light.css"));
2036 }
2037
2038 #[test]
2039 fn route_pattern_rejects_non_matching_path() {
2040 let pattern = RoutePattern::parse("/orders/:id");
2041 assert!(pattern.match_path("/users/42").is_none());
2042 }
2043
2044 #[test]
2045 fn graceful_shutdown_timeout_defaults_to_30_seconds() {
2046 let ingress = HttpIngress::<()>::new();
2047 assert_eq!(ingress.graceful_shutdown_timeout, Duration::from_secs(30));
2048 assert!(ingress.layers.is_empty());
2049 assert!(ingress.bus_injectors.is_empty());
2050 assert!(ingress.static_assets.mounts.is_empty());
2051 assert!(ingress.on_start.is_none());
2052 assert!(ingress.on_shutdown.is_none());
2053 }
2054
2055 #[test]
2056 fn layer_registration_stacks_globally() {
2057 let ingress = HttpIngress::<()>::new()
2058 .layer(tower::layer::util::Identity::new())
2059 .layer(tower::layer::util::Identity::new());
2060 assert_eq!(ingress.layers.len(), 2);
2061 }
2062
2063 #[test]
2064 fn layer_accepts_tower_http_cors_layer() {
2065 let ingress = HttpIngress::<()>::new().layer(tower_http::cors::CorsLayer::permissive());
2066 assert_eq!(ingress.layers.len(), 1);
2067 }
2068
2069 #[test]
2070 fn route_without_layer_keeps_empty_route_middleware_stack() {
2071 let ingress =
2072 HttpIngress::<()>::new().get("/ping", Axon::<(), (), Infallible, ()>::new("Ping"));
2073 assert_eq!(ingress.routes.len(), 1);
2074 assert!(ingress.routes[0].layers.is_empty());
2075 assert!(ingress.routes[0].apply_global_layers);
2076 }
2077
2078 #[test]
2079 fn route_with_layer_registers_route_middleware_stack() {
2080 let ingress = HttpIngress::<()>::new().get_with_layer(
2081 "/ping",
2082 Axon::<(), (), Infallible, ()>::new("Ping"),
2083 tower::layer::util::Identity::new(),
2084 );
2085 assert_eq!(ingress.routes.len(), 1);
2086 assert_eq!(ingress.routes[0].layers.len(), 1);
2087 assert!(ingress.routes[0].apply_global_layers);
2088 }
2089
2090 #[test]
2091 fn route_with_layer_override_disables_global_layers() {
2092 let ingress = HttpIngress::<()>::new().get_with_layer_override(
2093 "/ping",
2094 Axon::<(), (), Infallible, ()>::new("Ping"),
2095 tower::layer::util::Identity::new(),
2096 );
2097 assert_eq!(ingress.routes.len(), 1);
2098 assert_eq!(ingress.routes[0].layers.len(), 1);
2099 assert!(!ingress.routes[0].apply_global_layers);
2100 }
2101
2102 #[test]
2103 fn timeout_layer_registers_builtin_middleware() {
2104 let ingress = HttpIngress::<()>::new().timeout_layer(Duration::from_secs(1));
2105 assert_eq!(ingress.layers.len(), 1);
2106 }
2107
2108 #[test]
2109 fn request_id_layer_registers_builtin_middleware() {
2110 let ingress = HttpIngress::<()>::new().request_id_layer();
2111 assert_eq!(ingress.layers.len(), 1);
2112 }
2113
2114 #[test]
2115 fn compression_layer_registers_builtin_middleware() {
2116 let ingress = HttpIngress::<()>::new().compression_layer();
2117 assert!(ingress.static_assets.enable_compression);
2118 }
2119
2120 #[test]
2121 fn bus_injector_registration_adds_hook() {
2122 let ingress = HttpIngress::<()>::new().bus_injector(|_req, bus| {
2123 bus.insert("ok".to_string());
2124 });
2125 assert_eq!(ingress.bus_injectors.len(), 1);
2126 }
2127
2128 #[test]
2129 fn ws_route_registers_get_route_pattern() {
2130 let ingress =
2131 HttpIngress::<()>::new().ws("/ws/events", |_socket, _resources, _bus| async {});
2132 assert_eq!(ingress.routes.len(), 1);
2133 assert_eq!(ingress.routes[0].method, Method::GET);
2134 assert_eq!(ingress.routes[0].pattern.raw, "/ws/events");
2135 }
2136
2137 #[derive(Debug, Deserialize)]
2138 struct WsWelcomeFrame {
2139 connection_id: String,
2140 path: String,
2141 tenant: String,
2142 }
2143
2144 #[tokio::test]
2145 async fn ws_route_upgrades_and_bridges_event_source_sink_with_connection_bus() {
2146 let probe = std::net::TcpListener::bind("127.0.0.1:0").expect("bind probe");
2147 let addr = probe.local_addr().expect("local addr");
2148 drop(probe);
2149
2150 let ingress = HttpIngress::<()>::new()
2151 .bind(addr.to_string())
2152 .bus_injector(|req, bus| {
2153 if let Some(value) = req
2154 .headers()
2155 .get("x-tenant-id")
2156 .and_then(|v| v.to_str().ok())
2157 {
2158 bus.insert(value.to_string());
2159 }
2160 })
2161 .ws("/ws/echo", |mut socket, _resources, bus| async move {
2162 let tenant = bus
2163 .read::<String>()
2164 .cloned()
2165 .unwrap_or_else(|| "unknown".to_string());
2166 if let Some(session) = bus.read::<WebSocketSessionContext>() {
2167 let welcome = serde_json::json!({
2168 "connection_id": session.connection_id().to_string(),
2169 "path": session.path(),
2170 "tenant": tenant,
2171 });
2172 let _ = socket.send_json(&welcome).await;
2173 }
2174
2175 while let Some(event) = socket.next_event().await {
2176 match event {
2177 WebSocketEvent::Text(text) => {
2178 let _ = socket.send_event(format!("echo:{text}")).await;
2179 }
2180 WebSocketEvent::Binary(bytes) => {
2181 let _ = socket.send_event(bytes).await;
2182 }
2183 WebSocketEvent::Close => break,
2184 WebSocketEvent::Ping(_) | WebSocketEvent::Pong(_) => {}
2185 }
2186 }
2187 });
2188
2189 let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel::<()>();
2190 let server = tokio::spawn(async move {
2191 ingress
2192 .run_with_shutdown_signal((), async move {
2193 let _ = shutdown_rx.await;
2194 })
2195 .await
2196 });
2197
2198 let ws_uri = format!("ws://{addr}/ws/echo?room=alpha");
2199 let mut ws_request = ws_uri
2200 .as_str()
2201 .into_client_request()
2202 .expect("ws client request");
2203 ws_request
2204 .headers_mut()
2205 .insert("x-tenant-id", http::HeaderValue::from_static("acme"));
2206 let (mut client, _response) = tokio_tungstenite::connect_async(ws_request)
2207 .await
2208 .expect("websocket connect");
2209
2210 let welcome = client
2211 .next()
2212 .await
2213 .expect("welcome frame")
2214 .expect("welcome frame ok");
2215 let welcome_text = match welcome {
2216 WsClientMessage::Text(text) => text.to_string(),
2217 other => panic!("expected text welcome frame, got {other:?}"),
2218 };
2219 let welcome_payload: WsWelcomeFrame =
2220 serde_json::from_str(&welcome_text).expect("welcome json");
2221 assert_eq!(welcome_payload.path, "/ws/echo");
2222 assert_eq!(welcome_payload.tenant, "acme");
2223 assert!(!welcome_payload.connection_id.is_empty());
2224
2225 client
2226 .send(WsClientMessage::Text("hello".into()))
2227 .await
2228 .expect("send text");
2229 let echo_text = client
2230 .next()
2231 .await
2232 .expect("echo text frame")
2233 .expect("echo text frame ok");
2234 assert_eq!(echo_text, WsClientMessage::Text("echo:hello".into()));
2235
2236 client
2237 .send(WsClientMessage::Binary(vec![1, 2, 3, 4].into()))
2238 .await
2239 .expect("send binary");
2240 let echo_binary = client
2241 .next()
2242 .await
2243 .expect("echo binary frame")
2244 .expect("echo binary frame ok");
2245 assert_eq!(
2246 echo_binary,
2247 WsClientMessage::Binary(vec![1, 2, 3, 4].into())
2248 );
2249
2250 client.close(None).await.expect("close websocket");
2251
2252 let _ = shutdown_tx.send(());
2253 server
2254 .await
2255 .expect("server join")
2256 .expect("server shutdown should succeed");
2257 }
2258
2259 #[derive(Clone)]
2260 struct EchoTrace;
2261
2262 #[async_trait]
2263 impl Transition<(), String> for EchoTrace {
2264 type Error = Infallible;
2265 type Resources = ();
2266
2267 async fn run(
2268 &self,
2269 _state: (),
2270 _resources: &Self::Resources,
2271 bus: &mut Bus,
2272 ) -> Outcome<String, Self::Error> {
2273 let trace_id = bus
2274 .read::<String>()
2275 .cloned()
2276 .unwrap_or_else(|| "missing-trace".to_string());
2277 Outcome::next(trace_id)
2278 }
2279 }
2280
2281 #[tokio::test]
2282 async fn observe_trace_context_and_metrics_layers_work_with_ingress() {
2283 let metrics = HttpMetrics::default();
2284 let ingress = HttpIngress::<()>::new()
2285 .layer(TraceContextLayer::new())
2286 .layer(HttpMetricsLayer::new(metrics.clone()))
2287 .bus_injector(|req, bus| {
2288 if let Some(trace) = req.extensions().get::<IncomingTraceContext>() {
2289 bus.insert(trace.trace_id().to_string());
2290 }
2291 })
2292 .get(
2293 "/trace",
2294 Axon::<(), (), Infallible, ()>::new("EchoTrace").then(EchoTrace),
2295 );
2296
2297 let app = crate::test_harness::TestApp::new(ingress, ());
2298 let response = app
2299 .send(crate::test_harness::TestRequest::get("/trace").header(
2300 "traceparent",
2301 "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
2302 ))
2303 .await
2304 .expect("request should succeed");
2305
2306 assert_eq!(response.status(), StatusCode::OK);
2307 assert_eq!(
2308 response.text().expect("utf8 response"),
2309 "4bf92f3577b34da6a3ce929d0e0e4736"
2310 );
2311
2312 let snapshot = metrics.snapshot();
2313 assert_eq!(snapshot.requests_total, 1);
2314 assert_eq!(snapshot.requests_error, 0);
2315 }
2316
2317 #[test]
2318 fn route_descriptors_export_http_and_health_paths() {
2319 let ingress = HttpIngress::<()>::new()
2320 .get(
2321 "/orders/:id",
2322 Axon::<(), (), Infallible, ()>::new("OrderById"),
2323 )
2324 .health_endpoint("/healthz")
2325 .readiness_liveness("/readyz", "/livez");
2326
2327 let descriptors = ingress.route_descriptors();
2328
2329 assert!(
2330 descriptors
2331 .iter()
2332 .any(|descriptor| descriptor.method() == Method::GET
2333 && descriptor.path_pattern() == "/orders/:id")
2334 );
2335 assert!(
2336 descriptors
2337 .iter()
2338 .any(|descriptor| descriptor.method() == Method::GET
2339 && descriptor.path_pattern() == "/healthz")
2340 );
2341 assert!(
2342 descriptors
2343 .iter()
2344 .any(|descriptor| descriptor.method() == Method::GET
2345 && descriptor.path_pattern() == "/readyz")
2346 );
2347 assert!(
2348 descriptors
2349 .iter()
2350 .any(|descriptor| descriptor.method() == Method::GET
2351 && descriptor.path_pattern() == "/livez")
2352 );
2353 }
2354
2355 #[tokio::test]
2356 async fn lifecycle_hooks_fire_on_start_and_shutdown() {
2357 let started = Arc::new(AtomicBool::new(false));
2358 let shutdown = Arc::new(AtomicBool::new(false));
2359
2360 let started_flag = started.clone();
2361 let shutdown_flag = shutdown.clone();
2362
2363 let ingress = HttpIngress::<()>::new()
2364 .bind("127.0.0.1:0")
2365 .on_start(move || {
2366 started_flag.store(true, Ordering::SeqCst);
2367 })
2368 .on_shutdown(move || {
2369 shutdown_flag.store(true, Ordering::SeqCst);
2370 })
2371 .graceful_shutdown(Duration::from_millis(50));
2372
2373 ingress
2374 .run_with_shutdown_signal((), async {
2375 tokio::time::sleep(Duration::from_millis(20)).await;
2376 })
2377 .await
2378 .expect("server should exit gracefully");
2379
2380 assert!(started.load(Ordering::SeqCst));
2381 assert!(shutdown.load(Ordering::SeqCst));
2382 }
2383
2384 #[tokio::test]
2385 async fn graceful_shutdown_drains_in_flight_requests_before_exit() {
2386 #[derive(Clone)]
2387 struct SlowDrainRoute;
2388
2389 #[async_trait]
2390 impl Transition<(), &'static str> for SlowDrainRoute {
2391 type Error = Infallible;
2392 type Resources = ();
2393
2394 async fn run(
2395 &self,
2396 _state: (),
2397 _resources: &Self::Resources,
2398 _bus: &mut Bus,
2399 ) -> Outcome<&'static str, Self::Error> {
2400 tokio::time::sleep(Duration::from_millis(120)).await;
2401 Outcome::next("drained-ok")
2402 }
2403 }
2404
2405 let probe = std::net::TcpListener::bind("127.0.0.1:0").expect("bind probe");
2406 let addr = probe.local_addr().expect("local addr");
2407 drop(probe);
2408
2409 let ingress = HttpIngress::<()>::new()
2410 .bind(addr.to_string())
2411 .graceful_shutdown(Duration::from_millis(500))
2412 .get(
2413 "/drain",
2414 Axon::<(), (), Infallible, ()>::new("SlowDrain").then(SlowDrainRoute),
2415 );
2416
2417 let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel::<()>();
2418 let server = tokio::spawn(async move {
2419 ingress
2420 .run_with_shutdown_signal((), async move {
2421 let _ = shutdown_rx.await;
2422 })
2423 .await
2424 });
2425
2426 let mut stream = connect_with_retry(addr).await;
2427 stream
2428 .write_all(b"GET /drain HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")
2429 .await
2430 .expect("write request");
2431
2432 tokio::time::sleep(Duration::from_millis(20)).await;
2433 let _ = shutdown_tx.send(());
2434
2435 let mut buf = Vec::new();
2436 stream.read_to_end(&mut buf).await.expect("read response");
2437 let response = String::from_utf8_lossy(&buf);
2438 assert!(response.starts_with("HTTP/1.1 200"), "{response}");
2439 assert!(response.contains("drained-ok"), "{response}");
2440
2441 server
2442 .await
2443 .expect("server join")
2444 .expect("server shutdown should succeed");
2445 }
2446
2447 #[tokio::test]
2448 async fn serve_dir_serves_static_file_with_cache_and_metadata_headers() {
2449 let temp = tempdir().expect("tempdir");
2450 let root = temp.path().join("public");
2451 fs::create_dir_all(&root).expect("create dir");
2452 let file = root.join("hello.txt");
2453 fs::write(&file, "hello static").expect("write file");
2454
2455 let ingress =
2456 Ranvier::http::<()>().serve_dir("/static", root.to_string_lossy().to_string());
2457 let app = crate::test_harness::TestApp::new(ingress, ());
2458 let response = app
2459 .send(crate::test_harness::TestRequest::get("/static/hello.txt"))
2460 .await
2461 .expect("request should succeed");
2462
2463 assert_eq!(response.status(), StatusCode::OK);
2464 assert_eq!(response.text().expect("utf8"), "hello static");
2465 assert!(response.header("cache-control").is_some());
2466 let has_metadata_header =
2467 response.header("etag").is_some() || response.header("last-modified").is_some();
2468 assert!(has_metadata_header);
2469 }
2470
2471 #[tokio::test]
2472 async fn spa_fallback_returns_index_for_unmatched_path() {
2473 let temp = tempdir().expect("tempdir");
2474 let index = temp.path().join("index.html");
2475 fs::write(&index, "<html><body>spa</body></html>").expect("write index");
2476
2477 let ingress = Ranvier::http::<()>().spa_fallback(index.to_string_lossy().to_string());
2478 let app = crate::test_harness::TestApp::new(ingress, ());
2479 let response = app
2480 .send(crate::test_harness::TestRequest::get("/dashboard/settings"))
2481 .await
2482 .expect("request should succeed");
2483
2484 assert_eq!(response.status(), StatusCode::OK);
2485 assert!(response.text().expect("utf8").contains("spa"));
2486 }
2487
2488 #[tokio::test]
2489 async fn static_compression_layer_sets_content_encoding_for_gzip_client() {
2490 let temp = tempdir().expect("tempdir");
2491 let root = temp.path().join("public");
2492 fs::create_dir_all(&root).expect("create dir");
2493 let file = root.join("compressed.txt");
2494 fs::write(&file, "compress me ".repeat(400)).expect("write file");
2495
2496 let ingress = Ranvier::http::<()>()
2497 .serve_dir("/static", root.to_string_lossy().to_string())
2498 .compression_layer();
2499 let app = crate::test_harness::TestApp::new(ingress, ());
2500 let response = app
2501 .send(
2502 crate::test_harness::TestRequest::get("/static/compressed.txt")
2503 .header("accept-encoding", "gzip"),
2504 )
2505 .await
2506 .expect("request should succeed");
2507
2508 assert_eq!(response.status(), StatusCode::OK);
2509 assert_eq!(
2510 response
2511 .header("content-encoding")
2512 .and_then(|value| value.to_str().ok()),
2513 Some("gzip")
2514 );
2515 }
2516
2517 #[tokio::test]
2518 async fn drain_connections_completes_before_timeout() {
2519 let mut connections = tokio::task::JoinSet::new();
2520 connections.spawn(async {
2521 tokio::time::sleep(Duration::from_millis(20)).await;
2522 });
2523
2524 let timed_out = drain_connections(&mut connections, Duration::from_millis(200)).await;
2525 assert!(!timed_out);
2526 assert!(connections.is_empty());
2527 }
2528
2529 #[tokio::test]
2530 async fn drain_connections_times_out_and_aborts() {
2531 let mut connections = tokio::task::JoinSet::new();
2532 connections.spawn(async {
2533 tokio::time::sleep(Duration::from_secs(10)).await;
2534 });
2535
2536 let timed_out = drain_connections(&mut connections, Duration::from_millis(10)).await;
2537 assert!(timed_out);
2538 assert!(connections.is_empty());
2539 }
2540
2541 #[tokio::test]
2542 async fn timeout_layer_returns_408_for_slow_route() {
2543 #[derive(Clone)]
2544 struct SlowRoute;
2545
2546 #[async_trait]
2547 impl Transition<(), &'static str> for SlowRoute {
2548 type Error = Infallible;
2549 type Resources = ();
2550
2551 async fn run(
2552 &self,
2553 _state: (),
2554 _resources: &Self::Resources,
2555 _bus: &mut Bus,
2556 ) -> Outcome<&'static str, Self::Error> {
2557 tokio::time::sleep(Duration::from_millis(80)).await;
2558 Outcome::next("slow-ok")
2559 }
2560 }
2561
2562 let probe = std::net::TcpListener::bind("127.0.0.1:0").expect("bind probe");
2563 let addr = probe.local_addr().expect("local addr");
2564 drop(probe);
2565
2566 let ingress = HttpIngress::<()>::new()
2567 .bind(addr.to_string())
2568 .timeout_layer(Duration::from_millis(10))
2569 .get(
2570 "/slow",
2571 Axon::<(), (), Infallible, ()>::new("Slow").then(SlowRoute),
2572 );
2573
2574 let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel::<()>();
2575 let server = tokio::spawn(async move {
2576 ingress
2577 .run_with_shutdown_signal((), async move {
2578 let _ = shutdown_rx.await;
2579 })
2580 .await
2581 });
2582
2583 let mut stream = connect_with_retry(addr).await;
2584 stream
2585 .write_all(b"GET /slow HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")
2586 .await
2587 .expect("write request");
2588
2589 let mut buf = Vec::new();
2590 stream.read_to_end(&mut buf).await.expect("read response");
2591 let response = String::from_utf8_lossy(&buf);
2592 assert!(response.starts_with("HTTP/1.1 408"), "{response}");
2593
2594 let _ = shutdown_tx.send(());
2595 server
2596 .await
2597 .expect("server join")
2598 .expect("server shutdown should succeed");
2599 }
2600
2601 #[tokio::test]
2602 async fn route_layer_override_bypasses_global_timeout() {
2603 #[derive(Clone)]
2604 struct SlowRoute;
2605
2606 #[async_trait]
2607 impl Transition<(), &'static str> for SlowRoute {
2608 type Error = Infallible;
2609 type Resources = ();
2610
2611 async fn run(
2612 &self,
2613 _state: (),
2614 _resources: &Self::Resources,
2615 _bus: &mut Bus,
2616 ) -> Outcome<&'static str, Self::Error> {
2617 tokio::time::sleep(Duration::from_millis(60)).await;
2618 Outcome::next("override-ok")
2619 }
2620 }
2621
2622 let probe = std::net::TcpListener::bind("127.0.0.1:0").expect("bind probe");
2623 let addr = probe.local_addr().expect("local addr");
2624 drop(probe);
2625
2626 let ingress = HttpIngress::<()>::new()
2627 .bind(addr.to_string())
2628 .timeout_layer(Duration::from_millis(10))
2629 .get_with_layer_override(
2630 "/slow",
2631 Axon::<(), (), Infallible, ()>::new("SlowOverride").then(SlowRoute),
2632 tower::layer::util::Identity::new(),
2633 );
2634
2635 let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel::<()>();
2636 let server = tokio::spawn(async move {
2637 ingress
2638 .run_with_shutdown_signal((), async move {
2639 let _ = shutdown_rx.await;
2640 })
2641 .await
2642 });
2643
2644 let mut stream = connect_with_retry(addr).await;
2645 stream
2646 .write_all(b"GET /slow HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")
2647 .await
2648 .expect("write request");
2649
2650 let mut buf = Vec::new();
2651 stream.read_to_end(&mut buf).await.expect("read response");
2652 let response = String::from_utf8_lossy(&buf);
2653 assert!(response.starts_with("HTTP/1.1 200"), "{response}");
2654 assert!(response.contains("override-ok"), "{response}");
2655
2656 let _ = shutdown_tx.send(());
2657 server
2658 .await
2659 .expect("server join")
2660 .expect("server shutdown should succeed");
2661 }
2662}