1use std::future::{Future, IntoFuture};
4use std::net::{IpAddr, SocketAddr};
5use std::path::PathBuf;
6use std::str::FromStr;
7
8use axum::extract::DefaultBodyLimit;
9use axum::http::StatusCode;
10use axum::response::{IntoResponse, Response};
11use axum::routing::get;
12use axum::{Router, serve};
13use tokio::net::TcpListener;
14use tower_http::CompressionLevel;
15use tower_http::LatencyUnit;
16use tower_http::compression::CompressionLayer;
17use tower_http::compression::predicate::{DefaultPredicate, NotForContentType, Predicate};
18use tower_http::trace::{DefaultOnResponse, TraceLayer};
19use tracing::{Level, error, info, instrument, warn};
20
21use crate::env;
22use crate::environment::Environment;
23
24use super::error::WebServerError;
25use super::shutdown::{AppShutdown, DEFAULT_DRAIN_TIMEOUT, Shutdown};
26use super::state::{StateParts, WebServerState};
27use super::telemetry;
28
29pub const ENV_HOST: &str = "WSB_HOST";
31
32pub const ENV_PORT: &str = "WSB_PORT";
34
35pub const DEFAULT_PORT: u16 = 8080;
37
38pub const DEFAULT_BODY_LIMIT: usize = 256 * 1024;
43
44pub const API_PREFIX: &str = "/api/v1";
50
51pub struct WebServer<S = ()> {
58 host: String,
59 port: u16,
60 environment: Environment,
61 app: S,
62
63 body_limit: usize,
64 compression: bool,
65 root_dir: PathBuf,
66 router: Router<WebServerState<S>>,
67
68 #[cfg(feature = "pages")]
69 frontend: Option<super::frontend::FrontendParams<S>>,
70
71 #[cfg(feature = "pages")]
74 feed: Option<crate::feed::Feed>,
75}
76
77impl WebServer<()> {
78 #[must_use]
80 pub fn new(host: impl Into<String>, port: u16, environment: Environment) -> Self {
81 Self::with_state(host, port, environment, ())
82 }
83
84 pub fn from_env() -> Result<Self, WebServerError> {
94 Self::from_env_with_state(())
95 }
96}
97
98impl<S> WebServer<S>
99where
100 S: Clone + Send + Sync + 'static,
101{
102 #[must_use]
104 pub fn with_state(
105 host: impl Into<String>,
106 port: u16,
107 environment: Environment,
108 app: S,
109 ) -> Self {
110 Self {
111 host: host.into(),
112 port,
113 environment,
114 app,
115 body_limit: DEFAULT_BODY_LIMIT,
116 compression: true,
117 root_dir: PathBuf::new(),
119 router: Router::new(),
120 #[cfg(feature = "pages")]
121 frontend: None,
122 #[cfg(feature = "pages")]
123 feed: None,
124 }
125 }
126
127 pub fn from_env_with_state(app: S) -> Result<Self, WebServerError> {
134 let environment: Environment = Environment::from_env()?;
135 let host: String = env::optional(ENV_HOST).unwrap_or_else(|| {
136 if environment.is_production() {
137 String::from("0.0.0.0")
138 } else {
139 String::from("127.0.0.1")
140 }
141 });
142 let port: u16 =
143 env::parse_or(ENV_PORT, "port number", DEFAULT_PORT).map_err(WebServerError::Env)?;
144
145 Ok(Self::with_state(host, port, environment, app))
146 }
147
148 #[must_use]
153 pub const fn body_limit(mut self, body_limit: usize) -> Self {
154 self.body_limit = body_limit;
155 self
156 }
157
158 #[must_use]
167 pub const fn without_compression(mut self) -> Self {
168 self.compression = false;
169 self
170 }
171
172 #[must_use]
180 pub fn root_dir(mut self, root_dir: impl Into<PathBuf>) -> Self {
181 self.root_dir = root_dir.into();
182 self
183 }
184
185 #[must_use]
187 pub fn nest(mut self, path: &str, router: Router<WebServerState<S>>) -> Self {
188 self.router = self.router.nest(path, router);
189 self
190 }
191
192 #[must_use]
194 pub fn merge(mut self, router: Router<WebServerState<S>>) -> Self {
195 self.router = self.router.merge(router);
196 self
197 }
198
199 #[must_use]
201 pub fn nest_service<T>(mut self, path: &str, service: T) -> Self
202 where
203 T: tower::Service<axum::extract::Request, Error = std::convert::Infallible>
204 + Clone
205 + Send
206 + Sync
207 + 'static,
208 T::Response: axum::response::IntoResponse,
209 T::Future: Send + 'static,
210 {
211 self.router = self.router.nest_service(path, service);
212 self
213 }
214
215 #[cfg(feature = "pages")]
222 #[must_use]
223 pub fn frontend(mut self, params: super::frontend::FrontendParams<S>) -> Self {
224 self.frontend = Some(params);
225 self
226 }
227
228 #[cfg(feature = "pages")]
241 #[must_use]
242 pub fn feed(mut self, feed: crate::feed::Feed) -> Self {
243 self.feed = Some(feed);
244 self
245 }
246
247 pub fn into_router(self, shutdown: Shutdown) -> Result<Router, WebServerError> {
263 Ok(self.assemble(shutdown)?.router)
264 }
265
266 #[instrument(skip_all)]
273 pub async fn run(self, shutdown: Shutdown) -> Result<(), WebServerError>
274 where
275 S: AppShutdown,
276 {
277 let Assembled {
278 router,
279 state,
280 host,
281 port,
282 environment,
283 } = self.assemble(shutdown.clone())?;
284
285 if environment.is_production() {
286 tokio::spawn(telemetry::serve_metrics(shutdown.clone()));
287 }
288
289 serve_on(router, &host, port, shutdown, async move {
290 state.app().on_shutdown().await;
291 })
292 .await
293 }
294
295 #[instrument(skip_all)]
300 #[cfg_attr(
301 not(feature = "pages"),
302 expect(unused_mut, reason = "only a frontend merges routes into the router")
303 )]
304 fn assemble(self, shutdown: Shutdown) -> Result<Assembled<S>, WebServerError> {
305 let Self {
306 host,
307 port,
308 environment,
309 app,
310 body_limit,
311 compression,
312 root_dir,
313 router,
314 #[cfg(feature = "pages")]
315 frontend,
316 #[cfg(feature = "pages")]
317 feed,
318 } = self;
319
320 #[cfg(feature = "pages")]
323 if feed.is_some() && frontend.is_none() {
324 return Err(WebServerError::FeedWithoutFrontend);
325 }
326
327 let cache_buster: crate::assets::CacheBuster =
330 crate::assets::CacheBuster::load_in(&root_dir)?;
331
332 let mut no_cache: Router<WebServerState<S>> = router;
333 let mut built_in: Router<WebServerState<S>> = Router::new().route("/health", get(health));
334
335 #[cfg(feature = "pages")]
336 let mut frontend_runtime: Option<crate::templates::FrontendRuntime> = None;
337 #[cfg(feature = "pages")]
338 let mut base: Option<crate::templates::BaseTemplateData> = None;
339 #[cfg(feature = "pages")]
340 let mut templates: Option<crate::templates::TemplateRegistry<'static>> = None;
341 #[cfg(feature = "pages")]
342 let mut not_found: Option<super::not_found::NotFound<S>> = None;
343 #[cfg(feature = "pages")]
344 let mut proxy_scripts: Option<Router<WebServerState<S>>> = None;
345 #[cfg(feature = "pages")]
346 let mut feed_router: Option<Router<WebServerState<S>>> = None;
347
348 log_immutable_assets(&cache_buster);
349
350 #[cfg(feature = "pages")]
351 if let Some(params) = frontend {
352 let assembled: AssembledFrontend<S> =
353 assemble_frontend(params, feed, &cache_buster, environment)?;
354
355 no_cache = no_cache.merge(assembled.routes);
356 built_in = built_in.merge(assembled.api);
357 proxy_scripts = Some(assembled.proxy_scripts);
358 feed_router = assembled.feeds;
359 not_found = Some(assembled.not_found);
360 frontend_runtime = Some(assembled.runtime);
361 base = Some(assembled.base);
362 templates = Some(assembled.templates);
363 }
364
365 let no_cache: Router<WebServerState<S>> = no_cache.nest(API_PREFIX, built_in);
366
367 let mut app_router: Router<WebServerState<S>> = apply_cache_policy(no_cache, &cache_buster);
368
369 #[cfg(feature = "pages")]
373 if let Some(scripts) = proxy_scripts {
374 app_router = app_router.merge(scripts);
375 }
376
377 #[cfg(feature = "pages")]
378 if let Some(feeds) = feed_router {
379 app_router = app_router.merge(feeds);
380 }
381
382 #[cfg(feature = "pages")]
383 let app_router: Router<WebServerState<S>> = attach_not_found(app_router, not_found);
384 #[cfg(not(feature = "pages"))]
385 let app_router: Router<WebServerState<S>> = app_router.fallback(plain_not_found);
386
387 let state: WebServerState<S> = WebServerState::new(StateParts {
388 host: host.clone(),
389 port,
390 environment,
391 shutdown,
392 #[cfg(feature = "templates")]
393 base,
394 #[cfg(feature = "templates")]
395 templates,
396 cache_buster: Some(cache_buster),
397 #[cfg(feature = "templates")]
398 frontend: frontend_runtime,
399 app,
400 });
401
402 let app_router: Router = with_middleware(
405 app_router.with_state(state.clone()),
406 body_limit,
407 compression,
408 );
409
410 Ok(Assembled {
411 router: app_router,
412 state,
413 host,
414 port,
415 environment,
416 })
417 }
418}
419
420fn with_middleware(router: Router, body_limit: usize, compression: bool) -> Router {
427 let router: Router = router
428 .layer(axum::middleware::from_fn(telemetry::http_metrics))
429 .layer(
430 TraceLayer::new_for_http()
431 .make_span_with(|request: &axum::http::Request<axum::body::Body>| {
436 let request_id: &str = request
437 .headers()
438 .get(&telemetry::REQUEST_ID_HEADER)
439 .and_then(|value| value.to_str().ok())
440 .unwrap_or_default();
441 tracing::info_span!(
442 "request",
443 method = %request.method(),
444 path = %request.uri().path(),
445 version = ?request.version(),
446 request_id,
447 )
448 })
449 .on_response(
450 DefaultOnResponse::new()
451 .level(Level::INFO)
452 .latency_unit(LatencyUnit::Millis),
453 ),
454 )
455 .layer(axum::middleware::from_fn(telemetry::request_id));
456 let router: Router = if compression {
457 router.layer(compression_layer())
458 } else {
459 router
460 };
461 router.layer(DefaultBodyLimit::max(body_limit))
462}
463
464fn compression_layer() -> CompressionLayer<impl Predicate> {
473 CompressionLayer::new()
474 .no_deflate()
475 .quality(CompressionLevel::Precise(3))
476 .compress_when(
477 DefaultPredicate::new()
478 .and(NotForContentType::const_new("application/x-ndjson"))
479 .and(NotForContentType::const_new("application/jsonl")),
480 )
481}
482
483struct Assembled<S> {
486 router: Router,
487 state: WebServerState<S>,
490 host: String,
491 port: u16,
492 environment: Environment,
493}
494
495#[cfg(feature = "pages")]
502fn attach_not_found<S>(
503 router: Router<WebServerState<S>>,
504 not_found: Option<super::not_found::NotFound<S>>,
505) -> Router<WebServerState<S>>
506where
507 S: Clone + Send + Sync + 'static,
508{
509 match not_found {
510 Some(not_found) => router.fallback(
511 move |axum::extract::State(state): axum::extract::State<WebServerState<S>>,
512 uri: axum::http::Uri| {
513 let not_found: super::not_found::NotFound<S> = not_found.clone();
514 async move {
515 let data: serde_json::Value = not_found.data(state.clone(), uri).await;
516 state.not_found(data)
517 }
518 },
519 ),
520 None => router.fallback(plain_not_found),
521 }
522}
523
524async fn serve_on<F>(
531 router: Router,
532 host: &str,
533 port: u16,
534 shutdown: Shutdown,
535 on_shutdown: F,
536) -> Result<(), WebServerError>
537where
538 F: Future<Output = ()> + Send,
539{
540 let ip: IpAddr = IpAddr::from_str(host).map_err(|source| WebServerError::Bind {
541 addr: SocketAddr::from(([0, 0, 0, 0], port)),
542 source: std::io::Error::new(std::io::ErrorKind::InvalidInput, source),
543 })?;
544 let address: SocketAddr = SocketAddr::new(ip, port);
545 let listener: TcpListener =
546 TcpListener::bind(address)
547 .await
548 .map_err(|source| WebServerError::Bind {
549 addr: address,
550 source,
551 })?;
552
553 info!("listening on http://{address}");
554
555 let serving = serve(
559 listener,
560 router.into_make_service_with_connect_info::<SocketAddr>(),
561 )
562 .with_graceful_shutdown(shutdown.clone().recv())
563 .into_future();
564 tokio::pin!(serving);
565
566 tokio::select! {
570 result = &mut serving => return result.map_err(WebServerError::Serve),
571 () = shutdown.recv() => {}
572 }
573
574 let (served, cleaned) = tokio::join!(
579 tokio::time::timeout(DEFAULT_DRAIN_TIMEOUT, &mut serving),
580 tokio::time::timeout(DEFAULT_DRAIN_TIMEOUT, on_shutdown),
581 );
582
583 if cleaned.is_err() {
587 error!(
588 "app shutdown hook exceeded {DEFAULT_DRAIN_TIMEOUT:?}; cleanup was cancelled part-way"
589 );
590 }
591
592 match served {
593 Ok(result) => result.map_err(WebServerError::Serve),
594 Err(_elapsed) => {
597 warn!("drain window elapsed after {DEFAULT_DRAIN_TIMEOUT:?}; closing what remained");
598 Ok(())
599 }
600 }
601}
602
603fn apply_cache_policy<S>(
607 router: Router<WebServerState<S>>,
608 cache_buster: &crate::assets::CacheBuster,
609) -> Router<WebServerState<S>>
610where
611 S: Clone + Send + Sync + 'static,
612{
613 let router: Router<WebServerState<S>> = router.layer(axum::middleware::from_fn(
614 crate::assets::CacheBuster::never_cache_middleware,
615 ));
616
617 if cache_buster.is_empty() {
618 return router;
619 }
620
621 router.merge(
622 Router::new()
623 .nest_service(
624 "/static",
625 tower_http::services::ServeDir::new(
626 cache_buster.root().join(crate::assets::STATIC_DIRECTORY),
627 ),
628 )
629 .layer(axum::middleware::from_fn(reject_unservable_static_path))
630 .layer(axum::middleware::from_fn(
631 crate::assets::CacheBuster::forever_cache_middleware,
632 )),
633 )
634}
635
636const MAX_FILE_NAME_BYTES: usize = 255;
638
639fn has_overlong_segment(path: &str) -> bool {
643 path.split('/')
644 .any(|segment: &str| segment.len() > MAX_FILE_NAME_BYTES)
645}
646
647async fn reject_unservable_static_path(
651 request: axum::extract::Request,
652 next: axum::middleware::Next,
653) -> Response {
654 if has_overlong_segment(request.uri().path()) {
655 return plain_not_found_response();
656 }
657 next.run(request).await
658}
659
660async fn health() -> StatusCode {
663 StatusCode::OK
664}
665
666async fn plain_not_found() -> Response {
668 plain_not_found_response()
669}
670
671pub(super) fn plain_not_found_response() -> Response {
673 let mut response: Response = (StatusCode::NOT_FOUND, "404").into_response();
674 crate::assets::mark_never_cached(response.headers_mut());
675 response
676}
677
678#[cfg(feature = "pages")]
685fn well_known_routes<S>(well_known: &super::frontend::WellKnown) -> Router<WebServerState<S>>
686where
687 S: Clone + Send + Sync + 'static,
688{
689 use axum::http::header;
690
691 fn text<S>(
692 router: Router<WebServerState<S>>,
693 path: &str,
694 content_type: &'static str,
695 body: String,
696 ) -> Router<WebServerState<S>>
697 where
698 S: Clone + Send + Sync + 'static,
699 {
700 router.route(
701 path,
702 get(move || {
703 let body: String = body.clone();
704 async move { ([(header::CONTENT_TYPE, content_type)], body) }
705 }),
706 )
707 }
708
709 let mut router: Router<WebServerState<S>> = Router::new();
710 router = text(
711 router,
712 "/robots.txt",
713 "text/plain; charset=utf-8",
714 well_known.robots_txt.clone(),
715 );
716 router = text(
717 router,
718 "/humans.txt",
719 "text/plain; charset=utf-8",
720 well_known.humans_txt.clone(),
721 );
722 router = text(
723 router,
724 "/site.webmanifest",
725 "application/manifest+json",
726 well_known.webmanifest.clone(),
727 );
728 router = text(
729 router,
730 crate::sitemap::SITEMAP_INDEX_PATH,
731 "application/xml",
732 well_known.sitemaps.index().to_string(),
733 );
734 for (index, chunk) in well_known.sitemaps.chunks().iter().enumerate() {
735 router = text(
736 router,
737 &format!("/sitemap-{}.xml", index + 1),
738 "application/xml",
739 chunk.clone(),
740 );
741 }
742 router
743}
744
745#[cfg(feature = "pages")]
751fn icon_routes<S>(
752 cache_buster: &crate::assets::CacheBuster,
753 has_svg_icon: bool,
754) -> Router<WebServerState<S>>
755where
756 S: Clone + Send + Sync + 'static,
757{
758 use tower_http::services::ServeFile;
759
760 let mut icons: Vec<(&str, String)> = vec![
761 (
762 "/favicon.ico",
763 String::from("static/image/favicon/favicon.ico"),
764 ),
765 (
766 "/apple-touch-icon.png",
767 String::from("static/image/favicon/apple-touch-icon.png"),
768 ),
769 (
770 "/icon-192.png",
771 String::from("static/image/favicon/icon-192.png"),
772 ),
773 (
774 "/icon-512.png",
775 String::from("static/image/favicon/icon-512.png"),
776 ),
777 ];
778 if has_svg_icon {
780 icons.push((
781 "/favicon.svg",
782 String::from("static/image/favicon/favicon.svg"),
783 ));
784 }
785
786 let mut router: Router<WebServerState<S>> = Router::new();
787 for (route, original) in icons {
788 router = router.nest_service(route, ServeFile::new(cache_buster.file(&original)));
790 }
791 router
792}
793
794#[cfg(feature = "pages")]
805fn feed_routes<S>(feeds: &crate::feed::FeedSet) -> Router<WebServerState<S>>
806where
807 S: Clone + Send + Sync + 'static,
808{
809 use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
810
811 let last_modified: HeaderValue = HeaderValue::from_str(
815 &feeds
816 .last_modified()
817 .format("%a, %d %b %Y %H:%M:%S GMT")
818 .to_string(),
819 )
820 .unwrap_or_else(|_| HeaderValue::from_static(""));
821 let cache_control: HeaderValue = HeaderValue::from_str(&format!(
822 "public, max-age={}",
823 crate::feed::FEED_MAX_AGE_SECONDS
824 ))
825 .unwrap_or_else(|_| HeaderValue::from_static("public"));
826
827 let mut router: Router<WebServerState<S>> = Router::new();
828 for document in feeds.documents() {
829 let body: String = String::from(document.body());
830 let etag_text: String = String::from(document.etag());
831 let etag: HeaderValue =
832 HeaderValue::from_str(&etag_text).unwrap_or_else(|_| HeaderValue::from_static(""));
833 let content_type: HeaderValue = HeaderValue::from_static(document.content_type());
834 let last_modified: HeaderValue = last_modified.clone();
835 let cache_control: HeaderValue = cache_control.clone();
836
837 router = router.route(
838 document.path(),
839 get(move |headers: HeaderMap| {
840 let body: String = body.clone();
841 let etag_text: String = etag_text.clone();
842 let etag: HeaderValue = etag.clone();
843 let content_type: HeaderValue = content_type.clone();
844 let last_modified: HeaderValue = last_modified.clone();
845 let cache_control: HeaderValue = cache_control.clone();
846 async move {
847 let fresh: bool = if_none_match(&headers, &etag_text);
848
849 let mut response: Response = if fresh {
854 StatusCode::NOT_MODIFIED.into_response()
855 } else {
856 (StatusCode::OK, body).into_response()
857 };
858
859 let headers: &mut HeaderMap = response.headers_mut();
860 headers.insert(header::CACHE_CONTROL, cache_control);
861 headers.insert(header::ETAG, etag);
862 headers.insert(header::LAST_MODIFIED, last_modified);
863 if !fresh {
864 headers.insert(header::CONTENT_TYPE, content_type);
865 }
866
867 response
868 }
869 }),
870 );
871 }
872
873 router
874}
875
876#[cfg(feature = "pages")]
882fn if_none_match(headers: &axum::http::HeaderMap, etag: &str) -> bool {
883 let Some(header) = headers
884 .get(axum::http::header::IF_NONE_MATCH)
885 .and_then(|value| value.to_str().ok())
886 else {
887 return false;
888 };
889
890 header.split(',').any(|candidate| {
891 let candidate: &str = candidate.trim();
892 candidate == "*" || candidate.trim_start_matches("W/") == etag
893 })
894}
895
896fn log_immutable_assets(cache_buster: &crate::assets::CacheBuster) {
906 for (original, hashed) in cache_buster.cache() {
907 info!("immutable 1y /{original} -> /{hashed}");
908 }
909}
910
911#[cfg(feature = "pages")]
913fn log_served_documents(well_known: &super::frontend::WellKnown) {
914 for path in ["/robots.txt", "/humans.txt", "/site.webmanifest"] {
915 info!("uncached {path}");
916 }
917 for path in well_known.sitemaps.paths() {
918 info!("uncached {path}");
919 }
920
921 if let Some(feeds) = well_known.feeds.as_ref() {
922 for document in feeds.documents() {
923 info!(
924 "cached {}m {} (etag {})",
925 crate::feed::FEED_MAX_AGE_SECONDS / 60,
926 document.path(),
927 document.etag()
928 );
929 }
930 }
931}
932
933#[cfg(feature = "pages")]
939struct AssembledFrontend<S> {
940 routes: Router<WebServerState<S>>,
942 api: Router<WebServerState<S>>,
944 proxy_scripts: Router<WebServerState<S>>,
946 feeds: Option<Router<WebServerState<S>>>,
948 runtime: crate::templates::FrontendRuntime,
949 base: crate::templates::BaseTemplateData,
950 templates: crate::templates::TemplateRegistry<'static>,
951 not_found: super::not_found::NotFound<S>,
952}
953
954#[cfg(feature = "pages")]
956fn assemble_frontend<S>(
957 mut params: super::frontend::FrontendParams<S>,
958 feed: Option<crate::feed::Feed>,
959 cache_buster: &crate::assets::CacheBuster,
960 environment: Environment,
961) -> Result<AssembledFrontend<S>, WebServerError>
962where
963 S: Clone + Send + Sync + 'static,
964{
965 let mut templates: crate::templates::TemplateRegistry<'static> =
966 crate::templates::TemplateRegistry::from_dir(
967 cache_buster.root().join(crate::templates::TEMPLATE_ROOT),
968 )?;
969 for (name, helper) in std::mem::take(&mut params.helpers) {
970 templates.register_project_helper(&name, helper)?;
971 }
972
973 let built: super::frontend::Frontend<S> =
974 super::frontend::Frontend::build(params, feed, cache_buster, environment)?;
975
976 log_served_documents(&built.well_known);
977
978 let feeds: Option<Router<WebServerState<S>>> = built.well_known.feeds.as_ref().map(feed_routes);
982
983 let mut routes: Router<WebServerState<S>> = well_known_routes(&built.well_known);
984 routes = routes.merge(icon_routes(cache_buster, built.has_svg_icon));
985
986 let (proxy_scripts, api) = proxy_routes(&built);
990
991 routes = routes.merge(built.pages.into_router()?);
992
993 Ok(AssembledFrontend {
994 routes,
995 api,
996 proxy_scripts,
997 feeds,
998 runtime: built.runtime,
999 base: built.base,
1000 templates,
1001 not_found: built.not_found,
1002 })
1003}
1004
1005#[cfg(feature = "pages")]
1011fn proxy_routes<S>(
1012 frontend: &super::frontend::Frontend<S>,
1013) -> (Router<WebServerState<S>>, Router<WebServerState<S>>)
1014where
1015 S: Clone + Send + Sync + 'static,
1016{
1017 use crate::analytics::{AnalyticsConfig, ScriptRelay, relay_envelope, relay_event};
1018 use axum::body::Bytes;
1019 use axum::extract::ConnectInfo;
1020 use axum::http::HeaderMap;
1021 use axum::routing::post;
1022
1023 let client: reqwest::Client = reqwest::Client::new();
1024 let paths: &crate::templates::FrontendRuntime = &frontend.runtime;
1025
1026 let analytics_event_upstream: String = AnalyticsConfig::upstream_event_url();
1027 let sentry_envelope_upstream: String = frontend.sentry_dsn.upstream_envelope_url();
1028
1029 let script_route = |relay: ScriptRelay| {
1030 get(move |headers: HeaderMap| {
1031 let relay: ScriptRelay = relay.clone();
1032 async move { relay.respond(&headers).await }
1033 })
1034 };
1035 let mut scripts: Router<WebServerState<S>> = Router::new();
1036 if let (Some(analytics_paths), Some(upstream)) = (
1039 paths.analytics.as_ref(),
1040 frontend.analytics.upstream_script_url_if_enabled(),
1041 ) {
1042 scripts = scripts.route(
1043 &analytics_paths.script_path,
1044 script_route(ScriptRelay::new(client.clone(), upstream)),
1045 );
1046 }
1047 let scripts: Router<WebServerState<S>> = scripts.route(
1048 &paths.sentry_browser.script_path,
1049 script_route(ScriptRelay::new(
1050 client.clone(),
1051 frontend.sentry_dsn.upstream_script_url(),
1052 )),
1053 );
1054
1055 let tunnel_path: String = strip_api_prefix(&paths.sentry_browser.tunnel_path);
1057
1058 let mut endpoints: Router<WebServerState<S>> = Router::new();
1059 if let Some(analytics_paths) = paths
1060 .analytics
1061 .as_ref()
1062 .filter(|_| frontend.analytics.is_enabled())
1063 {
1064 let event_path: String = strip_api_prefix(&analytics_paths.event_path);
1065 endpoints = endpoints.route(
1066 &event_path,
1067 post({
1068 let client: reqwest::Client = client.clone();
1069 let upstream: std::sync::Arc<str> =
1070 std::sync::Arc::from(analytics_event_upstream.as_str());
1071 move |ConnectInfo(peer): ConnectInfo<SocketAddr>,
1072 headers: HeaderMap,
1073 body: Bytes| {
1074 let client: reqwest::Client = client.clone();
1075 let upstream: std::sync::Arc<str> = std::sync::Arc::clone(&upstream);
1076 async move { relay_event(&client, &upstream, &headers, peer, body).await }
1077 }
1078 }),
1079 );
1080 }
1081 let endpoints: Router<WebServerState<S>> = endpoints.route(
1082 &tunnel_path,
1083 post({
1084 let upstream: std::sync::Arc<str> =
1085 std::sync::Arc::from(sentry_envelope_upstream.as_str());
1086 move |body: Bytes| {
1087 let client: reqwest::Client = client.clone();
1088 let upstream: std::sync::Arc<str> = std::sync::Arc::clone(&upstream);
1089 async move { relay_envelope(&client, &upstream, body).await }
1090 }
1091 }),
1092 );
1093
1094 (scripts, endpoints)
1095}
1096
1097#[cfg(feature = "pages")]
1100fn strip_api_prefix(path: &str) -> String {
1101 path.strip_prefix(API_PREFIX)
1102 .map_or_else(|| path.to_string(), String::from)
1103}
1104
1105#[cfg(test)]
1106mod tests {
1107
1108 mod static_paths {
1109 use crate::webserver::server::has_overlong_segment;
1110
1111 #[test]
1112 fn a_hashed_asset_name_is_servable() {
1113 let expected: bool = false;
1114 let actual: bool = has_overlong_segment("/css/main.0123456789abcdef.css");
1115 assert_eq!(expected, actual);
1116 }
1117
1118 #[test]
1119 fn a_segment_at_the_file_name_limit_is_still_tried() {
1120 let expected: bool = false;
1121 let actual: bool = has_overlong_segment(&format!("/js/{}", "a".repeat(255)));
1122 assert_eq!(expected, actual);
1123 }
1124
1125 #[test]
1126 fn a_segment_past_the_file_name_limit_is_a_404() {
1127 let expected: bool = true;
1128 let actual: bool = has_overlong_segment(&format!("/js/{}", "a".repeat(256)));
1129 assert_eq!(expected, actual);
1130 }
1131 }
1132
1133 #[cfg(feature = "pages")]
1134 mod conditional_get {
1135 use axum::http::{HeaderMap, HeaderValue, header};
1136
1137 use crate::webserver::server::if_none_match;
1138
1139 const ETAG: &str = "\"abc123\"";
1140
1141 fn headers(value: &str) -> HeaderMap {
1142 let mut headers: HeaderMap = HeaderMap::new();
1143 headers.insert(
1144 header::IF_NONE_MATCH,
1145 HeaderValue::from_str(value).expect("a valid header"),
1146 );
1147 headers
1148 }
1149
1150 #[test]
1151 fn a_request_without_the_header_always_gets_the_body() {
1152 let expected: bool = false;
1153 let actual: bool = if_none_match(&HeaderMap::new(), ETAG);
1154 assert_eq!(expected, actual);
1155 }
1156
1157 #[test]
1158 fn the_same_validator_means_the_reader_already_has_this_feed() {
1159 let expected: bool = true;
1160 let actual: bool = if_none_match(&headers(ETAG), ETAG);
1161 assert_eq!(expected, actual);
1162 }
1163
1164 #[test]
1165 fn a_weak_validator_still_matches_because_feeds_need_no_byte_equality() {
1166 let expected: bool = true;
1167 let actual: bool = if_none_match(&headers("W/\"abc123\""), ETAG);
1168 assert_eq!(expected, actual);
1169 }
1170
1171 #[test]
1172 fn a_star_matches_anything_that_exists() {
1173 let expected: bool = true;
1174 let actual: bool = if_none_match(&headers("*"), ETAG);
1175 assert_eq!(expected, actual);
1176 }
1177
1178 #[test]
1179 fn one_match_anywhere_in_the_list_is_enough() {
1180 let expected: bool = true;
1184 let actual: bool = if_none_match(&headers("\"other\", \"abc123\""), ETAG);
1185 assert_eq!(expected, actual);
1186 }
1187
1188 #[test]
1189 fn a_stale_validator_gets_the_new_document() {
1190 let expected: bool = false;
1191 let actual: bool = if_none_match(&headers("\"stale\""), ETAG);
1192 assert_eq!(expected, actual);
1193 }
1194 }
1195 use std::sync::Arc;
1196 use std::sync::atomic::{AtomicBool, Ordering};
1197 use std::time::Duration;
1198
1199 use axum::Router;
1200 use axum::routing::get;
1201 use tokio::time::timeout;
1202
1203 use super::super::shutdown::Shutdown;
1204 use super::{
1205 API_PREFIX, AppShutdown, DEFAULT_BODY_LIMIT, DEFAULT_DRAIN_TIMEOUT, WebServerError, health,
1206 serve_on,
1207 };
1208
1209 #[derive(Clone)]
1212 struct RecordingState {
1213 ran: Arc<AtomicBool>,
1214 linger: Option<Duration>,
1215 }
1216
1217 impl RecordingState {
1218 fn instant() -> Self {
1219 Self {
1220 ran: Arc::new(AtomicBool::new(false)),
1221 linger: None,
1222 }
1223 }
1224 }
1225
1226 impl AppShutdown for RecordingState {
1227 async fn on_shutdown(&self) {
1228 if let Some(linger) = self.linger {
1229 tokio::time::sleep(linger).await;
1230 }
1231 self.ran.store(true, Ordering::SeqCst);
1232 }
1233 }
1234
1235 async fn serve_until_shutdown(
1237 state: RecordingState,
1238 shutdown: Shutdown,
1239 ) -> Result<(), WebServerError> {
1240 let router: Router = Router::new().route("/health", get(health));
1241 let cleanup: RecordingState = state.clone();
1242 serve_on(router, "127.0.0.1", 0, shutdown, async move {
1244 cleanup.on_shutdown().await;
1245 })
1246 .await
1247 }
1248
1249 #[tokio::test]
1250 async fn app_cleanup_runs_when_the_shutdown_signal_arrives() {
1251 let shutdown: Shutdown = Shutdown::manual();
1252 let state: RecordingState = RecordingState::instant();
1253 let ran: Arc<AtomicBool> = Arc::clone(&state.ran);
1254
1255 shutdown.trigger();
1256 timeout(
1257 Duration::from_secs(1),
1258 serve_until_shutdown(state, shutdown.clone()),
1259 )
1260 .await
1261 .expect("serving ended promptly")
1262 .expect("serving ended cleanly");
1263
1264 let expected: bool = true;
1265 let actual: bool = ran.load(Ordering::SeqCst);
1266 assert_eq!(expected, actual);
1267 }
1268
1269 #[tokio::test]
1270 async fn app_cleanup_never_runs_when_the_server_dies_before_any_signal() {
1271 let shutdown: Shutdown = Shutdown::manual();
1275 let state: RecordingState = RecordingState::instant();
1276 let ran: Arc<AtomicBool> = Arc::clone(&state.ran);
1277 let cleanup: RecordingState = state.clone();
1278
1279 let router: Router = Router::new().route("/health", get(health));
1280 let result: Result<(), WebServerError> = timeout(
1281 Duration::from_secs(1),
1282 serve_on(router, "not-an-ip", 0, shutdown, async move {
1283 cleanup.on_shutdown().await;
1284 }),
1285 )
1286 .await
1287 .expect("a bind failure returns immediately, it does not wait for cleanup");
1288
1289 assert!(result.is_err(), "an unparseable host is a bind error");
1290
1291 let expected: bool = false;
1292 let actual: bool = ran.load(Ordering::SeqCst);
1293 assert_eq!(expected, actual);
1294 }
1295
1296 #[tokio::test(start_paused = true)]
1297 async fn a_cleanup_that_overruns_the_window_is_cancelled_rather_than_awaited() {
1298 let shutdown: Shutdown = Shutdown::manual();
1302 let state: RecordingState = RecordingState {
1303 ran: Arc::new(AtomicBool::new(false)),
1304 linger: Some(DEFAULT_DRAIN_TIMEOUT * 2),
1305 };
1306 let ran: Arc<AtomicBool> = Arc::clone(&state.ran);
1307
1308 shutdown.trigger();
1309 serve_until_shutdown(state, shutdown.clone())
1310 .await
1311 .expect("serving still ends cleanly when cleanup is cancelled");
1312
1313 let expected: bool = false;
1314 let actual: bool = ran.load(Ordering::SeqCst);
1315 assert_eq!(
1316 expected, actual,
1317 "the hook was cancelled at its await, so it never reached its final store"
1318 );
1319 }
1320
1321 #[tokio::test]
1322 async fn a_server_with_nothing_in_flight_stops_at_once_instead_of_waiting_out_the_window() {
1323 let shutdown: Shutdown = Shutdown::manual();
1324 let router: Router = Router::new().route("/health", get(health));
1325
1326 let serving: tokio::task::JoinHandle<Result<(), WebServerError>> = tokio::spawn({
1328 let shutdown: Shutdown = shutdown.clone();
1329 async move { serve_on(router, "127.0.0.1", 0, shutdown, async {}).await }
1330 });
1331
1332 shutdown.trigger();
1333
1334 timeout(Duration::from_secs(1), serving)
1337 .await
1338 .expect("the server returned as soon as the drain began")
1339 .expect("the serving task did not panic")
1340 .expect("serving ended cleanly");
1341 }
1342
1343 #[test]
1344 fn the_body_limit_accommodates_an_ordinary_form_post() {
1345 let expected: usize = 256 * 1024;
1348 let actual: usize = DEFAULT_BODY_LIMIT;
1349 assert_eq!(expected, actual);
1350 }
1351
1352 #[cfg(feature = "pages")]
1353 #[test]
1354 fn stripping_the_prefix_leaves_a_nestable_path() {
1355 let expected: String = String::from("/boggledygook-a3f2c1d8");
1356 let actual: String = super::strip_api_prefix("/api/v1/boggledygook-a3f2c1d8");
1357 assert_eq!(expected, actual);
1358 }
1359
1360 #[test]
1361 fn the_api_prefix_is_the_one_every_project_shares() {
1362 assert_eq!("/api/v1", API_PREFIX);
1363 }
1364}