1use std::convert::Infallible;
11use std::future::Future;
12use std::marker::PhantomData;
13use std::pin::Pin;
14use std::task::{Context, Poll};
15
16use tower::util::BoxCloneSyncService;
17use tower::{Layer, Service, ServiceExt};
18
19use crate::extract::{FromRequest, FromRequestParts, Request};
20use crate::response::{IntoResponse, Response};
21
22pub trait Handler<T>: Clone + Send + Sync + Sized + 'static {
27 type Future: Future<Output = Response> + Send + 'static;
29
30 fn call(self, request: Request) -> Self::Future;
34}
35
36impl<F, Fut, R> Handler<()> for F
37where
38 F: FnOnce() -> Fut + Clone + Send + Sync + 'static,
39 Fut: Future<Output = R> + Send + 'static,
40 R: IntoResponse,
41{
42 type Future = Pin<Box<dyn Future<Output = Response> + Send>>;
43
44 fn call(self, _request: Request) -> Self::Future {
45 Box::pin(async move { self().await.into_response() })
46 }
47}
48
49macro_rules! handler {
50 ($($arg:ident),* ; $last:ident) => {
51 #[allow(non_snake_case)]
52 impl<F, Fut, R, M, $($arg,)* $last> Handler<(M, $($arg,)* $last,)> for F
53 where
54 F: FnOnce($($arg,)* $last) -> Fut + Clone + Send + Sync + 'static,
55 Fut: Future<Output = R> + Send + 'static,
56 R: IntoResponse,
57 M: 'static,
58 $($arg: FromRequestParts + 'static,)*
59 $last: FromRequest<M> + 'static,
60 {
61 type Future = Pin<Box<dyn Future<Output = Response> + Send>>;
62
63 fn call(self, request: Request) -> Self::Future {
64 Box::pin(async move {
65 #[allow(unused_mut)]
66 let (mut parts, body) = request.into_parts();
67 $(
68 let $arg = match $arg::from_request_parts(&mut parts).await {
69 Ok(value) => value,
70 Err(rejection) => return rejection.into_response(),
71 };
72 )*
73 let request = Request::from_parts(parts, body);
74 let $last = match $last::from_request(request).await {
75 Ok(value) => value,
76 Err(rejection) => return rejection.into_response(),
77 };
78 self($($arg,)* $last).await.into_response()
79 })
80 }
81 }
82 };
83}
84
85handler!(; T1);
86handler!(T1; T2);
87handler!(T1, T2; T3);
88handler!(T1, T2, T3; T4);
89handler!(T1, T2, T3, T4; T5);
90handler!(T1, T2, T3, T4, T5; T6);
91handler!(T1, T2, T3, T4, T5, T6; T7);
92handler!(T1, T2, T3, T4, T5, T6, T7; T8);
93handler!(T1, T2, T3, T4, T5, T6, T7, T8; T9);
94handler!(T1, T2, T3, T4, T5, T6, T7, T8, T9; T10);
95handler!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10; T11);
96handler!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11; T12);
97handler!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12; T13);
98handler!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13; T14);
99handler!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14; T15);
100handler!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15; T16);
101
102pub type BoxedService = BoxCloneSyncService<Request, Response, Infallible>;
104
105#[derive(Clone)]
107pub struct Endpoint {
108 service: BoxedService,
109}
110
111impl Endpoint {
112 pub fn new<H, T>(handler: H) -> Self
114 where
115 H: Handler<T>,
116 T: 'static,
117 {
118 Self {
119 service: BoxCloneSyncService::new(HandlerService {
120 handler,
121 _arguments: PhantomData,
122 }),
123 }
124 }
125
126 pub fn layer<L>(self, layer: L) -> Self
130 where
131 L: Layer<BoxedService>,
132 L::Service: Service<Request, Response = Response, Error = Infallible>
133 + Clone
134 + Send
135 + Sync
136 + 'static,
137 <L::Service as Service<Request>>::Future: Send + 'static,
138 {
139 Self {
140 service: BoxCloneSyncService::new(layer.layer(self.service)),
141 }
142 }
143
144 pub(crate) fn into_service(self) -> BoxedService {
146 self.service
147 }
148
149 pub fn guest_or(guest: Endpoint, signed_in: Endpoint) -> Self {
152 Self {
153 service: BoxCloneSyncService::new(GuestOr {
154 guest: guest.service,
155 signed_in: signed_in.service,
156 }),
157 }
158 }
159}
160
161#[derive(Clone)]
163struct GuestOr {
164 guest: BoxedService,
165 signed_in: BoxedService,
166}
167
168impl Service<Request> for GuestOr {
169 type Response = Response;
170 type Error = Infallible;
171 type Future = Pin<Box<dyn Future<Output = Result<Response, Infallible>> + Send>>;
172
173 fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Infallible>> {
174 Poll::Ready(Ok(()))
175 }
176
177 fn call(&mut self, request: Request) -> Self::Future {
178 let signed_in = request
179 .extensions()
180 .get::<navree_contracts::AuthState>()
181 .is_some_and(|state| state.0.is_some());
182 let service = if signed_in {
183 self.signed_in.clone()
184 } else {
185 self.guest.clone()
186 };
187 Box::pin(async move {
188 let mut response = service.oneshot(request).await?;
189 let headers = response.headers_mut();
190 if signed_in {
194 if !kept_private(headers) {
195 headers.insert(
196 http::header::CACHE_CONTROL,
197 http::HeaderValue::from_static("private, no-store"),
198 );
199 }
200 for cdn in [
203 "cdn-cache-control",
204 "cloudflare-cdn-cache-control",
205 "surrogate-control",
206 ] {
207 headers.remove(cdn);
208 }
209 }
210 headers.append(
212 http::header::VARY,
213 http::HeaderValue::from_static("cookie, authorization"),
214 );
215 Ok(response)
216 })
217 }
218}
219
220fn kept_private(headers: &http::HeaderMap) -> bool {
225 let mut directives: Vec<(String, bool)> = Vec::new();
226 for value in headers.get_all(http::header::CACHE_CONTROL) {
227 let Ok(value) = value.to_str() else {
228 return false;
229 };
230 for directive in value.split(',') {
231 let (name, argument) = match directive.split_once('=') {
232 Some((name, _)) => (name, true),
233 None => (directive, false),
234 };
235 directives.push((name.trim().to_ascii_lowercase(), argument));
236 }
237 }
238 let bare = |name: &str| directives.iter().any(|(have, arg)| have == name && !arg);
239 let any = |name: &str| directives.iter().any(|(have, _)| have == name);
240 (bare("private") || bare("no-store")) && !any("public") && !any("s-maxage")
241}
242
243impl std::fmt::Debug for Endpoint {
244 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
245 f.debug_struct("Endpoint").finish_non_exhaustive()
246 }
247}
248
249struct HandlerService<H, T> {
251 handler: H,
252 _arguments: PhantomData<fn() -> T>,
253}
254
255impl<H: Clone, T> Clone for HandlerService<H, T> {
256 fn clone(&self) -> Self {
257 Self {
258 handler: self.handler.clone(),
259 _arguments: PhantomData,
260 }
261 }
262}
263
264impl<H, T> Service<Request> for HandlerService<H, T>
265where
266 H: Handler<T>,
267{
268 type Response = Response;
269 type Error = Infallible;
270 type Future = OkFuture<H::Future>;
271
272 fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Infallible>> {
273 Poll::Ready(Ok(()))
274 }
275
276 fn call(&mut self, request: Request) -> Self::Future {
277 OkFuture {
278 inner: self.handler.clone().call(request),
279 }
280 }
281}
282
283pin_project_lite::pin_project! {
284 pub(crate) struct OkFuture<F> {
286 #[pin]
287 inner: F,
288 }
289}
290
291impl<F: Future<Output = Response>> Future for OkFuture<F> {
292 type Output = Result<Response, Infallible>;
293
294 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
295 self.project().inner.poll(cx).map(Ok)
296 }
297}
298
299pub(crate) async fn call(service: BoxedService, request: Request) -> Response {
301 match service.oneshot(request).await {
302 Ok(response) => response,
303 Err(never) => match never {},
304 }
305}
306
307#[cfg(test)]
308mod tests {
309 use http::StatusCode;
310 use http_body_util::BodyExt;
311
312 use super::*;
313 use crate::body::Body;
314 use crate::{Json, Query};
315
316 async fn run<H: Handler<T>, T: 'static>(handler: H, request: Request) -> (StatusCode, String) {
317 let response = handler.call(request).await;
318 let status = response.status();
319 let body = response.into_body().collect().await.unwrap().to_bytes();
321 (status, String::from_utf8_lossy(&body).into_owned())
322 }
323
324 fn get(uri: &str) -> Request {
325 http::Request::get(uri).body(Body::empty()).unwrap()
326 }
327
328 #[tokio::test]
329 async fn arguments_are_extracted_in_order() {
330 async fn none() -> &'static str {
331 "none"
332 }
333 assert_eq!(run(none, get("/")).await, (StatusCode::OK, "none".into()));
334
335 async fn query(Query(q): Query<std::collections::HashMap<String, String>>) -> String {
336 q["a"].clone()
337 }
338 assert_eq!(run(query, get("/?a=1")).await.1, "1");
339
340 async fn both(
341 Query(q): Query<std::collections::HashMap<String, u8>>,
342 Json(v): Json<u8>,
343 ) -> String {
344 format!("{} {v}", q["a"])
345 }
346 let request = http::Request::post("/?a=1")
347 .header("content-type", "application/json")
348 .body(Body::from("2"))
349 .unwrap();
350 assert_eq!(run(both, request).await.1, "1 2");
351 }
352
353 #[tokio::test]
354 async fn a_failed_extractor_answers_with_its_rejection() {
355 async fn needs_json(Json(_): Json<u8>) -> &'static str {
356 "unreachable"
357 }
358 let (status, _) = run(needs_json, get("/")).await;
359 assert_eq!(status, StatusCode::UNSUPPORTED_MEDIA_TYPE);
360 }
361}