Skip to main content

http_mel/
server.rs

1use crate::method::*;
2use crate::status::*;
3use async_lock::{Barrier as AsyncBarrier, RwLock as AsyncRwLock};
4use async_ringbuf::{AsyncHeapRb, AsyncProducer, AsyncRb};
5use core::{fmt::Debug, mem::MaybeUninit};
6use melodium_core::{
7    common::{
8        descriptor::DataType,
9        executive::{ResultStatus, Secret, SecretOrigin, SecretPolicy},
10    },
11    *,
12};
13use melodium_macro::{mel_context, mel_model, mel_treatment};
14use net_mel::ip::*;
15use ringbuf::SharedRb;
16use routefinder::RouteSpec;
17use routefinder::Segment;
18use std::sync::Arc as AsyncArc;
19use std::sync::Arc;
20use std::{
21    collections::HashMap,
22    sync::{RwLock, Weak},
23};
24use std_mel::data::map::*;
25use std_mel::data::string_map::*;
26use trillium::HeaderName;
27use trillium::HeaderValue;
28use trillium::KnownHeaderName;
29use trillium::{Body, Conn};
30use trillium::{Method, Status};
31use trillium_router::{Router, RouterConnExt};
32use uuid::Uuid;
33
34pub const SERVER: &str = concat!("http-mel/", env!("CARGO_PKG_VERSION"));
35
36/// Describes HTTP request data.
37///
38/// - `id`: identifier of connection, it is an arbitrary number that uniquely identifies a HTTP connection to a server.
39/// - `route`: the route used by the request.
40/// - `path`: the path called by the request.
41/// - `parameters`: the parameters from the route.
42/// - `method`: the HTTP method used by the request.
43/// - `authorization`: the `Authorization` header, if any.
44/// - `cookie`: the `Cookie` header, if any.
45/// - `secret_headers`: the headers listed in the `secret_headers` of the server, present in the
46/// request, as `Secret<string>` values named after the headers as listed.
47///
48/// `Authorization`, `Cookie` and the `secret_headers` of the server are only given as secrets,
49/// and are left out of the request headers.
50/// They come from the client, so the plain `std/secret::reveal` treatment may reveal them,
51/// for example to compare a token, and they are masked in logs once revealed.
52/// `crypto/token::check` compares them with a secret without revealing them to the program.
53#[mel_context]
54pub struct HttpRequest {
55    pub id: u128,
56    pub route: string,
57    pub path: string,
58    pub parameters: StringMap,
59    pub method: HttpMethod,
60    pub authorization: Option<Secret<string>>,
61    pub cookie: Option<Secret<string>>,
62    pub secret_headers: Map,
63}
64
65/// Headers of incoming requests only given as secrets.
66const SECRET_HEADERS: [KnownHeaderName; 2] =
67    [KnownHeaderName::Authorization, KnownHeaderName::Cookie];
68
69/// Gives the `header` of an incoming request as a secret named after it.
70fn secret_header(conn: &Conn, header: KnownHeaderName) -> Option<Secret> {
71    named_secret_header(conn, header.as_ref())
72}
73
74/// Gives the header named `name` of an incoming request as a secret named after it.
75fn named_secret_header(conn: &Conn, name: &str) -> Option<Secret> {
76    conn.request_headers()
77        .get_str(name.to_string())
78        .and_then(|value| {
79            Secret::new(
80                name.to_lowercase(),
81                DataType::String,
82                SecretPolicy {
83                    plain_reveal: true,
84                    ..SecretPolicy::default()
85                },
86                SecretOrigin::Inline(Value::String(value.to_string())),
87            )
88            .ok()
89        })
90}
91
92type AsyncProducerStatus =
93    AsyncProducer<Status, Arc<AsyncRb<Status, SharedRb<Status, Vec<MaybeUninit<Status>>>>>>;
94type AsyncProducerHeaders = AsyncProducer<
95    StringMap,
96    Arc<AsyncRb<StringMap, SharedRb<StringMap, Vec<MaybeUninit<StringMap>>>>>,
97>;
98type AsyncProducerOutgoing =
99    AsyncProducer<u8, Arc<AsyncRb<u8, SharedRb<u8, Vec<MaybeUninit<u8>>>>>>;
100
101/// A HTTP server for general use.
102///
103/// The HTTP server provides configuration for receiving and responding to HTTP incoming requests.
104/// - `host`: the network address to bind with.
105/// - `port`: the port to bind with.
106/// - `secret_headers`: names of headers of incoming requests to give only as secrets,
107/// separated by spaces, such as `X-Gitlab-Token`, in the `secret_headers` of `@HttpRequest`.
108/// `Authorization` and `Cookie` always are.
109///
110/// `HttpServer` aims to be used with `connection` treatment.
111/// Every time a new HTTP request matching a configured route comes, a new track is created with `@HttpRequest` context.
112///
113/// ℹ️ If server binding fails, `failedBinding` is emitted.
114///
115/// ⚠️ Use `HttpServer` with `connection` treatment, as using `incoming` source and `outgoing` treatment directly should be done carefully.
116///
117#[mel_model(
118    param host Ip none
119    param port u16 none
120    param secret_headers string ""
121    source incoming (HttpRequest) (
122        param method HttpMethod none
123        param route string none
124    ) (
125        started Block<void>
126        headers Block<StringMap>
127        data Stream<byte>
128        finished Block<void>
129        completed Block<void>
130        failed Block<void>
131        error Block<string>
132    )
133    source failedBinding () () (
134        failed Block<void>
135        error Block<string>
136    )
137    continuous (continuous)
138    shutdown shutdown
139    invoke_source invoke_source
140)]
141pub struct HttpServer {
142    model: Weak<HttpServerModel>,
143    launch_barrier: AsyncArc<AsyncBarrier>,
144    routes: RwLock<Vec<(Arc<HttpMethod>, String)>>,
145    status: AsyncArc<AsyncRwLock<HashMap<Uuid, AsyncProducerStatus>>>,
146    headers: AsyncArc<AsyncRwLock<HashMap<Uuid, AsyncProducerHeaders>>>,
147    outgoing: AsyncArc<AsyncRwLock<HashMap<Uuid, AsyncProducerOutgoing>>>,
148    #[cfg(feature = "real")]
149    shutdown: trillium_smol::Stopper,
150}
151
152impl Debug for HttpServer {
153    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
154        #[cfg(feature = "real")]
155        {
156            f.debug_struct("HttpServer")
157                .field("model", &self.model)
158                .field("routes", &self.routes)
159                .field("shutdown", &self.shutdown)
160                .finish()
161        }
162
163        #[cfg(not(feature = "real"))]
164        {
165            f.debug_struct("HttpServer")
166                .field("model", &self.model)
167                .field("routes", &self.routes)
168                .finish()
169        }
170    }
171}
172
173impl HttpServer {
174    pub fn new(model: Weak<HttpServerModel>) -> Self {
175        Self {
176            model,
177            launch_barrier: AsyncArc::new(AsyncBarrier::new(2)),
178            routes: RwLock::new(Vec::new()),
179            status: AsyncArc::new(AsyncRwLock::new(HashMap::new())),
180            headers: AsyncArc::new(AsyncRwLock::new(HashMap::new())),
181            outgoing: AsyncArc::new(AsyncRwLock::new(HashMap::new())),
182            #[cfg(feature = "real")]
183            shutdown: trillium_smol::Stopper::new(),
184        }
185    }
186
187    pub fn statuses(&self) -> AsyncArc<AsyncRwLock<HashMap<Uuid, AsyncProducerStatus>>> {
188        AsyncArc::clone(&self.status)
189    }
190
191    pub fn headers(&self) -> AsyncArc<AsyncRwLock<HashMap<Uuid, AsyncProducerHeaders>>> {
192        AsyncArc::clone(&self.headers)
193    }
194
195    pub fn outgoing(&self) -> AsyncArc<AsyncRwLock<HashMap<Uuid, AsyncProducerOutgoing>>> {
196        AsyncArc::clone(&self.outgoing)
197    }
198
199    #[cfg(feature = "real")]
200    async fn continuous(&self) {
201        let model = self.model.upgrade().unwrap();
202
203        self.launch_barrier.wait().await;
204
205        let routes = self.routes.read().unwrap().clone();
206        let secret_headers: Arc<Vec<String>> = Arc::new(
207            model
208                .get_secret_headers()
209                .split_whitespace()
210                .map(str::to_string)
211                .collect(),
212        );
213
214        let status = self.status.clone();
215        let headers = self.headers.clone();
216        let outgoing = self.outgoing.clone();
217
218        let mut router = Router::new();
219        for (method, route) in routes {
220            let route = match RouteSpec::try_from(route.as_str()) {
221                Ok(route) => route,
222                Err(_) => continue,
223            };
224
225            let handler = {
226                let route = Arc::new(route.clone());
227                let status = Arc::clone(&status);
228                let headers = Arc::clone(&headers);
229                let outgoing = Arc::clone(&outgoing);
230                let model = Arc::clone(&model);
231                let method = Arc::clone(&method);
232                let secret_headers = Arc::clone(&secret_headers);
233
234                move |mut conn: Conn| {
235                    let route = Arc::clone(&route);
236                    let status = Arc::clone(&status);
237                    let headers = Arc::clone(&headers);
238                    let outgoing = Arc::clone(&outgoing);
239                    let model = Arc::clone(&model);
240                    let method = Arc::clone(&method);
241                    let secret_headers = Arc::clone(&secret_headers);
242
243                    async move {
244                        let id = Uuid::new_v4();
245                        let http_request = HttpRequest {
246                            id: id.as_u128(),
247                            route: conn.route().map(|r| r.to_string()).unwrap_or_default(),
248                            path: conn.path().to_string(),
249                            parameters: StringMap::new_with(
250                                route
251                                    .segments()
252                                    .iter()
253                                    .filter_map(|seg| {
254                                        if let Segment::Param(param) = seg {
255                                            conn.param(param)
256                                                .map(|v| (param.to_string(), v.to_string()))
257                                        } else {
258                                            None
259                                        }
260                                    })
261                                    .collect(),
262                            ),
263                            method: (*method).clone(),
264                            authorization: secret_header(&conn, KnownHeaderName::Authorization),
265                            cookie: secret_header(&conn, KnownHeaderName::Cookie),
266                            secret_headers: Map::new_with(
267                                secret_headers
268                                    .iter()
269                                    .filter_map(|name| {
270                                        named_secret_header(&conn, name)
271                                            .map(|secret| (name.clone(), Value::Secret(secret)))
272                                    })
273                                    .collect(),
274                            ),
275                        };
276
277                        let params = {
278                            let mut params = HashMap::new();
279                            params.insert(
280                                "method".to_string(),
281                                Value::Data(Arc::clone(&method) as Arc<dyn Data>),
282                            );
283                            params.insert("route".to_string(), route.to_string().into());
284                            params
285                        };
286
287                        let status_buf = AsyncHeapRb::<Status>::new(1);
288                        let (status_prod, mut status_cons) = status_buf.split();
289                        let headers_buf = AsyncHeapRb::<StringMap>::new(1);
290                        let (headers_prod, mut headers_cons) = headers_buf.split();
291                        let outgoing_buf = AsyncHeapRb::<u8>::new(2usize.pow(20));
292                        let (prod, cons) = outgoing_buf.split();
293
294                        status.write().await.insert(id, status_prod);
295                        headers.write().await.insert(id, headers_prod);
296                        outgoing.write().await.insert(id, prod);
297
298                        let incoming_headers = conn
299                            .request_headers()
300                            .iter()
301                            .filter(|(name, _)| {
302                                !SECRET_HEADERS.iter().any(|secret| {
303                                    name.as_ref().eq_ignore_ascii_case(secret.as_ref())
304                                }) && !secret_headers
305                                    .iter()
306                                    .any(|secret| name.as_ref().eq_ignore_ascii_case(secret))
307                            })
308                            .filter_map(|(name, value)| {
309                                value
310                                    .as_str()
311                                    .map(|value| (name.to_string(), value.to_string()))
312                            })
313                            .collect();
314
315                        // For now the reading of request is "one-shot", not allowing effective streaming of very large incoming requests.
316                        let body = conn.request_body().await;
317                        let (content, occured_failure) = match body.read_bytes().await {
318                            Ok(content) => (content, None),
319                            Err(err) => (Vec::new(), Some(err.to_string())),
320                        };
321
322                        model
323                            .new_incoming(
324                                None,
325                                http_request,
326                                &params,
327                                Some(Box::new(move |mut outputs| {
328                                    let started = outputs.get("started");
329                                    let headers = outputs.get("headers");
330                                    let data = outputs.get("data");
331                                    let completed = outputs.get("completed");
332                                    let failed = outputs.get("failed");
333                                    let finished = outputs.get("finished");
334                                    let error = outputs.get("error");
335
336                                    vec![Box::new(Box::pin(async move {
337                                        if let Some(occured_failure) = occured_failure {
338                                            let _ = failed.send_one_as(()).await;
339                                            let _ = error.send_one_as(occured_failure).await;
340                                        } else {
341                                            let _ = started.send_one_as(()).await;
342                                            started.close().await;
343                                            let _ = headers
344                                                .send_one_as(Arc::new(StringMap::new_with(
345                                                    incoming_headers,
346                                                ))
347                                                    as Arc<dyn Data>)
348                                                .await;
349                                            headers.close().await;
350                                            let _ = data
351                                                .send_many(TransmissionValue::Byte(content.into()))
352                                                .await;
353                                            let _ = completed.send_one_as(()).await;
354                                        }
355                                        let _ = finished.send_one_as(()).await;
356
357                                        headers.close().await;
358                                        data.close().await;
359                                        completed.close().await;
360                                        finished.close().await;
361                                        failed.close().await;
362                                        error.close().await;
363                                        ResultStatus::Ok
364                                    }))]
365                                })),
366                            )
367                            .await;
368
369                        if let (Some(status), Some(headers)) =
370                            futures::join!(status_cons.pop(), headers_cons.pop())
371                        {
372                            conn.set_status(status);
373                            conn.response_headers_mut()
374                                .insert(KnownHeaderName::Server, SERVER);
375
376                            for (name, content) in &headers.map {
377                                let header_name = HeaderName::from(name.to_string());
378                                if header_name.is_valid() {
379                                    let header_content = HeaderValue::from(content.clone());
380                                    if header_content.is_valid() {
381                                        conn.response_headers_mut()
382                                            .insert(header_name.to_owned(), header_content);
383                                    }
384                                }
385                            }
386
387                            conn.set_body(Body::new_streaming(cons, None));
388                        } else {
389                            conn.set_status(Status::InternalServerError);
390                        }
391
392                        conn.halt()
393                    }
394                }
395            };
396
397            match method.0 {
398                Method::Delete => router = router.delete(route, handler),
399                Method::Get => router = router.get(route, handler),
400                Method::Patch => router = router.patch(route, handler),
401                Method::Post => router = router.post(route, handler),
402                Method::Put => router = router.put(route, handler),
403                _ => {}
404            }
405        }
406
407        match smol::net::TcpListener::bind((model.get_host().0, model.get_port())).await {
408            Ok(listener) => {
409                trillium_smol::config()
410                    .without_signals()
411                    .with_stopper(self.shutdown.clone())
412                    .with_prebound_server(listener)
413                    .run_async(router)
414                    .await
415            }
416            Err(err) => {
417                model
418                    .new_failedBinding(
419                        None,
420                        &HashMap::new(),
421                        Some(Box::new(move |mut outputs| {
422                            let error = outputs.get("error");
423                            let failed = outputs.get("failed");
424                            vec![Box::new(Box::pin(async move {
425                                let _ = failed.send_one_as(()).await;
426                                let _ = error.send_one_as(err.to_string()).await;
427                                failed.close().await;
428                                error.close().await;
429                                ResultStatus::Ok
430                            }))]
431                        })),
432                    )
433                    .await
434            }
435        }
436    }
437
438    #[cfg(not(feature = "real"))]
439    async fn continuous(&self) {}
440
441    fn invoke_source(&self, source: &str, params: HashMap<String, Value>) {
442        match source {
443            "incoming" => {
444                let method = params
445                    .get("method")
446                    .unwrap()
447                    .clone()
448                    .try_data::<Arc<HttpMethod>>()
449                    .unwrap();
450                let route = params
451                    .get("route")
452                    .unwrap()
453                    .clone()
454                    .try_data::<String>()
455                    .unwrap();
456
457                self.routes.write().unwrap().push((method, route));
458            }
459            _ => {}
460        }
461    }
462
463    fn shutdown(&self) {
464        #[cfg(feature = "real")]
465        self.shutdown.stop();
466    }
467}
468
469/// Start listening for incoming HTTP connections.
470///
471/// Blocks until `trigger` is received, then releases the HTTP server launch barrier so
472/// that the server begins accepting connections.
473///
474/// ℹ️ Use this treatment together with `connection`: `start` unblocks the server, while
475/// each `connection` track handles an individual request.
476///
477/// ```mermaid
478/// graph LR
479///     T("start()")
480///     B["〈🟦〉"] -->|trigger| T
481///     style B fill:#ffffff,stroke:#ffffff
482/// ```
483#[mel_treatment(
484    model http_server HttpServer
485    input trigger Block<void>
486)]
487pub async fn start() {
488    let model = HttpServerModel::into(http_server);
489    let http_server = model.inner();
490
491    if let Ok(_) = trigger.recv_one().await {
492        http_server.launch_barrier.wait().await;
493    }
494}
495
496/// Send an HTTP response for a specific connection.
497///
498/// Low-level counterpart to `connection`, sending `status`, `headers`, and streaming the body
499/// `data` back to the client identified by `id`.
500///
501/// `status` and `headers` must both arrive before any body data is forwarded; if either is
502/// missing the response is not sent.
503///
504/// ⚠️ Use `connection` rather than `outgoing` directly unless you have a specific reason to
505/// manage connection IDs manually.
506///
507/// ```mermaid
508/// graph LR
509///     T("outgoing()")
510///     ST["〈🟦〉"] -->|status| T
511///     H["〈🟨〉"] -->|headers| T
512///     D["🟩 …"] -->|data| T
513///     style ST fill:#ffffff,stroke:#ffffff
514///     style H fill:#ffffff,stroke:#ffffff
515///     style D fill:#ffffff,stroke:#ffffff
516/// ```
517#[mel_treatment(
518    input status Block<HttpStatus>
519    input headers Block<StringMap>
520    input data Stream<byte>
521    model http_server HttpServer
522)]
523pub async fn outgoing(id: u128) {
524    let id = Uuid::from_u128(id);
525    let model = HttpServerModel::into(http_server);
526    let http_server = model.inner();
527
528    let out_status;
529    let out_headers;
530    let output;
531    {
532        let statuses = http_server.statuses();
533        let mut lock = statuses.write().await;
534        out_status = lock.remove(&id);
535    }
536    {
537        let headers = http_server.headers();
538        let mut lock = headers.write().await;
539        out_headers = lock.remove(&id);
540    }
541    {
542        let outputs = http_server.outgoing();
543        let mut lock = outputs.write().await;
544        output = lock.remove(&id);
545    }
546    if let (Some(mut out_status), Some(mut out_headers), Some(mut output)) =
547        (out_status, out_headers, output)
548    {
549        if let Ok((status, headers)) = futures::try_join!(
550            status.recv_one_as::<Arc<HttpStatus>>(),
551            headers.recv_one_as::<Arc<StringMap>>(),
552        ) {
553            match futures::join!(
554                out_status.push(status.0),
555                out_headers.push(Arc::unwrap_or_clone(headers))
556            ) {
557                (Ok(_), Ok(_)) => {
558                    while let (Ok(data), false) =
559                        (data.recv_many_as::<byte>().await, output.is_closed())
560                    {
561                        match output.push_iter(data.into_iter()).await {
562                            Ok(_) => {}
563                            Err(_) => break,
564                        }
565                    }
566                }
567                (_, _) => {}
568            }
569        }
570    }
571}