ferrohealth_server/stack.rs
1// SPDX-FileCopyrightText: Cadasto B.V.
2// SPDX-License-Identifier: BUSL-1.1
3
4//! The one stack every server runs around its routes.
5
6use std::sync::Arc;
7
8use axum::Router;
9use axum::extract::DefaultBodyLimit;
10use axum::handler::Handler;
11use ferrohealth_telemetry::request_log::RequestLog;
12use opentelemetry::metrics::Meter;
13use tower::ServiceBuilder;
14use tower_http::compression::CompressionLayer;
15use tower_http::compression::predicate::{NotForContentType, Predicate as _, SizeAbove};
16use tower_http::limit::RequestBodyLimitLayer;
17
18use crate::api_headers;
19use crate::client_address::Forwarding;
20use crate::decoding::DecodeLayer;
21use crate::edge::{self, EdgeLayer, IdentifyLayer};
22use crate::health::{self, Health};
23use crate::overload::{self, Admission};
24use crate::panic::{self, PanicBody};
25use crate::refusal::{self, RefusalBody};
26use crate::section::ServerSection;
27
28/// What a product decides inside the stack: the body of a panicked request,
29/// the body of a refusal, the request log with its recorders and the meter
30/// of the stack's own metrics.
31#[derive(Clone)]
32pub struct StackPolicy {
33 /// The body of a panicked request.
34 pub panic_body: PanicBody,
35 /// The body of a refusal the stack writes: `408`, `413`, `415`, `429`,
36 /// `503`, and the `400` of an encoded body that does not decode.
37 pub refusal_body: RefusalBody,
38 /// The request log.
39 pub request_log: RequestLog,
40 /// The meter the admission records its waits and refusals in
41 /// ([`crate::overload::Admission::with_metrics`]), such as
42 /// `Telemetry::meter`'s; unset, they are not recorded.
43 pub meter: Option<Meter>,
44}
45
46impl std::fmt::Debug for StackPolicy {
47 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48 f.debug_struct("StackPolicy")
49 .field("request_log", &self.request_log)
50 .field("meter", &self.meter)
51 .finish_non_exhaustive()
52 }
53}
54
55impl Default for StackPolicy {
56 fn default() -> Self {
57 Self {
58 panic_body: panic::default_body(),
59 refusal_body: Arc::clone(&refusal::DEFAULT_BODY),
60 request_log: RequestLog::default(),
61 meter: None,
62 }
63 }
64}
65
66/// Wraps `product` and the health routes in the stack, under the base path.
67///
68/// From the outside in: the API security headers ([`crate::api_headers`]),
69/// the overload bound and its queue on the product's routes and the routes
70/// beside, the request id, the request log, the client address, the refusal
71/// rendering, the panic rendering, the panic catch, the request timeout
72/// (`408`), the body limit (`413`, and the same ceiling for every
73/// extractor), the request decoding when it is on (`415` for a coding it
74/// does not decode, and the body limit on the decoded bytes), the response
75/// compression when it is on, then the routes.
76/// Every request the bound admits leaves one request line, a refusal and a
77/// panic included. A request the bound refuses is counted and leaves no
78/// line of its own ([`crate::overload`]), so a refusal costs less than
79/// serving.
80///
81/// It is [`Stack::new`] with nothing beside the base path, and a request no
82/// route matched takes the product's fallback with the product's layers
83/// (axum's empty `404` unless the product changes it); [`Stack`] adds both.
84pub fn app(
85 product: Router,
86 health: Health,
87 section: &ServerSection,
88 policy: StackPolicy,
89) -> Router {
90 Stack::new(product, health, section, policy).into_router()
91}
92
93/// The stack around a product, with the routes it serves beside its base
94/// path and the fallback of a request no route matched.
95///
96/// [`Stack::into_router`] mounts the product and the health routes under
97/// the base path, as [`app`] does, the routes of [`Stack::beside`] at the
98/// root next to them, and the handler of [`Stack::fallback`] for every
99/// request no route matched. Every layer of [`app`] covers all three, and
100/// the overload bound covers the product's routes and the routes beside.
101///
102/// # Examples
103///
104/// ```
105/// use axum::Router;
106/// use axum::routing::get;
107/// use ferrohealth_health::lifecycle::Lifecycle;
108/// use ferrohealth_health::registry::Registry;
109/// use ferrohealth_server::health::Health;
110/// use ferrohealth_server::section::{BasePath, ServerSection};
111/// use ferrohealth_server::stack::{Stack, StackPolicy};
112/// use http::StatusCode;
113///
114/// let section = ServerSection {
115/// base_path: BasePath::new("/ehr")?,
116/// ..ServerSection::default()
117/// };
118/// let health = Health::new(Registry::default(), Lifecycle::default());
119/// // `/ehr/v1/ehr` and `/ehr/health` under the base path, `/fhir/metadata`
120/// // beside it, and the product's own `404` for every other path.
121/// let product = Router::new().route("/v1/ehr", get(|| async { "ehr" }));
122/// let fhir = Router::new().route("/fhir/metadata", get(|| async { "metadata" }));
123/// let app: Router = Stack::new(product, health, §ion, StackPolicy::default())
124/// .beside(fhir)
125/// .fallback(|| async { (StatusCode::NOT_FOUND, "no such resource") })
126/// .into_router();
127/// # let _ = app;
128/// # Ok::<(), ferrohealth_server::section::BasePathError>(())
129/// ```
130#[derive(Debug)]
131#[must_use]
132pub struct Stack {
133 product: Router,
134 health: Health,
135 section: ServerSection,
136 policy: StackPolicy,
137 beside: Router,
138 fallback: Option<Router>,
139}
140
141impl Stack {
142 /// The stack around `product` and `health` under `section`, with
143 /// `policy`: what [`app`] builds.
144 pub fn new(
145 product: Router,
146 health: Health,
147 section: &ServerSection,
148 policy: StackPolicy,
149 ) -> Self {
150 Self {
151 product,
152 health,
153 section: section.clone(),
154 policy,
155 beside: Router::new(),
156 fallback: None,
157 }
158 }
159
160 /// Mounts `routes` at the root, beside the base path, with every layer
161 /// of the stack and the overload bound around them.
162 ///
163 /// A path of `routes` is served as written, whatever the base path; with
164 /// an empty base path they sit next to the product's routes. Called more
165 /// than once, the routes add up.
166 ///
167 /// Without [`Stack::fallback`], a path no route matched takes the
168 /// fallback `routes` declare when they declare one, and the product's
169 /// otherwise, with every layer the product applied. Under an empty base
170 /// path that is the product's own or default fallback; under a non-empty
171 /// one only a fallback the product declares, for the paths under the
172 /// base path (axum `Router::nest`, "Fallbacks"), and axum's empty `404`
173 /// for the rest.
174 pub fn beside(mut self, routes: Router) -> Self {
175 self.beside = self.beside.merge(routes);
176 self
177 }
178
179 /// Answers every request no route matched with `handler`, inside every
180 /// layer of the stack and outside the overload bound.
181 ///
182 /// It answers a path outside the base path and every route beside it,
183 /// and a path under the base path that no route matched, unless the
184 /// product's router has a fallback of its own (axum `Router::nest`,
185 /// "Fallbacks"). A second call replaces the first.
186 pub fn fallback<H, T>(mut self, handler: H) -> Self
187 where
188 H: Handler<T, ()>,
189 T: 'static,
190 {
191 self.fallback = Some(Router::new().fallback(handler));
192 self
193 }
194
195 /// Builds the router the listener serves.
196 ///
197 /// # Panics
198 ///
199 /// When axum refuses the routes it merges: a route beside the base path
200 /// that is also a route under it, or, with [`Stack::fallback`] set, a
201 /// router beside or a product under an empty base path that carries a
202 /// fallback of its own (axum `Router::merge`, "Panics").
203 pub fn into_router(self) -> Router {
204 let Self {
205 product,
206 health,
207 section,
208 policy,
209 beside,
210 fallback,
211 } = self;
212 let base = section.base_path.as_str();
213 let admission = Admission::new(section.max_concurrent_requests, section.retry_after.get())
214 .with_queue(section.max_waiting_requests, section.admission_wait.get())
215 .exempting(
216 [
217 health::LIVENESS,
218 health::READINESS,
219 health::SUMMARY,
220 health::INFO,
221 ]
222 .map(|route| format!("{base}{route}")),
223 )
224 .writing(Arc::clone(&policy.refusal_body));
225 let admission = match &policy.meter {
226 Some(meter) => admission.with_metrics(meter),
227 None => admission,
228 };
229 let routes = health::routes(health).merge(product);
230 let routes = if base.is_empty() {
231 routes
232 } else {
233 Router::new().nest(base, routes)
234 };
235 // NOTE: axum 0.8 `Router::merge` keeps the fallback of `other` when neither router
236 // declares one, so `routes` merges last and keeps the product's layered fallback.
237 let routes = beside.merge(routes);
238 let routes = match fallback {
239 Some(fallback) => routes.merge(fallback),
240 None => routes,
241 };
242 wrap(routes, §ion, policy, admission)
243 }
244}
245
246/// Wraps `routes` in every layer of the stack, with `admission` on every
247/// route outside the request id and inside the API security headers.
248fn wrap(
249 routes: Router,
250 section: &ServerSection,
251 policy: StackPolicy,
252 admission: Admission,
253) -> Router {
254 // NOTE: axum `Router::layer` wraps every route and the fallback, so the matched
255 // route is still known and a request no route matched is logged too.
256 let edge = EdgeLayer::new(edge::Settings {
257 forwarding: Forwarding::from_section(section),
258 panic_body: policy.panic_body,
259 refusal_body: policy.refusal_body,
260 timeout: section.request_timeout.get(),
261 body_limit: section.body_limit_bytes(),
262 decoding: section.request_decompression,
263 });
264 let transport = api_headers::Transport {
265 tls: section.tls.is_some(),
266 };
267 let outer = ServiceBuilder::new()
268 .layer(IdentifyLayer)
269 .layer(policy.request_log)
270 .layer(edge)
271 .layer(RequestBodyLimitLayer::new(section.body_limit_bytes()))
272 .layer(DefaultBodyLimit::max(section.body_limit_bytes()));
273 // NOTE: axum `Router::layer` wraps the routes in order, so the decoder sits innermost,
274 // inside the wire body limit, and the edge has admitted the coding it reads.
275 let routes = if section.request_decompression {
276 routes.layer(DecodeLayer)
277 } else {
278 routes
279 };
280 let routes = if section.compression {
281 routes.layer(
282 outer.layer(
283 CompressionLayer::new().gzip(true).br(true).compress_when(
284 SizeAbove::new(section.compression_min_size.bytes())
285 .and(NotForContentType::GRPC)
286 .and(NotForContentType::IMAGES)
287 .and(NotForContentType::SSE),
288 ),
289 ),
290 )
291 } else {
292 routes.layer(outer)
293 };
294 // NOTE: axum 0.8 `Router::route_layer` wraps the routes alone after routing, so the
295 // bound sees the matched route, passes the health family and leaves every fallback out.
296 routes
297 .route_layer(axum::middleware::from_fn_with_state(
298 admission,
299 overload::admit,
300 ))
301 .layer(axum::middleware::from_fn_with_state(
302 transport,
303 api_headers::set,
304 ))
305}