Skip to main content

waveless_runtime/services/upgrade/
websockets.rs

1// Waveless
2// Copyright (C) 2026 Oscar Alvarez Gonzalez
3
4use waveless_commons::databases::DatabaseConsumer;
5
6use crate::*;
7
8/// TODO: add documentation.
9#[derive(Clone, Constructor, Debug)]
10pub struct WebSocketsSvc;
11
12impl Service<RequestCx> for WebSocketsSvc {
13    type Response = ResponseCx;
14
15    type Error = RequestError;
16
17    type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
18
19    fn poll_ready(&mut self, _cx: &mut std::task::Context<'_>) -> Poll<Result<(), Self::Error>> {
20        Poll::Ready(Ok(()))
21    }
22
23    #[instrument(skip_all)]
24    fn call(&mut self, mut cx: RequestCx) -> Self::Future {
25        let future: Pin<_> = Box::pin(async move {
26            let RequestCx {
27                request,
28                request_params,
29                ..
30            } = &mut cx;
31
32            // Make sure the current request is truly a connection upgrade request.
33            if !hyper_tungstenite::is_upgrade_request(&request) {
34                unreachable!()
35            }
36
37            // Get the requested socket endpoint.
38            let endpoint_id = match request
39                .headers()
40                .get("Sec-WebSocket-Protocol")
41                .map(|value| value.to_str())
42            {
43                Some(Ok(value)) if !value.is_empty() => value,
44                Some(Err(_)) => {
45                    return Err(RequestError::Expected(
46                        StatusCode::BAD_REQUEST,
47                        format!("Socket endpoint id format is not valid.").into(),
48                    ));
49                }
50                _ => {
51                    return Err(RequestError::Expected(
52                        StatusCode::BAD_REQUEST,
53                        format!("Socket endpoint id was not specified.").into(),
54                    ));
55                }
56            };
57
58            let _build_lock = RuntimeCx::acquire().build().read().await;
59
60            let Some(endpoint) = _build_lock
61                .endpoints()
62                .inner()
63                .iter()
64                .find(|endpoint| {
65                    match (endpoint.id() == endpoint_id, endpoint.execution_target()) {
66                        (true, ExecutionTarget::Socket(_)) => true,
67                        _ => false,
68                    }
69                })
70                .to_owned()
71            else {
72                return Err(RequestError::Expected(
73                    StatusCode::BAD_REQUEST,
74                    format!("Socket endpoint `{}` is not defined.", endpoint_id).into(),
75                ));
76            };
77
78            let auth = endpoint.auth();
79
80            // Enforce socket endpoint's authentication.
81            // TODO: maybe do this in the [`SessionWatchdog`](waveless_runtime::services::SessionWatchdog) and enforce roles.
82            if let AuthLevel::Required = auth.level()
83                && request_params.get("user_id").is_none()
84            {
85                return Err(RequestError::Expected(
86                    StatusCode::UNAUTHORIZED,
87                    format!(
88                        "Cannot open new socket connection for endpoint `{}`: invalid session.",
89                        endpoint_id
90                    )
91                    .into(),
92                ));
93            }
94
95            // Retrieves the endpoint's target database.
96            let db_conns = endpoint.get_db_handle()?;
97
98            // Upgrade connection.
99            debug!("Upgrading connection to WebSockets.");
100
101            let (response, websocket) = hyper_tungstenite::upgrade(request, None)
102                .expect("Cannot upgrade connection to WebSockets.");
103
104            if let ExecutionTarget::Socket(socket_target) = endpoint.execution_target() {
105                if let Some(execute_strategy) = socket_target.executor() {
106                    let execute_strategy = execute_strategy.to_owned();
107
108                    let request_params = request_params.to_owned();
109                    let endpoint = endpoint.to_owned();
110
111                    tokio::task::spawn(async move {
112                        execute_strategy
113                            .execute(
114                                HandshakeCx {
115                                    request_params,
116                                    endpoint,
117                                },
118                                websocket,
119                                db_conns,
120                            )
121                            .await
122                    });
123                } else {
124                    return Err(RequestError::Expected(
125                        StatusCode::INTERNAL_SERVER_ERROR,
126                        format!(
127                            "The socket endpoint `{}` doesn't have any executor defined.",
128                            endpoint.id()
129                        )
130                        .into(),
131                    ));
132                }
133            } else {
134                unreachable!()
135            }
136
137            return Ok(ResponseCx::new_with_status(
138                StatusCode::SWITCHING_PROTOCOLS,
139                response
140                    .headers()
141                    .iter()
142                    .map(|(key, value)| (key.as_str().into(), value.to_str().unwrap().into()))
143                    .collect::<HashMap<_, _>>(),
144                None,
145            ));
146        })
147        .into();
148
149        future as Self::Future // Actually, this is not an error! https://github.com/rust-lang/rust/issues/92929
150    }
151}