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::LatencyUnit;
15use tower_http::trace::{DefaultMakeSpan, DefaultOnResponse, TraceLayer};
16use tracing::{Level, error, info, instrument, warn};
17
18use crate::env;
19use crate::environment::Environment;
20
21use super::error::WebServerError;
22use super::shutdown::{AppShutdown, DEFAULT_DRAIN_TIMEOUT, Shutdown};
23use super::state::{StateParts, WebServerState};
24
25pub const ENV_HOST: &str = "WSB_HOST";
27
28pub const ENV_PORT: &str = "WSB_PORT";
30
31pub const DEFAULT_PORT: u16 = 8080;
33
34pub const DEFAULT_BODY_LIMIT: usize = 256 * 1024;
39
40pub const API_PREFIX: &str = "/api/v1";
46
47pub struct WebServer<S = ()> {
54 host: String,
55 port: u16,
56 environment: Environment,
57 app: S,
58
59 body_limit: usize,
60 root_dir: PathBuf,
61 router: Router<WebServerState<S>>,
62
63 #[cfg(feature = "pages")]
64 frontend: Option<super::frontend::FrontendParams<S>>,
65
66 #[cfg(feature = "pages")]
69 feed: Option<crate::feed::Feed>,
70}
71
72impl WebServer<()> {
73 #[must_use]
75 pub fn new(host: impl Into<String>, port: u16, environment: Environment) -> Self {
76 Self::with_state(host, port, environment, ())
77 }
78
79 pub fn from_env() -> Result<Self, WebServerError> {
89 Self::from_env_with_state(())
90 }
91}
92
93impl<S> WebServer<S>
94where
95 S: Clone + Send + Sync + 'static,
96{
97 #[must_use]
99 pub fn with_state(
100 host: impl Into<String>,
101 port: u16,
102 environment: Environment,
103 app: S,
104 ) -> Self {
105 Self {
106 host: host.into(),
107 port,
108 environment,
109 app,
110 body_limit: DEFAULT_BODY_LIMIT,
111 root_dir: PathBuf::new(),
113 router: Router::new(),
114 #[cfg(feature = "pages")]
115 frontend: None,
116 #[cfg(feature = "pages")]
117 feed: None,
118 }
119 }
120
121 pub fn from_env_with_state(app: S) -> Result<Self, WebServerError> {
128 let environment: Environment = Environment::from_env()?;
129 let host: String = env::optional(ENV_HOST).unwrap_or_else(|| {
130 if environment.is_production() {
131 String::from("0.0.0.0")
132 } else {
133 String::from("127.0.0.1")
134 }
135 });
136 let port: u16 =
137 env::parse_or(ENV_PORT, "port number", DEFAULT_PORT).map_err(WebServerError::Env)?;
138
139 Ok(Self::with_state(host, port, environment, app))
140 }
141
142 #[must_use]
147 pub const fn body_limit(mut self, body_limit: usize) -> Self {
148 self.body_limit = body_limit;
149 self
150 }
151
152 #[must_use]
160 pub fn root_dir(mut self, root_dir: impl Into<PathBuf>) -> Self {
161 self.root_dir = root_dir.into();
162 self
163 }
164
165 #[must_use]
167 pub fn nest(mut self, path: &str, router: Router<WebServerState<S>>) -> Self {
168 self.router = self.router.nest(path, router);
169 self
170 }
171
172 #[must_use]
174 pub fn merge(mut self, router: Router<WebServerState<S>>) -> Self {
175 self.router = self.router.merge(router);
176 self
177 }
178
179 #[must_use]
181 pub fn nest_service<T>(mut self, path: &str, service: T) -> Self
182 where
183 T: tower::Service<axum::extract::Request, Error = std::convert::Infallible>
184 + Clone
185 + Send
186 + Sync
187 + 'static,
188 T::Response: axum::response::IntoResponse,
189 T::Future: Send + 'static,
190 {
191 self.router = self.router.nest_service(path, service);
192 self
193 }
194
195 #[cfg(feature = "pages")]
202 #[must_use]
203 pub fn frontend(mut self, params: super::frontend::FrontendParams<S>) -> Self {
204 self.frontend = Some(params);
205 self
206 }
207
208 #[cfg(feature = "pages")]
221 #[must_use]
222 pub fn feed(mut self, feed: crate::feed::Feed) -> Self {
223 self.feed = Some(feed);
224 self
225 }
226
227 pub fn into_router(self, shutdown: Shutdown) -> Result<Router, WebServerError> {
243 Ok(self.assemble(shutdown)?.router)
244 }
245
246 #[instrument(skip_all)]
253 pub async fn run(self, shutdown: Shutdown) -> Result<(), WebServerError>
254 where
255 S: AppShutdown,
256 {
257 let Assembled {
258 router,
259 state,
260 host,
261 port,
262 } = self.assemble(shutdown.clone())?;
263
264 serve_on(router, &host, port, shutdown, async move {
265 state.app().on_shutdown().await;
266 })
267 .await
268 }
269
270 #[instrument(skip_all)]
275 #[cfg_attr(
276 not(feature = "pages"),
277 expect(unused_mut, reason = "only a frontend merges routes into the router")
278 )]
279 fn assemble(self, shutdown: Shutdown) -> Result<Assembled<S>, WebServerError> {
280 let Self {
281 host,
282 port,
283 environment,
284 app,
285 body_limit,
286 root_dir,
287 router,
288 #[cfg(feature = "pages")]
289 frontend,
290 #[cfg(feature = "pages")]
291 feed,
292 } = self;
293
294 #[cfg(feature = "pages")]
297 if feed.is_some() && frontend.is_none() {
298 return Err(WebServerError::FeedWithoutFrontend);
299 }
300
301 let cache_buster: crate::assets::CacheBuster =
304 crate::assets::CacheBuster::load_in(&root_dir)?;
305
306 let mut no_cache: Router<WebServerState<S>> = router;
307 let mut built_in: Router<WebServerState<S>> = Router::new().route("/health", get(health));
308
309 #[cfg(feature = "pages")]
310 let mut frontend_runtime: Option<crate::templates::FrontendRuntime> = None;
311 #[cfg(feature = "pages")]
312 let mut base: Option<crate::templates::BaseTemplateData> = None;
313 #[cfg(feature = "pages")]
314 let mut templates: Option<crate::templates::TemplateRegistry<'static>> = None;
315 #[cfg(feature = "pages")]
316 let mut not_found: Option<super::not_found::NotFound<S>> = None;
317 #[cfg(feature = "pages")]
318 let mut proxy_scripts: Option<Router<WebServerState<S>>> = None;
319 #[cfg(feature = "pages")]
320 let mut feed_router: Option<Router<WebServerState<S>>> = None;
321
322 log_immutable_assets(&cache_buster);
323
324 #[cfg(feature = "pages")]
325 if let Some(params) = frontend {
326 let assembled: AssembledFrontend<S> =
327 assemble_frontend(params, feed, &cache_buster, environment)?;
328
329 no_cache = no_cache.merge(assembled.routes);
330 built_in = built_in.merge(assembled.api);
331 proxy_scripts = Some(assembled.proxy_scripts);
332 feed_router = assembled.feeds;
333 not_found = Some(assembled.not_found);
334 frontend_runtime = Some(assembled.runtime);
335 base = Some(assembled.base);
336 templates = Some(assembled.templates);
337 }
338
339 let no_cache: Router<WebServerState<S>> = no_cache.nest(API_PREFIX, built_in);
340
341 let mut app_router: Router<WebServerState<S>> = apply_cache_policy(no_cache, &cache_buster);
342
343 #[cfg(feature = "pages")]
347 if let Some(scripts) = proxy_scripts {
348 app_router = app_router.merge(scripts);
349 }
350
351 #[cfg(feature = "pages")]
352 if let Some(feeds) = feed_router {
353 app_router = app_router.merge(feeds);
354 }
355
356 #[cfg(feature = "pages")]
357 let app_router: Router<WebServerState<S>> = attach_not_found(app_router, not_found);
358 #[cfg(not(feature = "pages"))]
359 let app_router: Router<WebServerState<S>> = app_router.fallback(plain_not_found);
360
361 let state: WebServerState<S> = WebServerState::new(StateParts {
362 host: host.clone(),
363 port,
364 environment,
365 shutdown,
366 #[cfg(feature = "templates")]
367 base,
368 #[cfg(feature = "templates")]
369 templates,
370 cache_buster: Some(cache_buster),
371 #[cfg(feature = "templates")]
372 frontend: frontend_runtime,
373 app,
374 });
375
376 let app_router: Router = app_router
381 .with_state(state.clone())
382 .layer(
383 TraceLayer::new_for_http()
384 .make_span_with(
390 DefaultMakeSpan::new()
391 .level(Level::INFO)
392 .include_headers(false),
393 )
394 .on_response(
395 DefaultOnResponse::new()
396 .level(Level::INFO)
397 .latency_unit(LatencyUnit::Millis),
398 ),
399 )
400 .layer(DefaultBodyLimit::max(body_limit));
401
402 Ok(Assembled {
403 router: app_router,
404 state,
405 host,
406 port,
407 })
408 }
409}
410
411struct Assembled<S> {
414 router: Router,
415 state: WebServerState<S>,
418 host: String,
419 port: u16,
420}
421
422#[cfg(feature = "pages")]
429fn attach_not_found<S>(
430 router: Router<WebServerState<S>>,
431 not_found: Option<super::not_found::NotFound<S>>,
432) -> Router<WebServerState<S>>
433where
434 S: Clone + Send + Sync + 'static,
435{
436 match not_found {
437 Some(not_found) => router.fallback(
438 move |axum::extract::State(state): axum::extract::State<WebServerState<S>>,
439 uri: axum::http::Uri| {
440 let not_found: super::not_found::NotFound<S> = not_found.clone();
441 async move {
442 let data: serde_json::Value = not_found.data(state.clone(), uri).await;
443 state.not_found(data)
444 }
445 },
446 ),
447 None => router.fallback(plain_not_found),
448 }
449}
450
451async fn serve_on<F>(
458 router: Router,
459 host: &str,
460 port: u16,
461 shutdown: Shutdown,
462 on_shutdown: F,
463) -> Result<(), WebServerError>
464where
465 F: Future<Output = ()> + Send,
466{
467 let ip: IpAddr = IpAddr::from_str(host).map_err(|source| WebServerError::Bind {
468 addr: SocketAddr::from(([0, 0, 0, 0], port)),
469 source: std::io::Error::new(std::io::ErrorKind::InvalidInput, source),
470 })?;
471 let address: SocketAddr = SocketAddr::new(ip, port);
472 let listener: TcpListener =
473 TcpListener::bind(address)
474 .await
475 .map_err(|source| WebServerError::Bind {
476 addr: address,
477 source,
478 })?;
479
480 info!("listening on http://{address}");
481
482 let serving = serve(
486 listener,
487 router.into_make_service_with_connect_info::<SocketAddr>(),
488 )
489 .with_graceful_shutdown(shutdown.clone().recv())
490 .into_future();
491 tokio::pin!(serving);
492
493 tokio::select! {
497 result = &mut serving => return result.map_err(WebServerError::Serve),
498 () = shutdown.recv() => {}
499 }
500
501 let (served, cleaned) = tokio::join!(
506 tokio::time::timeout(DEFAULT_DRAIN_TIMEOUT, &mut serving),
507 tokio::time::timeout(DEFAULT_DRAIN_TIMEOUT, on_shutdown),
508 );
509
510 if cleaned.is_err() {
514 error!(
515 "app shutdown hook exceeded {DEFAULT_DRAIN_TIMEOUT:?}; cleanup was cancelled part-way"
516 );
517 }
518
519 match served {
520 Ok(result) => result.map_err(WebServerError::Serve),
521 Err(_elapsed) => {
524 warn!("drain window elapsed after {DEFAULT_DRAIN_TIMEOUT:?}; closing what remained");
525 Ok(())
526 }
527 }
528}
529
530fn apply_cache_policy<S>(
533 router: Router<WebServerState<S>>,
534 cache_buster: &crate::assets::CacheBuster,
535) -> Router<WebServerState<S>>
536where
537 S: Clone + Send + Sync + 'static,
538{
539 let router: Router<WebServerState<S>> = router.layer(axum::middleware::from_fn(
540 crate::assets::CacheBuster::never_cache_middleware,
541 ));
542
543 if cache_buster.is_empty() {
544 return router;
545 }
546
547 router.merge(
548 Router::new()
549 .nest_service(
550 "/static",
551 tower_http::services::ServeDir::new(
552 cache_buster.root().join(crate::assets::STATIC_DIRECTORY),
553 ),
554 )
555 .layer(axum::middleware::from_fn(
556 crate::assets::CacheBuster::forever_cache_middleware,
557 )),
558 )
559}
560
561async fn health() -> StatusCode {
564 StatusCode::OK
565}
566
567async fn plain_not_found() -> Response {
569 plain_not_found_response()
570}
571
572pub(super) fn plain_not_found_response() -> Response {
574 let mut response: Response = (StatusCode::NOT_FOUND, "404").into_response();
575 crate::assets::mark_never_cached(response.headers_mut());
576 response
577}
578
579#[cfg(feature = "pages")]
586fn well_known_routes<S>(well_known: &super::frontend::WellKnown) -> Router<WebServerState<S>>
587where
588 S: Clone + Send + Sync + 'static,
589{
590 use axum::http::header;
591
592 fn text<S>(
593 router: Router<WebServerState<S>>,
594 path: &str,
595 content_type: &'static str,
596 body: String,
597 ) -> Router<WebServerState<S>>
598 where
599 S: Clone + Send + Sync + 'static,
600 {
601 router.route(
602 path,
603 get(move || {
604 let body: String = body.clone();
605 async move { ([(header::CONTENT_TYPE, content_type)], body) }
606 }),
607 )
608 }
609
610 let mut router: Router<WebServerState<S>> = Router::new();
611 router = text(
612 router,
613 "/robots.txt",
614 "text/plain; charset=utf-8",
615 well_known.robots_txt.clone(),
616 );
617 router = text(
618 router,
619 "/humans.txt",
620 "text/plain; charset=utf-8",
621 well_known.humans_txt.clone(),
622 );
623 router = text(
624 router,
625 "/site.webmanifest",
626 "application/manifest+json",
627 well_known.webmanifest.clone(),
628 );
629 router = text(
630 router,
631 crate::sitemap::SITEMAP_INDEX_PATH,
632 "application/xml",
633 well_known.sitemaps.index().to_string(),
634 );
635 for (index, chunk) in well_known.sitemaps.chunks().iter().enumerate() {
636 router = text(
637 router,
638 &format!("/sitemap-{}.xml", index + 1),
639 "application/xml",
640 chunk.clone(),
641 );
642 }
643 router
644}
645
646#[cfg(feature = "pages")]
652fn icon_routes<S>(
653 cache_buster: &crate::assets::CacheBuster,
654 has_svg_icon: bool,
655) -> Router<WebServerState<S>>
656where
657 S: Clone + Send + Sync + 'static,
658{
659 use tower_http::services::ServeFile;
660
661 let mut icons: Vec<(&str, String)> = vec![
662 (
663 "/favicon.ico",
664 String::from("static/image/favicon/favicon.ico"),
665 ),
666 (
667 "/apple-touch-icon.png",
668 String::from("static/image/favicon/apple-touch-icon.png"),
669 ),
670 (
671 "/icon-192.png",
672 String::from("static/image/favicon/icon-192.png"),
673 ),
674 (
675 "/icon-512.png",
676 String::from("static/image/favicon/icon-512.png"),
677 ),
678 ];
679 if has_svg_icon {
681 icons.push((
682 "/favicon.svg",
683 String::from("static/image/favicon/favicon.svg"),
684 ));
685 }
686
687 let mut router: Router<WebServerState<S>> = Router::new();
688 for (route, original) in icons {
689 router = router.nest_service(route, ServeFile::new(cache_buster.file(&original)));
691 }
692 router
693}
694
695#[cfg(feature = "pages")]
706fn feed_routes<S>(feeds: &crate::feed::FeedSet) -> Router<WebServerState<S>>
707where
708 S: Clone + Send + Sync + 'static,
709{
710 use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
711
712 let last_modified: HeaderValue = HeaderValue::from_str(
716 &feeds
717 .last_modified()
718 .format("%a, %d %b %Y %H:%M:%S GMT")
719 .to_string(),
720 )
721 .unwrap_or_else(|_| HeaderValue::from_static(""));
722 let cache_control: HeaderValue = HeaderValue::from_str(&format!(
723 "public, max-age={}",
724 crate::feed::FEED_MAX_AGE_SECONDS
725 ))
726 .unwrap_or_else(|_| HeaderValue::from_static("public"));
727
728 let mut router: Router<WebServerState<S>> = Router::new();
729 for document in feeds.documents() {
730 let body: String = String::from(document.body());
731 let etag_text: String = String::from(document.etag());
732 let etag: HeaderValue =
733 HeaderValue::from_str(&etag_text).unwrap_or_else(|_| HeaderValue::from_static(""));
734 let content_type: HeaderValue = HeaderValue::from_static(document.content_type());
735 let last_modified: HeaderValue = last_modified.clone();
736 let cache_control: HeaderValue = cache_control.clone();
737
738 router = router.route(
739 document.path(),
740 get(move |headers: HeaderMap| {
741 let body: String = body.clone();
742 let etag_text: String = etag_text.clone();
743 let etag: HeaderValue = etag.clone();
744 let content_type: HeaderValue = content_type.clone();
745 let last_modified: HeaderValue = last_modified.clone();
746 let cache_control: HeaderValue = cache_control.clone();
747 async move {
748 let fresh: bool = if_none_match(&headers, &etag_text);
749
750 let mut response: Response = if fresh {
755 StatusCode::NOT_MODIFIED.into_response()
756 } else {
757 (StatusCode::OK, body).into_response()
758 };
759
760 let headers: &mut HeaderMap = response.headers_mut();
761 headers.insert(header::CACHE_CONTROL, cache_control);
762 headers.insert(header::ETAG, etag);
763 headers.insert(header::LAST_MODIFIED, last_modified);
764 if !fresh {
765 headers.insert(header::CONTENT_TYPE, content_type);
766 }
767
768 response
769 }
770 }),
771 );
772 }
773
774 router
775}
776
777#[cfg(feature = "pages")]
783fn if_none_match(headers: &axum::http::HeaderMap, etag: &str) -> bool {
784 let Some(header) = headers
785 .get(axum::http::header::IF_NONE_MATCH)
786 .and_then(|value| value.to_str().ok())
787 else {
788 return false;
789 };
790
791 header.split(',').any(|candidate| {
792 let candidate: &str = candidate.trim();
793 candidate == "*" || candidate.trim_start_matches("W/") == etag
794 })
795}
796
797fn log_immutable_assets(cache_buster: &crate::assets::CacheBuster) {
807 for (original, hashed) in cache_buster.cache() {
808 info!("immutable 1y /{original} -> /{hashed}");
809 }
810}
811
812#[cfg(feature = "pages")]
814fn log_served_documents(well_known: &super::frontend::WellKnown) {
815 for path in ["/robots.txt", "/humans.txt", "/site.webmanifest"] {
816 info!("uncached {path}");
817 }
818 for path in well_known.sitemaps.paths() {
819 info!("uncached {path}");
820 }
821
822 if let Some(feeds) = well_known.feeds.as_ref() {
823 for document in feeds.documents() {
824 info!(
825 "cached {}m {} (etag {})",
826 crate::feed::FEED_MAX_AGE_SECONDS / 60,
827 document.path(),
828 document.etag()
829 );
830 }
831 }
832}
833
834#[cfg(feature = "pages")]
840struct AssembledFrontend<S> {
841 routes: Router<WebServerState<S>>,
843 api: Router<WebServerState<S>>,
845 proxy_scripts: Router<WebServerState<S>>,
847 feeds: Option<Router<WebServerState<S>>>,
849 runtime: crate::templates::FrontendRuntime,
850 base: crate::templates::BaseTemplateData,
851 templates: crate::templates::TemplateRegistry<'static>,
852 not_found: super::not_found::NotFound<S>,
853}
854
855#[cfg(feature = "pages")]
857fn assemble_frontend<S>(
858 mut params: super::frontend::FrontendParams<S>,
859 feed: Option<crate::feed::Feed>,
860 cache_buster: &crate::assets::CacheBuster,
861 environment: Environment,
862) -> Result<AssembledFrontend<S>, WebServerError>
863where
864 S: Clone + Send + Sync + 'static,
865{
866 let mut templates: crate::templates::TemplateRegistry<'static> =
867 crate::templates::TemplateRegistry::from_dir(
868 cache_buster.root().join(crate::templates::TEMPLATE_ROOT),
869 )?;
870 for (name, helper) in std::mem::take(&mut params.helpers) {
871 templates.register_project_helper(&name, helper)?;
872 }
873
874 let built: super::frontend::Frontend<S> =
875 super::frontend::Frontend::build(params, feed, cache_buster, environment)?;
876
877 log_served_documents(&built.well_known);
878
879 let feeds: Option<Router<WebServerState<S>>> = built.well_known.feeds.as_ref().map(feed_routes);
883
884 let mut routes: Router<WebServerState<S>> = well_known_routes(&built.well_known);
885 routes = routes.merge(icon_routes(cache_buster, built.has_svg_icon));
886
887 let (proxy_scripts, api) = proxy_routes(&built);
891
892 routes = routes.merge(built.pages.into_router()?);
893
894 Ok(AssembledFrontend {
895 routes,
896 api,
897 proxy_scripts,
898 feeds,
899 runtime: built.runtime,
900 base: built.base,
901 templates,
902 not_found: built.not_found,
903 })
904}
905
906#[cfg(feature = "pages")]
912fn proxy_routes<S>(
913 frontend: &super::frontend::Frontend<S>,
914) -> (Router<WebServerState<S>>, Router<WebServerState<S>>)
915where
916 S: Clone + Send + Sync + 'static,
917{
918 use crate::analytics::{AnalyticsConfig, relay_envelope, relay_event, relay_script};
919 use axum::body::Bytes;
920 use axum::extract::ConnectInfo;
921 use axum::http::HeaderMap;
922 use axum::routing::post;
923
924 let client: reqwest::Client = reqwest::Client::new();
925 let paths: &crate::templates::FrontendRuntime = &frontend.runtime;
926
927 let analytics_script_upstream: String = frontend.analytics.upstream_script_url();
928 let analytics_event_upstream: String = AnalyticsConfig::upstream_event_url();
929 let sentry_script_upstream: String = frontend.sentry_dsn.upstream_script_url();
930 let sentry_envelope_upstream: String = frontend.sentry_dsn.upstream_envelope_url();
931
932 let scripts: Router<WebServerState<S>> = Router::new()
933 .route(
934 &paths.analytics.script_path,
935 get({
936 let client: reqwest::Client = client.clone();
937 let upstream: std::sync::Arc<str> =
938 std::sync::Arc::from(analytics_script_upstream.as_str());
939 move || {
940 let client: reqwest::Client = client.clone();
941 let upstream: std::sync::Arc<str> = std::sync::Arc::clone(&upstream);
942 async move { relay_script(&client, &upstream).await }
943 }
944 }),
945 )
946 .route(
947 &paths.sentry_browser.script_path,
948 get({
949 let client: reqwest::Client = client.clone();
950 let upstream: std::sync::Arc<str> =
951 std::sync::Arc::from(sentry_script_upstream.as_str());
952 move || {
953 let client: reqwest::Client = client.clone();
954 let upstream: std::sync::Arc<str> = std::sync::Arc::clone(&upstream);
955 async move { relay_script(&client, &upstream).await }
956 }
957 }),
958 );
959
960 let event_path: String = strip_api_prefix(&paths.analytics.event_path);
962 let tunnel_path: String = strip_api_prefix(&paths.sentry_browser.tunnel_path);
963
964 let endpoints: Router<WebServerState<S>> = Router::new()
965 .route(
966 &event_path,
967 post({
968 let client: reqwest::Client = client.clone();
969 let upstream: std::sync::Arc<str> =
970 std::sync::Arc::from(analytics_event_upstream.as_str());
971 move |ConnectInfo(peer): ConnectInfo<SocketAddr>,
972 headers: HeaderMap,
973 body: Bytes| {
974 let client: reqwest::Client = client.clone();
975 let upstream: std::sync::Arc<str> = std::sync::Arc::clone(&upstream);
976 async move { relay_event(&client, &upstream, &headers, peer, body).await }
977 }
978 }),
979 )
980 .route(
981 &tunnel_path,
982 post({
983 let upstream: std::sync::Arc<str> =
984 std::sync::Arc::from(sentry_envelope_upstream.as_str());
985 move |body: Bytes| {
986 let client: reqwest::Client = client.clone();
987 let upstream: std::sync::Arc<str> = std::sync::Arc::clone(&upstream);
988 async move { relay_envelope(&client, &upstream, body).await }
989 }
990 }),
991 );
992
993 (scripts, endpoints)
994}
995
996#[cfg(feature = "pages")]
999fn strip_api_prefix(path: &str) -> String {
1000 path.strip_prefix(API_PREFIX)
1001 .map_or_else(|| path.to_string(), String::from)
1002}
1003
1004#[cfg(test)]
1005mod tests {
1006
1007 #[cfg(feature = "pages")]
1008 mod conditional_get {
1009 use axum::http::{HeaderMap, HeaderValue, header};
1010
1011 use crate::webserver::server::if_none_match;
1012
1013 const ETAG: &str = "\"abc123\"";
1014
1015 fn headers(value: &str) -> HeaderMap {
1016 let mut headers: HeaderMap = HeaderMap::new();
1017 headers.insert(
1018 header::IF_NONE_MATCH,
1019 HeaderValue::from_str(value).expect("a valid header"),
1020 );
1021 headers
1022 }
1023
1024 #[test]
1025 fn a_request_without_the_header_always_gets_the_body() {
1026 let expected: bool = false;
1027 let actual: bool = if_none_match(&HeaderMap::new(), ETAG);
1028 assert_eq!(expected, actual);
1029 }
1030
1031 #[test]
1032 fn the_same_validator_means_the_reader_already_has_this_feed() {
1033 let expected: bool = true;
1034 let actual: bool = if_none_match(&headers(ETAG), ETAG);
1035 assert_eq!(expected, actual);
1036 }
1037
1038 #[test]
1039 fn a_weak_validator_still_matches_because_feeds_need_no_byte_equality() {
1040 let expected: bool = true;
1041 let actual: bool = if_none_match(&headers("W/\"abc123\""), ETAG);
1042 assert_eq!(expected, actual);
1043 }
1044
1045 #[test]
1046 fn a_star_matches_anything_that_exists() {
1047 let expected: bool = true;
1048 let actual: bool = if_none_match(&headers("*"), ETAG);
1049 assert_eq!(expected, actual);
1050 }
1051
1052 #[test]
1053 fn one_match_anywhere_in_the_list_is_enough() {
1054 let expected: bool = true;
1058 let actual: bool = if_none_match(&headers("\"other\", \"abc123\""), ETAG);
1059 assert_eq!(expected, actual);
1060 }
1061
1062 #[test]
1063 fn a_stale_validator_gets_the_new_document() {
1064 let expected: bool = false;
1065 let actual: bool = if_none_match(&headers("\"stale\""), ETAG);
1066 assert_eq!(expected, actual);
1067 }
1068 }
1069 use std::sync::Arc;
1070 use std::sync::atomic::{AtomicBool, Ordering};
1071 use std::time::Duration;
1072
1073 use axum::Router;
1074 use axum::routing::get;
1075 use tokio::time::timeout;
1076
1077 use super::super::shutdown::Shutdown;
1078 use super::{
1079 API_PREFIX, AppShutdown, DEFAULT_BODY_LIMIT, DEFAULT_DRAIN_TIMEOUT, WebServerError, health,
1080 serve_on,
1081 };
1082
1083 #[derive(Clone)]
1086 struct RecordingState {
1087 ran: Arc<AtomicBool>,
1088 linger: Option<Duration>,
1089 }
1090
1091 impl RecordingState {
1092 fn instant() -> Self {
1093 Self {
1094 ran: Arc::new(AtomicBool::new(false)),
1095 linger: None,
1096 }
1097 }
1098 }
1099
1100 impl AppShutdown for RecordingState {
1101 async fn on_shutdown(&self) {
1102 if let Some(linger) = self.linger {
1103 tokio::time::sleep(linger).await;
1104 }
1105 self.ran.store(true, Ordering::SeqCst);
1106 }
1107 }
1108
1109 async fn serve_until_shutdown(
1111 state: RecordingState,
1112 shutdown: Shutdown,
1113 ) -> Result<(), WebServerError> {
1114 let router: Router = Router::new().route("/health", get(health));
1115 let cleanup: RecordingState = state.clone();
1116 serve_on(router, "127.0.0.1", 0, shutdown, async move {
1118 cleanup.on_shutdown().await;
1119 })
1120 .await
1121 }
1122
1123 #[tokio::test]
1124 async fn app_cleanup_runs_when_the_shutdown_signal_arrives() {
1125 let shutdown: Shutdown = Shutdown::manual();
1126 let state: RecordingState = RecordingState::instant();
1127 let ran: Arc<AtomicBool> = Arc::clone(&state.ran);
1128
1129 shutdown.trigger();
1130 timeout(
1131 Duration::from_secs(1),
1132 serve_until_shutdown(state, shutdown.clone()),
1133 )
1134 .await
1135 .expect("serving ended promptly")
1136 .expect("serving ended cleanly");
1137
1138 let expected: bool = true;
1139 let actual: bool = ran.load(Ordering::SeqCst);
1140 assert_eq!(expected, actual);
1141 }
1142
1143 #[tokio::test]
1144 async fn app_cleanup_never_runs_when_the_server_dies_before_any_signal() {
1145 let shutdown: Shutdown = Shutdown::manual();
1149 let state: RecordingState = RecordingState::instant();
1150 let ran: Arc<AtomicBool> = Arc::clone(&state.ran);
1151 let cleanup: RecordingState = state.clone();
1152
1153 let router: Router = Router::new().route("/health", get(health));
1154 let result: Result<(), WebServerError> = timeout(
1155 Duration::from_secs(1),
1156 serve_on(router, "not-an-ip", 0, shutdown, async move {
1157 cleanup.on_shutdown().await;
1158 }),
1159 )
1160 .await
1161 .expect("a bind failure returns immediately, it does not wait for cleanup");
1162
1163 assert!(result.is_err(), "an unparseable host is a bind error");
1164
1165 let expected: bool = false;
1166 let actual: bool = ran.load(Ordering::SeqCst);
1167 assert_eq!(expected, actual);
1168 }
1169
1170 #[tokio::test(start_paused = true)]
1171 async fn a_cleanup_that_overruns_the_window_is_cancelled_rather_than_awaited() {
1172 let shutdown: Shutdown = Shutdown::manual();
1176 let state: RecordingState = RecordingState {
1177 ran: Arc::new(AtomicBool::new(false)),
1178 linger: Some(DEFAULT_DRAIN_TIMEOUT * 2),
1179 };
1180 let ran: Arc<AtomicBool> = Arc::clone(&state.ran);
1181
1182 shutdown.trigger();
1183 serve_until_shutdown(state, shutdown.clone())
1184 .await
1185 .expect("serving still ends cleanly when cleanup is cancelled");
1186
1187 let expected: bool = false;
1188 let actual: bool = ran.load(Ordering::SeqCst);
1189 assert_eq!(
1190 expected, actual,
1191 "the hook was cancelled at its await, so it never reached its final store"
1192 );
1193 }
1194
1195 #[tokio::test]
1196 async fn a_server_with_nothing_in_flight_stops_at_once_instead_of_waiting_out_the_window() {
1197 let shutdown: Shutdown = Shutdown::manual();
1198 let router: Router = Router::new().route("/health", get(health));
1199
1200 let serving: tokio::task::JoinHandle<Result<(), WebServerError>> = tokio::spawn({
1202 let shutdown: Shutdown = shutdown.clone();
1203 async move { serve_on(router, "127.0.0.1", 0, shutdown, async {}).await }
1204 });
1205
1206 shutdown.trigger();
1207
1208 timeout(Duration::from_secs(1), serving)
1211 .await
1212 .expect("the server returned as soon as the drain began")
1213 .expect("the serving task did not panic")
1214 .expect("serving ended cleanly");
1215 }
1216
1217 #[test]
1218 fn the_body_limit_accommodates_an_ordinary_form_post() {
1219 let expected: usize = 256 * 1024;
1222 let actual: usize = DEFAULT_BODY_LIMIT;
1223 assert_eq!(expected, actual);
1224 }
1225
1226 #[cfg(feature = "pages")]
1227 #[test]
1228 fn stripping_the_prefix_leaves_a_nestable_path() {
1229 let expected: String = String::from("/boggledygook-a3f2c1d8");
1230 let actual: String = super::strip_api_prefix("/api/v1/boggledygook-a3f2c1d8");
1231 assert_eq!(expected, actual);
1232 }
1233
1234 #[test]
1235 fn the_api_prefix_is_the_one_every_project_shares() {
1236 assert_eq!("/api/v1", API_PREFIX);
1237 }
1238}