Skip to main content

http_mel/
client.rs

1use crate::method::*;
2use crate::status::*;
3use async_ringbuf::AsyncHeapRb;
4use melodium_core::{
5    common::executive::{Input, Output, SecretsAccess},
6    *,
7};
8use melodium_macro::{check, mel_model, mel_treatment};
9use std::sync::RwLock;
10use std::sync::{Arc, Weak};
11use std_mel::data::map::*;
12use std_mel::data::string_map::*;
13use trillium::HeaderName;
14use trillium::HeaderValue;
15use trillium::KnownHeaderName;
16use trillium_client::Url;
17use trillium_client::{Body, Client, Conn};
18
19pub const USER_AGENT: &str = concat!("http-mel/", env!("CARGO_PKG_VERSION"));
20
21/// HTTP client for general use
22///
23/// The HTTP client provides configuration for HTTP requests.
24///
25/// - `base_url`: The base URL for a client. All request URLs will be relative to this URL.
26/// - `tcp_no_delay`: TCP `NO_DELAY` field.
27/// - `headers`: Headers to add in requests made with this client.
28/// - `secret_headers`: Headers to add in requests made with this client, whose values are
29/// `Secret<string>` (or `Option<Secret<string>>`, as given by `std/secret::|locate`), such as
30/// `Authorization`. They are revealed by the treatment making each request.
31///
32/// The default headers are `Accept: */*` and `User-Agent: http-mel/<version>`
33#[mel_model(
34    param base_url Option<string> none
35    param tcp_no_delay bool true
36    param headers StringMap none
37    param secret_headers Option<Map> none
38    initialize initialization
39)]
40#[derive(Debug)]
41pub struct HttpClient {
42    model: Weak<HttpClientModel>,
43    client: RwLock<Option<Arc<Client>>>,
44}
45
46impl HttpClient {
47    fn new(model: Weak<HttpClientModel>) -> Self {
48        Self {
49            model,
50            client: RwLock::new(None),
51        }
52    }
53
54    fn initialization(&self) {
55        #[cfg(feature = "real")]
56        {
57            let model = self.model.upgrade().unwrap();
58
59            let config = trillium_rustls::RustlsConfig::default().with_tcp_config(
60                trillium_smol::ClientConfig::new().with_nodelay(model.get_tcp_no_delay()),
61            );
62
63            let mut client = Client::new(config)
64                .with_default_pool()
65                .with_default_header(KnownHeaderName::UserAgent, USER_AGENT);
66            if let Some(base) = model.get_base_url() {
67                if let Ok(url) = Url::parse(&base) {
68                    client = client.with_base(url);
69                }
70            }
71            for (name, content) in &model.get_headers().map {
72                let header_name = HeaderName::from(name.to_string());
73                let header_content = HeaderValue::from(content.to_string());
74                if header_name.is_valid() && header_content.is_valid() {
75                    client = client.with_default_header(header_name.to_owned(), header_content);
76                }
77            }
78
79            *self.client.write().unwrap() = Some(Arc::new(client));
80        }
81    }
82
83    fn client(&self) -> Option<Arc<Client>> {
84        self.client.read().unwrap().clone()
85    }
86
87    /// Reveals the secret headers of the client, then `runtime_headers`, into `conn`,
88    /// on behalf of `access`.
89    async fn add_secret_headers(
90        &self,
91        conn: &mut Conn,
92        access: &SecretsAccess,
93        runtime_headers: Option<&Map>,
94    ) -> Result<(), String> {
95        let model = self.model.upgrade().unwrap();
96        let client_headers = model.get_secret_headers();
97        for (name, value) in client_headers
98            .as_deref()
99            .into_iter()
100            .chain(runtime_headers)
101            .flat_map(|headers| headers.map.iter())
102        {
103            let header_name = HeaderName::from(name.to_string());
104            if !header_name.is_valid() {
105                return Err(format!("'{name}' is not a valid header name"));
106            }
107            let secret = match value {
108                Value::Secret(secret) => secret,
109                Value::Option(Some(value)) => match value.as_ref() {
110                    Value::Secret(secret) => secret,
111                    _ => return Err(format!("secret header '{name}' is not a Secret<string>")),
112                },
113                _ => return Err(format!("secret header '{name}' is not a Secret<string>")),
114            };
115            access
116                .reveal_str(secret, |content| {
117                    let header_content = HeaderValue::from(content.to_string());
118                    if header_content.is_valid() {
119                        conn.request_headers_mut()
120                            .insert(header_name.to_owned(), header_content);
121                        Ok(())
122                    } else {
123                        Err(format!(
124                            "secret header '{name}' is not a valid header value"
125                        ))
126                    }
127                })
128                .await
129                .map_err(|error| format!("secret header '{name}': {error}"))??;
130        }
131        Ok(())
132    }
133}
134
135/// Performs HTTP operation without data emission.
136///
137/// This treatment process HTTP request to the given `url`.
138/// - `method`: HTTP method used for the request.
139///
140/// - `url`: the URL to use for the request (combined with optional base from the client model), request starts as soon as the URL is transmitted.
141/// - `req_headers`: the headers to use for the request (combined with ones defined at client level).
142///
143/// - `status`: HTTP status response.
144/// - `res_headers`: the headers contained in the response.
145/// - `data`: data received as response, corresponding to the HTTP body.
146/// - `completed`: emitted when the incoming request finished successfully.
147/// - `failed`: emitted if the incoming request failed technically.
148/// - `error`: message containing error when request failed technically.
149/// - `finished`: emitted when the incoming request finished, regardless of state.
150#[mel_treatment(
151    model client HttpClient
152    input url Block<string>
153    input req_headers Block<StringMap>
154    output res_headers Block<StringMap>
155    output data Stream<byte>
156    output completed Block<void>
157    output failed Block<void>
158    output finished Block<void>
159    output error Block<string>
160    output status Block<HttpStatus>
161    secrets_access
162)]
163pub async fn request(method: HttpMethod) {
164    if let (Ok(url), Ok(req_headers)) = (
165        url.recv_one_as::<string>().await,
166        req_headers.recv_one_as::<Arc<StringMap>>().await,
167    ) {
168        let model = HttpClientModel::into(client);
169        perform_request(
170            model.inner(),
171            method,
172            url,
173            &req_headers,
174            None,
175            &secrets_access,
176            Responses::new(
177                &**data,
178                &**res_headers,
179                &**completed,
180                &**failed,
181                &**finished,
182                &**error,
183                &**status,
184            ),
185        )
186        .await;
187    }
188}
189
190/// Performs HTTP operation without data emission, with secret headers received at runtime.
191///
192/// Same as `request`, with `secret_headers`, a map built with the treatments of
193/// `std/data/map/block`, whose values are `Secret<string>` (or `Option<Secret<string>>`),
194/// such as given by `vault::get` or derived by `std/secret/block::format`. They are revealed
195/// to make the request, after those of the client, replacing the client ones of the same name.
196#[mel_treatment(
197    model client HttpClient
198    input url Block<string>
199    input req_headers Block<StringMap>
200    input secret_headers Block<Map>
201    output res_headers Block<StringMap>
202    output data Stream<byte>
203    output completed Block<void>
204    output failed Block<void>
205    output finished Block<void>
206    output error Block<string>
207    output status Block<HttpStatus>
208    secrets_access
209)]
210pub async fn request_with_secret_headers(method: HttpMethod) {
211    if let (Ok(url), Ok(req_headers), Ok(runtime_headers)) = (
212        url.recv_one_as::<string>().await,
213        req_headers.recv_one_as::<Arc<StringMap>>().await,
214        secret_headers.recv_one_as::<Arc<Map>>().await,
215    ) {
216        let model = HttpClientModel::into(client);
217        perform_request(
218            model.inner(),
219            method,
220            url,
221            &req_headers,
222            Some(&runtime_headers),
223            &secrets_access,
224            Responses::new(
225                &**data,
226                &**res_headers,
227                &**completed,
228                &**failed,
229                &**finished,
230                &**error,
231                &**status,
232            ),
233        )
234        .await;
235    }
236}
237
238/// Performs HTTP operation with data emission.
239///
240/// This treatment process HTTP request to the given `url`.
241/// - `method`: HTTP method used for the request.
242///
243/// - `url`: the URL to use for the request (combined with optional base from the client model), request starts as soon as the URL is transmitted.
244/// - `req_headers`: the headers to use for the request (combined with ones defined at client level).
245/// - `body`: data to send as request body.
246///
247/// - `status`: HTTP status response.
248/// - `res_headers`: the headers contained in the response.
249/// - `data`: data received as response, corresponding to the HTTP body.
250/// - `completed`: emitted when the request finished successfully.
251/// - `failed`: emitted if the request failed technically.
252/// - `error`: message containing error when request failed technically.
253/// - `finished`: emitted when the request finished, regardless of state.
254#[mel_treatment(
255    model client HttpClient
256    input url Block<string>
257    input req_headers Block<StringMap>
258    input body Stream<byte>
259    output data Stream<byte>
260    output res_headers Block<StringMap>
261    output completed Block<void>
262    output failed Block<void>
263    output finished Block<void>
264    output error Block<string>
265    output status Block<HttpStatus>
266    secrets_access
267)]
268pub async fn request_with_body(method: HttpMethod) {
269    if let (Ok(url), Ok(req_headers)) = (
270        url.recv_one_as::<string>().await,
271        req_headers.recv_one_as::<Arc<StringMap>>().await,
272    ) {
273        let model = HttpClientModel::into(client);
274        perform_request_with_body(
275            model.inner(),
276            method,
277            url,
278            &req_headers,
279            &**body,
280            None,
281            &secrets_access,
282            Responses::new(
283                &**data,
284                &**res_headers,
285                &**completed,
286                &**failed,
287                &**finished,
288                &**error,
289                &**status,
290            ),
291        )
292        .await;
293    }
294}
295
296/// Performs HTTP operation with data emission, with secret headers received at runtime.
297///
298/// Same as `request_with_body`, with `secret_headers`, a map built with the treatments of
299/// `std/data/map/block`, whose values are `Secret<string>` (or `Option<Secret<string>>`),
300/// such as given by `vault::get` or derived by `std/secret/block::format`. They are revealed
301/// to make the request, after those of the client, replacing the client ones of the same name.
302#[mel_treatment(
303    model client HttpClient
304    input url Block<string>
305    input req_headers Block<StringMap>
306    input secret_headers Block<Map>
307    input body Stream<byte>
308    output data Stream<byte>
309    output res_headers Block<StringMap>
310    output completed Block<void>
311    output failed Block<void>
312    output finished Block<void>
313    output error Block<string>
314    output status Block<HttpStatus>
315    secrets_access
316)]
317pub async fn request_with_body_and_secret_headers(method: HttpMethod) {
318    if let (Ok(url), Ok(req_headers), Ok(runtime_headers)) = (
319        url.recv_one_as::<string>().await,
320        req_headers.recv_one_as::<Arc<StringMap>>().await,
321        secret_headers.recv_one_as::<Arc<Map>>().await,
322    ) {
323        let model = HttpClientModel::into(client);
324        perform_request_with_body(
325            model.inner(),
326            method,
327            url,
328            &req_headers,
329            &**body,
330            Some(&runtime_headers),
331            &secrets_access,
332            Responses::new(
333                &**data,
334                &**res_headers,
335                &**completed,
336                &**failed,
337                &**finished,
338                &**error,
339                &**status,
340            ),
341        )
342        .await;
343    }
344}
345
346/// Outputs of the request treatments.
347struct Responses<'a> {
348    data: &'a dyn Output,
349    res_headers: &'a dyn Output,
350    completed: &'a dyn Output,
351    failed: &'a dyn Output,
352    finished: &'a dyn Output,
353    error: &'a dyn Output,
354    status: &'a dyn Output,
355}
356
357impl<'a> Responses<'a> {
358    fn new(
359        data: &'a dyn Output,
360        res_headers: &'a dyn Output,
361        completed: &'a dyn Output,
362        failed: &'a dyn Output,
363        finished: &'a dyn Output,
364        error: &'a dyn Output,
365        status: &'a dyn Output,
366    ) -> Self {
367        Self {
368            data,
369            res_headers,
370            completed,
371            failed,
372            finished,
373            error,
374            status,
375        }
376    }
377}
378
379/// Performs a request without body, for `request` and `request_with_secret_headers`.
380async fn perform_request(
381    http_client: &HttpClient,
382    method: Arc<HttpMethod>,
383    url: String,
384    req_headers: &StringMap,
385    secret_headers: Option<&Map>,
386    access: &SecretsAccess,
387    responses: Responses<'_>,
388) {
389    let Responses {
390        data,
391        res_headers,
392        completed,
393        failed,
394        finished,
395        error,
396        status,
397    } = responses;
398    if let Some(client) = http_client.client() {
399        match client
400            .base()
401            .map(|base_url| base_url.join(&url))
402            .unwrap_or_else(|| Url::parse(&url))
403        {
404            Ok(url) => match async {
405                let mut conn = client.build_conn(method.0, url);
406                for (name, content) in &req_headers.map {
407                    let header_name = HeaderName::from(name.to_string());
408                    if header_name.is_valid() {
409                        let header_content = HeaderValue::from(content.clone());
410                        if header_content.is_valid() {
411                            conn.request_headers_mut()
412                                .insert(header_name.to_owned(), header_content);
413                        }
414                    }
415                }
416                http_client
417                    .add_secret_headers(&mut conn, access, secret_headers)
418                    .await?;
419                conn.await.map_err(|err| err.to_string())
420            }
421            .await
422            {
423                Ok(mut conn) => {
424                    if let Some(recv_status) = conn.status() {
425                        let _ = status
426                            .send_one_as(Arc::new(HttpStatus(recv_status)) as Arc<dyn Data>)
427                            .await;
428
429                        let headers = conn
430                            .response_headers()
431                            .iter()
432                            .filter_map(|(name, value)| {
433                                value
434                                    .as_str()
435                                    .map(|value| (name.to_string(), value.to_string()))
436                            })
437                            .collect();
438
439                        let _ = res_headers
440                            .send_one_as(Arc::new(StringMap::new_with(headers)) as Arc<dyn Data>)
441                            .await;
442
443                        status.close().await;
444                        res_headers.close().await;
445
446                        let data_buf = AsyncHeapRb::<u8>::new(2usize.pow(20));
447                        let (prod, mut cons) = data_buf.split();
448
449                        let response_body = conn.response_body();
450                        let _ = futures::join!(
451                            async {
452                                let _ = futures_lite::io::copy(response_body, prod).await;
453                                let _ = completed.send_one_as(()).await;
454                            },
455                            async {
456                                loop {
457                                    let mut size = 2usize.pow(20);
458                                    let mut recv_data = vec![0; size];
459
460                                    match cons.pop_slice(&mut recv_data).await {
461                                        Ok(_) => {}
462                                        Err(written_size) => size = written_size,
463                                    }
464
465                                    recv_data.truncate(size);
466
467                                    check!(
468                                        data.send_many(TransmissionValue::Byte(recv_data.into()))
469                                            .await
470                                    );
471                                    if cons.is_closed() {
472                                        break;
473                                    }
474                                }
475                            }
476                        );
477                    }
478                }
479                Err(err) => {
480                    let _ = failed.send_one_as(()).await;
481                    let _ = error.send_one_as(err.to_string()).await;
482                }
483            },
484            Err(err) => {
485                let _ = failed.send_one_as(()).await;
486                let _ = error.send_one_as(err.to_string()).await;
487            }
488        }
489        let _ = finished.send_one_as(()).await;
490    }
491}
492
493/// Performs a request with body, for `request_with_body` and
494/// `request_with_body_and_secret_headers`.
495async fn perform_request_with_body(
496    http_client: &HttpClient,
497    method: Arc<HttpMethod>,
498    url: String,
499    req_headers: &StringMap,
500    body: &dyn Input,
501    secret_headers: Option<&Map>,
502    access: &SecretsAccess,
503    responses: Responses<'_>,
504) {
505    let Responses {
506        data,
507        res_headers,
508        completed,
509        failed,
510        finished,
511        error,
512        status,
513    } = responses;
514    if let Some(client) = http_client.client() {
515        match client
516            .base()
517            .map(|base_url| base_url.join(&url))
518            .unwrap_or_else(|| Url::parse(&url))
519        {
520            Ok(url) => {
521                let in_body_buf = AsyncHeapRb::<u8>::new(2usize.pow(20));
522                let (mut in_prod, in_cons) = in_body_buf.split();
523
524                let conn_doing = async {
525                    let mut conn = client.build_conn(method.0, url);
526
527                    for (name, content) in &req_headers.map {
528                        let header_name = HeaderName::from(name.to_string());
529                        if header_name.is_valid() {
530                            let header_content = HeaderValue::from(content.to_string());
531                            if header_content.is_valid() {
532                                conn.request_headers_mut()
533                                    .insert(header_name.to_owned(), header_content);
534                            }
535                        }
536                    }
537                    http_client
538                        .add_secret_headers(&mut conn, access, secret_headers)
539                        .await?;
540                    conn.with_body(Body::new_streaming(in_cons, None))
541                        .await
542                        .map_err(|err| err.to_string())
543                };
544                let body_transmission = async {
545                    while let Ok(body_data) = body
546                        .recv_many()
547                        .await
548                        .map(|values| TryInto::<VecDeque<u8>>::try_into(values).unwrap())
549                    {
550                        if let Err(_) = in_prod.push_iter(body_data.into_iter()).await {
551                            break;
552                        }
553                    }
554                    in_prod.close();
555                };
556
557                match futures::join!(body_transmission, conn_doing) {
558                    (_, Ok(mut conn)) => {
559                        if let Some(recv_status) = conn.status() {
560                            let _ = status
561                                .send_one_as(Arc::new(HttpStatus(recv_status)) as Arc<dyn Data>)
562                                .await;
563
564                            let headers = conn
565                                .response_headers()
566                                .iter()
567                                .filter_map(|(name, value)| {
568                                    value
569                                        .as_str()
570                                        .map(|value| (name.to_string(), value.to_string()))
571                                })
572                                .collect();
573                            let _ =
574                                res_headers
575                                    .send_one_as(
576                                        Arc::new(StringMap::new_with(headers)) as Arc<dyn Data>
577                                    )
578                                    .await;
579
580                            status.close().await;
581                            res_headers.close().await;
582
583                            let out_data_buf = AsyncHeapRb::<u8>::new(2usize.pow(20));
584                            let (out_prod, mut out_cons) = out_data_buf.split();
585
586                            let response_body = conn.response_body();
587                            let _ = futures::join!(
588                                async {
589                                    let _ = futures_lite::io::copy(response_body, out_prod).await;
590                                    let _ = completed.send_one_as(()).await;
591                                },
592                                async {
593                                    loop {
594                                        let mut size = 2usize.pow(20);
595                                        let mut recv_data = vec![0; size];
596                                        match out_cons.pop_slice(&mut recv_data).await {
597                                            Ok(_) => {}
598                                            Err(written_size) => size = written_size,
599                                        }
600
601                                        recv_data.truncate(size);
602
603                                        check!(
604                                            data.send_many(TransmissionValue::Byte(
605                                                recv_data.into()
606                                            ))
607                                            .await
608                                        );
609                                        if out_cons.is_closed() {
610                                            break;
611                                        }
612                                    }
613                                }
614                            );
615                        }
616                    }
617                    (_, Err(err)) => {
618                        let _ = failed.send_one_as(()).await;
619                        let _ = error.send_one_as(err.to_string()).await;
620                    }
621                }
622            }
623            Err(err) => {
624                let _ = failed.send_one_as(()).await;
625                let _ = error.send_one_as(err.to_string()).await;
626            }
627        }
628        let _ = finished.send_one_as(()).await;
629    }
630}