Skip to main content

tuwunel_api/router/
handler.rs

1use std::{any::Any, fmt::Debug};
2
3use axum::{
4	Router,
5	body::Body,
6	extract::{FromRequest, FromRequestParts},
7	handler::Handler,
8	response::{IntoResponse, Response},
9	routing::{MethodFilter, on},
10};
11#[cfg(debug_assertions)]
12use futures::FutureExt;
13use http::{Method, Request};
14use ruma::api::{IncomingRequest, path_builder::PathBuilder};
15use tuwunel_core::Result;
16
17use super::{Ruma, RumaResponse, State, auth::AuthDispatch};
18
19/// Registers Matrix request handlers with a router.
20///
21/// Implementations convert incoming requests and dispatch them to endpoint handlers.
22pub trait RumaHandler<T> {
23	/// Registers every path declared by the request type.
24	///
25	/// Each path dispatches requests to this handler.
26	fn add_routes(&'static self, router: Router<State>) -> Router<State>;
27
28	/// Registers the handler at one endpoint path.
29	///
30	/// The returned router dispatches matching requests to this handler.
31	fn add_route(&'static self, router: Router<State>, path: &str) -> Router<State>;
32
33	/// Dispatches an incoming request to the endpoint handler.
34	///
35	/// The returned future resolves to the HTTP response.
36	fn call_route(
37		handler: RouteHandler,
38		state: State,
39		request: Request<Body>,
40	) -> impl Future<Output = Response> + Send + 'static;
41}
42
43/// Extends routers with Matrix endpoint registration.
44///
45/// Each handler registers the paths declared by its request type.
46pub trait RouterExt {
47	/// Registers a Matrix endpoint handler with this router.
48	///
49	/// The handler supplies the paths declared by its request type.
50	#[must_use]
51	fn ruma_route<H: RumaHandler<T>, T>(self, handler: &'static H) -> Self;
52}
53
54struct Route<Fut> {
55	call: RouteCall<Fut>,
56	handler: RouteHandler,
57}
58
59type RouteCall<Fut> = fn(RouteHandler, State, Request<Body>) -> Fut;
60type RouteHandler = &'static (dyn Any + Send + Sync);
61
62impl<Fut> Copy for Route<Fut> {}
63
64impl<Fut> Clone for Route<Fut> {
65	fn clone(&self) -> Self { *self }
66}
67
68impl RouterExt for Router<State> {
69	fn ruma_route<H: RumaHandler<T>, T>(self, handler: &'static H) -> Self {
70		handler.add_routes(self)
71	}
72}
73
74impl<Fut> Handler<(), State> for Route<Fut>
75where
76	Fut: Future<Output = Response> + Send + 'static,
77{
78	type Future = Fut;
79
80	fn call(self, request: Request<Body>, state: State) -> Self::Future {
81		(self.call)(self.handler, state, request)
82	}
83}
84
85macro_rules! ruma_handler {
86	( $($tx:ident),* $(,)? ) => {
87		#[allow(clippy::allow_attributes, non_snake_case)]
88		impl<Err, Req, Fut, Fun, const ADMIN: bool, $($tx,)*> RumaHandler<($($tx,)* Ruma<Req, ADMIN>,)> for Fun
89		where
90			Fun: Fn($($tx,)* Ruma<Req, ADMIN>,) -> Fut + Send + Sync + 'static,
91			Fut: Future<Output = Result<Req::OutgoingResponse, Err>> + Send + 'static,
92			Req: IncomingRequest + Debug + Send + Sync + 'static,
93			Req::Authentication: AuthDispatch,
94			Err: IntoResponse + Send,
95			<Req as IncomingRequest>::OutgoingResponse: Send,
96			$( $tx: FromRequestParts<State> + Send + Sync + 'static, )*
97		{
98			fn add_routes(&'static self, router: Router<State>) -> Router<State> {
99				Req::PATH_BUILDER
100					.all_paths()
101					.fold(router, |router, path| self.add_route(router, path))
102			}
103
104			fn add_route(&'static self, router: Router<State>, path: &str) -> Router<State> {
105				let route = Route { handler: self, call: Self::call_route };
106
107				router.route(path, on(method_to_filter(&Req::METHOD), route))
108			}
109
110			fn call_route(
111				handler: RouteHandler,
112				state: State,
113				request: Request<Body>,
114			) -> impl Future<Output = Response> + Send + 'static {
115				let handler: &'static Fun = handler
116					.downcast_ref()
117					.expect("route handler matches the type it registered with");
118
119				let response = async move {
120					#[allow(unused_mut)]
121					let (mut parts, body) = request.into_parts();
122					$(
123						let $tx = match $tx::from_request_parts(&mut parts, &state).await {
124							| Err(error) => return error.into_response(),
125							| Ok(value) => value,
126						};
127					)*
128
129					let request = Request::from_parts(parts, body);
130					let args = match Ruma::<Req, ADMIN>::from_request(request, &state).await {
131						| Err(error) => return error.into_response(),
132						| Ok(args) => args,
133					};
134
135					match handler($($tx,)* args).await {
136						| Err(error) => error.into_response(),
137						| Ok(response) => RumaResponse(response).into_response(),
138					}
139				};
140
141				cfg_select! {
142					debug_assertions => response.boxed(), // compile-time firewall per route
143					_ => response,
144				}
145			}
146		}
147	}
148}
149ruma_handler!();
150ruma_handler!(T1);
151ruma_handler!(T1, T2);
152ruma_handler!(T1, T2, T3);
153ruma_handler!(T1, T2, T3, T4);
154
155fn method_to_filter(method: &Method) -> MethodFilter {
156	match method {
157		| &Method::DELETE => MethodFilter::DELETE,
158		| &Method::GET => MethodFilter::GET,
159		| &Method::HEAD => MethodFilter::HEAD,
160		| &Method::OPTIONS => MethodFilter::OPTIONS,
161		| &Method::PATCH => MethodFilter::PATCH,
162		| &Method::POST => MethodFilter::POST,
163		| &Method::PUT => MethodFilter::PUT,
164		| &Method::TRACE => MethodFilter::TRACE,
165		| _ => panic!("Unsupported HTTP method"),
166	}
167}