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::{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};
24use super::telemetry;
25
26pub const ENV_HOST: &str = "WSB_HOST";
28
29pub const ENV_PORT: &str = "WSB_PORT";
31
32pub const DEFAULT_PORT: u16 = 8080;
34
35pub const DEFAULT_BODY_LIMIT: usize = 256 * 1024;
40
41pub const API_PREFIX: &str = "/api/v1";
47
48pub struct WebServer<S = ()> {
55 host: String,
56 port: u16,
57 environment: Environment,
58 app: S,
59
60 body_limit: usize,
61 root_dir: PathBuf,
62 router: Router<WebServerState<S>>,
63
64 #[cfg(feature = "pages")]
65 frontend: Option<super::frontend::FrontendParams<S>>,
66
67 #[cfg(feature = "pages")]
70 feed: Option<crate::feed::Feed>,
71}
72
73impl WebServer<()> {
74 #[must_use]
76 pub fn new(host: impl Into<String>, port: u16, environment: Environment) -> Self {
77 Self::with_state(host, port, environment, ())
78 }
79
80 pub fn from_env() -> Result<Self, WebServerError> {
90 Self::from_env_with_state(())
91 }
92}
93
94impl<S> WebServer<S>
95where
96 S: Clone + Send + Sync + 'static,
97{
98 #[must_use]
100 pub fn with_state(
101 host: impl Into<String>,
102 port: u16,
103 environment: Environment,
104 app: S,
105 ) -> Self {
106 Self {
107 host: host.into(),
108 port,
109 environment,
110 app,
111 body_limit: DEFAULT_BODY_LIMIT,
112 root_dir: PathBuf::new(),
114 router: Router::new(),
115 #[cfg(feature = "pages")]
116 frontend: None,
117 #[cfg(feature = "pages")]
118 feed: None,
119 }
120 }
121
122 pub fn from_env_with_state(app: S) -> Result<Self, WebServerError> {
129 let environment: Environment = Environment::from_env()?;
130 let host: String = env::optional(ENV_HOST).unwrap_or_else(|| {
131 if environment.is_production() {
132 String::from("0.0.0.0")
133 } else {
134 String::from("127.0.0.1")
135 }
136 });
137 let port: u16 =
138 env::parse_or(ENV_PORT, "port number", DEFAULT_PORT).map_err(WebServerError::Env)?;
139
140 Ok(Self::with_state(host, port, environment, app))
141 }
142
143 #[must_use]
148 pub const fn body_limit(mut self, body_limit: usize) -> Self {
149 self.body_limit = body_limit;
150 self
151 }
152
153 #[must_use]
161 pub fn root_dir(mut self, root_dir: impl Into<PathBuf>) -> Self {
162 self.root_dir = root_dir.into();
163 self
164 }
165
166 #[must_use]
168 pub fn nest(mut self, path: &str, router: Router<WebServerState<S>>) -> Self {
169 self.router = self.router.nest(path, router);
170 self
171 }
172
173 #[must_use]
175 pub fn merge(mut self, router: Router<WebServerState<S>>) -> Self {
176 self.router = self.router.merge(router);
177 self
178 }
179
180 #[must_use]
182 pub fn nest_service<T>(mut self, path: &str, service: T) -> Self
183 where
184 T: tower::Service<axum::extract::Request, Error = std::convert::Infallible>
185 + Clone
186 + Send
187 + Sync
188 + 'static,
189 T::Response: axum::response::IntoResponse,
190 T::Future: Send + 'static,
191 {
192 self.router = self.router.nest_service(path, service);
193 self
194 }
195
196 #[cfg(feature = "pages")]
203 #[must_use]
204 pub fn frontend(mut self, params: super::frontend::FrontendParams<S>) -> Self {
205 self.frontend = Some(params);
206 self
207 }
208
209 #[cfg(feature = "pages")]
222 #[must_use]
223 pub fn feed(mut self, feed: crate::feed::Feed) -> Self {
224 self.feed = Some(feed);
225 self
226 }
227
228 pub fn into_router(self, shutdown: Shutdown) -> Result<Router, WebServerError> {
244 Ok(self.assemble(shutdown)?.router)
245 }
246
247 #[instrument(skip_all)]
254 pub async fn run(self, shutdown: Shutdown) -> Result<(), WebServerError>
255 where
256 S: AppShutdown,
257 {
258 let Assembled {
259 router,
260 state,
261 host,
262 port,
263 environment,
264 } = self.assemble(shutdown.clone())?;
265
266 if environment.is_production() {
267 tokio::spawn(telemetry::serve_metrics(shutdown.clone()));
268 }
269
270 serve_on(router, &host, port, shutdown, async move {
271 state.app().on_shutdown().await;
272 })
273 .await
274 }
275
276 #[instrument(skip_all)]
281 #[cfg_attr(
282 not(feature = "pages"),
283 expect(unused_mut, reason = "only a frontend merges routes into the router")
284 )]
285 fn assemble(self, shutdown: Shutdown) -> Result<Assembled<S>, WebServerError> {
286 let Self {
287 host,
288 port,
289 environment,
290 app,
291 body_limit,
292 root_dir,
293 router,
294 #[cfg(feature = "pages")]
295 frontend,
296 #[cfg(feature = "pages")]
297 feed,
298 } = self;
299
300 #[cfg(feature = "pages")]
303 if feed.is_some() && frontend.is_none() {
304 return Err(WebServerError::FeedWithoutFrontend);
305 }
306
307 let cache_buster: crate::assets::CacheBuster =
310 crate::assets::CacheBuster::load_in(&root_dir)?;
311
312 let mut no_cache: Router<WebServerState<S>> = router;
313 let mut built_in: Router<WebServerState<S>> = Router::new().route("/health", get(health));
314
315 #[cfg(feature = "pages")]
316 let mut frontend_runtime: Option<crate::templates::FrontendRuntime> = None;
317 #[cfg(feature = "pages")]
318 let mut base: Option<crate::templates::BaseTemplateData> = None;
319 #[cfg(feature = "pages")]
320 let mut templates: Option<crate::templates::TemplateRegistry<'static>> = None;
321 #[cfg(feature = "pages")]
322 let mut not_found: Option<super::not_found::NotFound<S>> = None;
323 #[cfg(feature = "pages")]
324 let mut proxy_scripts: Option<Router<WebServerState<S>>> = None;
325 #[cfg(feature = "pages")]
326 let mut feed_router: Option<Router<WebServerState<S>>> = None;
327
328 log_immutable_assets(&cache_buster);
329
330 #[cfg(feature = "pages")]
331 if let Some(params) = frontend {
332 let assembled: AssembledFrontend<S> =
333 assemble_frontend(params, feed, &cache_buster, environment)?;
334
335 no_cache = no_cache.merge(assembled.routes);
336 built_in = built_in.merge(assembled.api);
337 proxy_scripts = Some(assembled.proxy_scripts);
338 feed_router = assembled.feeds;
339 not_found = Some(assembled.not_found);
340 frontend_runtime = Some(assembled.runtime);
341 base = Some(assembled.base);
342 templates = Some(assembled.templates);
343 }
344
345 let no_cache: Router<WebServerState<S>> = no_cache.nest(API_PREFIX, built_in);
346
347 let mut app_router: Router<WebServerState<S>> = apply_cache_policy(no_cache, &cache_buster);
348
349 #[cfg(feature = "pages")]
353 if let Some(scripts) = proxy_scripts {
354 app_router = app_router.merge(scripts);
355 }
356
357 #[cfg(feature = "pages")]
358 if let Some(feeds) = feed_router {
359 app_router = app_router.merge(feeds);
360 }
361
362 #[cfg(feature = "pages")]
363 let app_router: Router<WebServerState<S>> = attach_not_found(app_router, not_found);
364 #[cfg(not(feature = "pages"))]
365 let app_router: Router<WebServerState<S>> = app_router.fallback(plain_not_found);
366
367 let state: WebServerState<S> = WebServerState::new(StateParts {
368 host: host.clone(),
369 port,
370 environment,
371 shutdown,
372 #[cfg(feature = "templates")]
373 base,
374 #[cfg(feature = "templates")]
375 templates,
376 cache_buster: Some(cache_buster),
377 #[cfg(feature = "templates")]
378 frontend: frontend_runtime,
379 app,
380 });
381
382 let app_router: Router = with_middleware(app_router.with_state(state.clone()), body_limit);
385
386 Ok(Assembled {
387 router: app_router,
388 state,
389 host,
390 port,
391 environment,
392 })
393 }
394}
395
396fn with_middleware(router: Router, body_limit: usize) -> Router {
401 router
402 .layer(axum::middleware::from_fn(telemetry::http_metrics))
403 .layer(
404 TraceLayer::new_for_http()
405 .make_span_with(|request: &axum::http::Request<axum::body::Body>| {
410 let request_id: &str = request
411 .headers()
412 .get(&telemetry::REQUEST_ID_HEADER)
413 .and_then(|value| value.to_str().ok())
414 .unwrap_or_default();
415 tracing::info_span!(
416 "request",
417 method = %request.method(),
418 path = %request.uri().path(),
419 version = ?request.version(),
420 request_id,
421 )
422 })
423 .on_response(
424 DefaultOnResponse::new()
425 .level(Level::INFO)
426 .latency_unit(LatencyUnit::Millis),
427 ),
428 )
429 .layer(axum::middleware::from_fn(telemetry::request_id))
430 .layer(DefaultBodyLimit::max(body_limit))
431}
432
433struct Assembled<S> {
436 router: Router,
437 state: WebServerState<S>,
440 host: String,
441 port: u16,
442 environment: Environment,
443}
444
445#[cfg(feature = "pages")]
452fn attach_not_found<S>(
453 router: Router<WebServerState<S>>,
454 not_found: Option<super::not_found::NotFound<S>>,
455) -> Router<WebServerState<S>>
456where
457 S: Clone + Send + Sync + 'static,
458{
459 match not_found {
460 Some(not_found) => router.fallback(
461 move |axum::extract::State(state): axum::extract::State<WebServerState<S>>,
462 uri: axum::http::Uri| {
463 let not_found: super::not_found::NotFound<S> = not_found.clone();
464 async move {
465 let data: serde_json::Value = not_found.data(state.clone(), uri).await;
466 state.not_found(data)
467 }
468 },
469 ),
470 None => router.fallback(plain_not_found),
471 }
472}
473
474async fn serve_on<F>(
481 router: Router,
482 host: &str,
483 port: u16,
484 shutdown: Shutdown,
485 on_shutdown: F,
486) -> Result<(), WebServerError>
487where
488 F: Future<Output = ()> + Send,
489{
490 let ip: IpAddr = IpAddr::from_str(host).map_err(|source| WebServerError::Bind {
491 addr: SocketAddr::from(([0, 0, 0, 0], port)),
492 source: std::io::Error::new(std::io::ErrorKind::InvalidInput, source),
493 })?;
494 let address: SocketAddr = SocketAddr::new(ip, port);
495 let listener: TcpListener =
496 TcpListener::bind(address)
497 .await
498 .map_err(|source| WebServerError::Bind {
499 addr: address,
500 source,
501 })?;
502
503 info!("listening on http://{address}");
504
505 let serving = serve(
509 listener,
510 router.into_make_service_with_connect_info::<SocketAddr>(),
511 )
512 .with_graceful_shutdown(shutdown.clone().recv())
513 .into_future();
514 tokio::pin!(serving);
515
516 tokio::select! {
520 result = &mut serving => return result.map_err(WebServerError::Serve),
521 () = shutdown.recv() => {}
522 }
523
524 let (served, cleaned) = tokio::join!(
529 tokio::time::timeout(DEFAULT_DRAIN_TIMEOUT, &mut serving),
530 tokio::time::timeout(DEFAULT_DRAIN_TIMEOUT, on_shutdown),
531 );
532
533 if cleaned.is_err() {
537 error!(
538 "app shutdown hook exceeded {DEFAULT_DRAIN_TIMEOUT:?}; cleanup was cancelled part-way"
539 );
540 }
541
542 match served {
543 Ok(result) => result.map_err(WebServerError::Serve),
544 Err(_elapsed) => {
547 warn!("drain window elapsed after {DEFAULT_DRAIN_TIMEOUT:?}; closing what remained");
548 Ok(())
549 }
550 }
551}
552
553fn apply_cache_policy<S>(
557 router: Router<WebServerState<S>>,
558 cache_buster: &crate::assets::CacheBuster,
559) -> Router<WebServerState<S>>
560where
561 S: Clone + Send + Sync + 'static,
562{
563 let router: Router<WebServerState<S>> = router.layer(axum::middleware::from_fn(
564 crate::assets::CacheBuster::never_cache_middleware,
565 ));
566
567 if cache_buster.is_empty() {
568 return router;
569 }
570
571 router.merge(
572 Router::new()
573 .nest_service(
574 "/static",
575 tower_http::services::ServeDir::new(
576 cache_buster.root().join(crate::assets::STATIC_DIRECTORY),
577 ),
578 )
579 .layer(axum::middleware::from_fn(
580 crate::assets::CacheBuster::forever_cache_middleware,
581 )),
582 )
583}
584
585async fn health() -> StatusCode {
588 StatusCode::OK
589}
590
591async fn plain_not_found() -> Response {
593 plain_not_found_response()
594}
595
596pub(super) fn plain_not_found_response() -> Response {
598 let mut response: Response = (StatusCode::NOT_FOUND, "404").into_response();
599 crate::assets::mark_never_cached(response.headers_mut());
600 response
601}
602
603#[cfg(feature = "pages")]
610fn well_known_routes<S>(well_known: &super::frontend::WellKnown) -> Router<WebServerState<S>>
611where
612 S: Clone + Send + Sync + 'static,
613{
614 use axum::http::header;
615
616 fn text<S>(
617 router: Router<WebServerState<S>>,
618 path: &str,
619 content_type: &'static str,
620 body: String,
621 ) -> Router<WebServerState<S>>
622 where
623 S: Clone + Send + Sync + 'static,
624 {
625 router.route(
626 path,
627 get(move || {
628 let body: String = body.clone();
629 async move { ([(header::CONTENT_TYPE, content_type)], body) }
630 }),
631 )
632 }
633
634 let mut router: Router<WebServerState<S>> = Router::new();
635 router = text(
636 router,
637 "/robots.txt",
638 "text/plain; charset=utf-8",
639 well_known.robots_txt.clone(),
640 );
641 router = text(
642 router,
643 "/humans.txt",
644 "text/plain; charset=utf-8",
645 well_known.humans_txt.clone(),
646 );
647 router = text(
648 router,
649 "/site.webmanifest",
650 "application/manifest+json",
651 well_known.webmanifest.clone(),
652 );
653 router = text(
654 router,
655 crate::sitemap::SITEMAP_INDEX_PATH,
656 "application/xml",
657 well_known.sitemaps.index().to_string(),
658 );
659 for (index, chunk) in well_known.sitemaps.chunks().iter().enumerate() {
660 router = text(
661 router,
662 &format!("/sitemap-{}.xml", index + 1),
663 "application/xml",
664 chunk.clone(),
665 );
666 }
667 router
668}
669
670#[cfg(feature = "pages")]
676fn icon_routes<S>(
677 cache_buster: &crate::assets::CacheBuster,
678 has_svg_icon: bool,
679) -> Router<WebServerState<S>>
680where
681 S: Clone + Send + Sync + 'static,
682{
683 use tower_http::services::ServeFile;
684
685 let mut icons: Vec<(&str, String)> = vec![
686 (
687 "/favicon.ico",
688 String::from("static/image/favicon/favicon.ico"),
689 ),
690 (
691 "/apple-touch-icon.png",
692 String::from("static/image/favicon/apple-touch-icon.png"),
693 ),
694 (
695 "/icon-192.png",
696 String::from("static/image/favicon/icon-192.png"),
697 ),
698 (
699 "/icon-512.png",
700 String::from("static/image/favicon/icon-512.png"),
701 ),
702 ];
703 if has_svg_icon {
705 icons.push((
706 "/favicon.svg",
707 String::from("static/image/favicon/favicon.svg"),
708 ));
709 }
710
711 let mut router: Router<WebServerState<S>> = Router::new();
712 for (route, original) in icons {
713 router = router.nest_service(route, ServeFile::new(cache_buster.file(&original)));
715 }
716 router
717}
718
719#[cfg(feature = "pages")]
730fn feed_routes<S>(feeds: &crate::feed::FeedSet) -> Router<WebServerState<S>>
731where
732 S: Clone + Send + Sync + 'static,
733{
734 use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
735
736 let last_modified: HeaderValue = HeaderValue::from_str(
740 &feeds
741 .last_modified()
742 .format("%a, %d %b %Y %H:%M:%S GMT")
743 .to_string(),
744 )
745 .unwrap_or_else(|_| HeaderValue::from_static(""));
746 let cache_control: HeaderValue = HeaderValue::from_str(&format!(
747 "public, max-age={}",
748 crate::feed::FEED_MAX_AGE_SECONDS
749 ))
750 .unwrap_or_else(|_| HeaderValue::from_static("public"));
751
752 let mut router: Router<WebServerState<S>> = Router::new();
753 for document in feeds.documents() {
754 let body: String = String::from(document.body());
755 let etag_text: String = String::from(document.etag());
756 let etag: HeaderValue =
757 HeaderValue::from_str(&etag_text).unwrap_or_else(|_| HeaderValue::from_static(""));
758 let content_type: HeaderValue = HeaderValue::from_static(document.content_type());
759 let last_modified: HeaderValue = last_modified.clone();
760 let cache_control: HeaderValue = cache_control.clone();
761
762 router = router.route(
763 document.path(),
764 get(move |headers: HeaderMap| {
765 let body: String = body.clone();
766 let etag_text: String = etag_text.clone();
767 let etag: HeaderValue = etag.clone();
768 let content_type: HeaderValue = content_type.clone();
769 let last_modified: HeaderValue = last_modified.clone();
770 let cache_control: HeaderValue = cache_control.clone();
771 async move {
772 let fresh: bool = if_none_match(&headers, &etag_text);
773
774 let mut response: Response = if fresh {
779 StatusCode::NOT_MODIFIED.into_response()
780 } else {
781 (StatusCode::OK, body).into_response()
782 };
783
784 let headers: &mut HeaderMap = response.headers_mut();
785 headers.insert(header::CACHE_CONTROL, cache_control);
786 headers.insert(header::ETAG, etag);
787 headers.insert(header::LAST_MODIFIED, last_modified);
788 if !fresh {
789 headers.insert(header::CONTENT_TYPE, content_type);
790 }
791
792 response
793 }
794 }),
795 );
796 }
797
798 router
799}
800
801#[cfg(feature = "pages")]
807fn if_none_match(headers: &axum::http::HeaderMap, etag: &str) -> bool {
808 let Some(header) = headers
809 .get(axum::http::header::IF_NONE_MATCH)
810 .and_then(|value| value.to_str().ok())
811 else {
812 return false;
813 };
814
815 header.split(',').any(|candidate| {
816 let candidate: &str = candidate.trim();
817 candidate == "*" || candidate.trim_start_matches("W/") == etag
818 })
819}
820
821fn log_immutable_assets(cache_buster: &crate::assets::CacheBuster) {
831 for (original, hashed) in cache_buster.cache() {
832 info!("immutable 1y /{original} -> /{hashed}");
833 }
834}
835
836#[cfg(feature = "pages")]
838fn log_served_documents(well_known: &super::frontend::WellKnown) {
839 for path in ["/robots.txt", "/humans.txt", "/site.webmanifest"] {
840 info!("uncached {path}");
841 }
842 for path in well_known.sitemaps.paths() {
843 info!("uncached {path}");
844 }
845
846 if let Some(feeds) = well_known.feeds.as_ref() {
847 for document in feeds.documents() {
848 info!(
849 "cached {}m {} (etag {})",
850 crate::feed::FEED_MAX_AGE_SECONDS / 60,
851 document.path(),
852 document.etag()
853 );
854 }
855 }
856}
857
858#[cfg(feature = "pages")]
864struct AssembledFrontend<S> {
865 routes: Router<WebServerState<S>>,
867 api: Router<WebServerState<S>>,
869 proxy_scripts: Router<WebServerState<S>>,
871 feeds: Option<Router<WebServerState<S>>>,
873 runtime: crate::templates::FrontendRuntime,
874 base: crate::templates::BaseTemplateData,
875 templates: crate::templates::TemplateRegistry<'static>,
876 not_found: super::not_found::NotFound<S>,
877}
878
879#[cfg(feature = "pages")]
881fn assemble_frontend<S>(
882 mut params: super::frontend::FrontendParams<S>,
883 feed: Option<crate::feed::Feed>,
884 cache_buster: &crate::assets::CacheBuster,
885 environment: Environment,
886) -> Result<AssembledFrontend<S>, WebServerError>
887where
888 S: Clone + Send + Sync + 'static,
889{
890 let mut templates: crate::templates::TemplateRegistry<'static> =
891 crate::templates::TemplateRegistry::from_dir(
892 cache_buster.root().join(crate::templates::TEMPLATE_ROOT),
893 )?;
894 for (name, helper) in std::mem::take(&mut params.helpers) {
895 templates.register_project_helper(&name, helper)?;
896 }
897
898 let built: super::frontend::Frontend<S> =
899 super::frontend::Frontend::build(params, feed, cache_buster, environment)?;
900
901 log_served_documents(&built.well_known);
902
903 let feeds: Option<Router<WebServerState<S>>> = built.well_known.feeds.as_ref().map(feed_routes);
907
908 let mut routes: Router<WebServerState<S>> = well_known_routes(&built.well_known);
909 routes = routes.merge(icon_routes(cache_buster, built.has_svg_icon));
910
911 let (proxy_scripts, api) = proxy_routes(&built);
915
916 routes = routes.merge(built.pages.into_router()?);
917
918 Ok(AssembledFrontend {
919 routes,
920 api,
921 proxy_scripts,
922 feeds,
923 runtime: built.runtime,
924 base: built.base,
925 templates,
926 not_found: built.not_found,
927 })
928}
929
930#[cfg(feature = "pages")]
936fn proxy_routes<S>(
937 frontend: &super::frontend::Frontend<S>,
938) -> (Router<WebServerState<S>>, Router<WebServerState<S>>)
939where
940 S: Clone + Send + Sync + 'static,
941{
942 use crate::analytics::{AnalyticsConfig, relay_envelope, relay_event, relay_script};
943 use axum::body::Bytes;
944 use axum::extract::ConnectInfo;
945 use axum::http::HeaderMap;
946 use axum::routing::post;
947
948 let client: reqwest::Client = reqwest::Client::new();
949 let paths: &crate::templates::FrontendRuntime = &frontend.runtime;
950
951 let analytics_script_upstream: String = frontend.analytics.upstream_script_url();
952 let analytics_event_upstream: String = AnalyticsConfig::upstream_event_url();
953 let sentry_script_upstream: String = frontend.sentry_dsn.upstream_script_url();
954 let sentry_envelope_upstream: String = frontend.sentry_dsn.upstream_envelope_url();
955
956 let scripts: Router<WebServerState<S>> = Router::new()
957 .route(
958 &paths.analytics.script_path,
959 get({
960 let client: reqwest::Client = client.clone();
961 let upstream: std::sync::Arc<str> =
962 std::sync::Arc::from(analytics_script_upstream.as_str());
963 move || {
964 let client: reqwest::Client = client.clone();
965 let upstream: std::sync::Arc<str> = std::sync::Arc::clone(&upstream);
966 async move { relay_script(&client, &upstream).await }
967 }
968 }),
969 )
970 .route(
971 &paths.sentry_browser.script_path,
972 get({
973 let client: reqwest::Client = client.clone();
974 let upstream: std::sync::Arc<str> =
975 std::sync::Arc::from(sentry_script_upstream.as_str());
976 move || {
977 let client: reqwest::Client = client.clone();
978 let upstream: std::sync::Arc<str> = std::sync::Arc::clone(&upstream);
979 async move { relay_script(&client, &upstream).await }
980 }
981 }),
982 );
983
984 let event_path: String = strip_api_prefix(&paths.analytics.event_path);
986 let tunnel_path: String = strip_api_prefix(&paths.sentry_browser.tunnel_path);
987
988 let endpoints: Router<WebServerState<S>> = Router::new()
989 .route(
990 &event_path,
991 post({
992 let client: reqwest::Client = client.clone();
993 let upstream: std::sync::Arc<str> =
994 std::sync::Arc::from(analytics_event_upstream.as_str());
995 move |ConnectInfo(peer): ConnectInfo<SocketAddr>,
996 headers: HeaderMap,
997 body: Bytes| {
998 let client: reqwest::Client = client.clone();
999 let upstream: std::sync::Arc<str> = std::sync::Arc::clone(&upstream);
1000 async move { relay_event(&client, &upstream, &headers, peer, body).await }
1001 }
1002 }),
1003 )
1004 .route(
1005 &tunnel_path,
1006 post({
1007 let upstream: std::sync::Arc<str> =
1008 std::sync::Arc::from(sentry_envelope_upstream.as_str());
1009 move |body: Bytes| {
1010 let client: reqwest::Client = client.clone();
1011 let upstream: std::sync::Arc<str> = std::sync::Arc::clone(&upstream);
1012 async move { relay_envelope(&client, &upstream, body).await }
1013 }
1014 }),
1015 );
1016
1017 (scripts, endpoints)
1018}
1019
1020#[cfg(feature = "pages")]
1023fn strip_api_prefix(path: &str) -> String {
1024 path.strip_prefix(API_PREFIX)
1025 .map_or_else(|| path.to_string(), String::from)
1026}
1027
1028#[cfg(test)]
1029mod tests {
1030
1031 #[cfg(feature = "pages")]
1032 mod conditional_get {
1033 use axum::http::{HeaderMap, HeaderValue, header};
1034
1035 use crate::webserver::server::if_none_match;
1036
1037 const ETAG: &str = "\"abc123\"";
1038
1039 fn headers(value: &str) -> HeaderMap {
1040 let mut headers: HeaderMap = HeaderMap::new();
1041 headers.insert(
1042 header::IF_NONE_MATCH,
1043 HeaderValue::from_str(value).expect("a valid header"),
1044 );
1045 headers
1046 }
1047
1048 #[test]
1049 fn a_request_without_the_header_always_gets_the_body() {
1050 let expected: bool = false;
1051 let actual: bool = if_none_match(&HeaderMap::new(), ETAG);
1052 assert_eq!(expected, actual);
1053 }
1054
1055 #[test]
1056 fn the_same_validator_means_the_reader_already_has_this_feed() {
1057 let expected: bool = true;
1058 let actual: bool = if_none_match(&headers(ETAG), ETAG);
1059 assert_eq!(expected, actual);
1060 }
1061
1062 #[test]
1063 fn a_weak_validator_still_matches_because_feeds_need_no_byte_equality() {
1064 let expected: bool = true;
1065 let actual: bool = if_none_match(&headers("W/\"abc123\""), ETAG);
1066 assert_eq!(expected, actual);
1067 }
1068
1069 #[test]
1070 fn a_star_matches_anything_that_exists() {
1071 let expected: bool = true;
1072 let actual: bool = if_none_match(&headers("*"), ETAG);
1073 assert_eq!(expected, actual);
1074 }
1075
1076 #[test]
1077 fn one_match_anywhere_in_the_list_is_enough() {
1078 let expected: bool = true;
1082 let actual: bool = if_none_match(&headers("\"other\", \"abc123\""), ETAG);
1083 assert_eq!(expected, actual);
1084 }
1085
1086 #[test]
1087 fn a_stale_validator_gets_the_new_document() {
1088 let expected: bool = false;
1089 let actual: bool = if_none_match(&headers("\"stale\""), ETAG);
1090 assert_eq!(expected, actual);
1091 }
1092 }
1093 use std::sync::Arc;
1094 use std::sync::atomic::{AtomicBool, Ordering};
1095 use std::time::Duration;
1096
1097 use axum::Router;
1098 use axum::routing::get;
1099 use tokio::time::timeout;
1100
1101 use super::super::shutdown::Shutdown;
1102 use super::{
1103 API_PREFIX, AppShutdown, DEFAULT_BODY_LIMIT, DEFAULT_DRAIN_TIMEOUT, WebServerError, health,
1104 serve_on,
1105 };
1106
1107 #[derive(Clone)]
1110 struct RecordingState {
1111 ran: Arc<AtomicBool>,
1112 linger: Option<Duration>,
1113 }
1114
1115 impl RecordingState {
1116 fn instant() -> Self {
1117 Self {
1118 ran: Arc::new(AtomicBool::new(false)),
1119 linger: None,
1120 }
1121 }
1122 }
1123
1124 impl AppShutdown for RecordingState {
1125 async fn on_shutdown(&self) {
1126 if let Some(linger) = self.linger {
1127 tokio::time::sleep(linger).await;
1128 }
1129 self.ran.store(true, Ordering::SeqCst);
1130 }
1131 }
1132
1133 async fn serve_until_shutdown(
1135 state: RecordingState,
1136 shutdown: Shutdown,
1137 ) -> Result<(), WebServerError> {
1138 let router: Router = Router::new().route("/health", get(health));
1139 let cleanup: RecordingState = state.clone();
1140 serve_on(router, "127.0.0.1", 0, shutdown, async move {
1142 cleanup.on_shutdown().await;
1143 })
1144 .await
1145 }
1146
1147 #[tokio::test]
1148 async fn app_cleanup_runs_when_the_shutdown_signal_arrives() {
1149 let shutdown: Shutdown = Shutdown::manual();
1150 let state: RecordingState = RecordingState::instant();
1151 let ran: Arc<AtomicBool> = Arc::clone(&state.ran);
1152
1153 shutdown.trigger();
1154 timeout(
1155 Duration::from_secs(1),
1156 serve_until_shutdown(state, shutdown.clone()),
1157 )
1158 .await
1159 .expect("serving ended promptly")
1160 .expect("serving ended cleanly");
1161
1162 let expected: bool = true;
1163 let actual: bool = ran.load(Ordering::SeqCst);
1164 assert_eq!(expected, actual);
1165 }
1166
1167 #[tokio::test]
1168 async fn app_cleanup_never_runs_when_the_server_dies_before_any_signal() {
1169 let shutdown: Shutdown = Shutdown::manual();
1173 let state: RecordingState = RecordingState::instant();
1174 let ran: Arc<AtomicBool> = Arc::clone(&state.ran);
1175 let cleanup: RecordingState = state.clone();
1176
1177 let router: Router = Router::new().route("/health", get(health));
1178 let result: Result<(), WebServerError> = timeout(
1179 Duration::from_secs(1),
1180 serve_on(router, "not-an-ip", 0, shutdown, async move {
1181 cleanup.on_shutdown().await;
1182 }),
1183 )
1184 .await
1185 .expect("a bind failure returns immediately, it does not wait for cleanup");
1186
1187 assert!(result.is_err(), "an unparseable host is a bind error");
1188
1189 let expected: bool = false;
1190 let actual: bool = ran.load(Ordering::SeqCst);
1191 assert_eq!(expected, actual);
1192 }
1193
1194 #[tokio::test(start_paused = true)]
1195 async fn a_cleanup_that_overruns_the_window_is_cancelled_rather_than_awaited() {
1196 let shutdown: Shutdown = Shutdown::manual();
1200 let state: RecordingState = RecordingState {
1201 ran: Arc::new(AtomicBool::new(false)),
1202 linger: Some(DEFAULT_DRAIN_TIMEOUT * 2),
1203 };
1204 let ran: Arc<AtomicBool> = Arc::clone(&state.ran);
1205
1206 shutdown.trigger();
1207 serve_until_shutdown(state, shutdown.clone())
1208 .await
1209 .expect("serving still ends cleanly when cleanup is cancelled");
1210
1211 let expected: bool = false;
1212 let actual: bool = ran.load(Ordering::SeqCst);
1213 assert_eq!(
1214 expected, actual,
1215 "the hook was cancelled at its await, so it never reached its final store"
1216 );
1217 }
1218
1219 #[tokio::test]
1220 async fn a_server_with_nothing_in_flight_stops_at_once_instead_of_waiting_out_the_window() {
1221 let shutdown: Shutdown = Shutdown::manual();
1222 let router: Router = Router::new().route("/health", get(health));
1223
1224 let serving: tokio::task::JoinHandle<Result<(), WebServerError>> = tokio::spawn({
1226 let shutdown: Shutdown = shutdown.clone();
1227 async move { serve_on(router, "127.0.0.1", 0, shutdown, async {}).await }
1228 });
1229
1230 shutdown.trigger();
1231
1232 timeout(Duration::from_secs(1), serving)
1235 .await
1236 .expect("the server returned as soon as the drain began")
1237 .expect("the serving task did not panic")
1238 .expect("serving ended cleanly");
1239 }
1240
1241 #[test]
1242 fn the_body_limit_accommodates_an_ordinary_form_post() {
1243 let expected: usize = 256 * 1024;
1246 let actual: usize = DEFAULT_BODY_LIMIT;
1247 assert_eq!(expected, actual);
1248 }
1249
1250 #[cfg(feature = "pages")]
1251 #[test]
1252 fn stripping_the_prefix_leaves_a_nestable_path() {
1253 let expected: String = String::from("/boggledygook-a3f2c1d8");
1254 let actual: String = super::strip_api_prefix("/api/v1/boggledygook-a3f2c1d8");
1255 assert_eq!(expected, actual);
1256 }
1257
1258 #[test]
1259 fn the_api_prefix_is_the_one_every_project_shares() {
1260 assert_eq!("/api/v1", API_PREFIX);
1261 }
1262}