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    executive::*,
7    *,
8};
9use melodium_macro::{check, mel_data, mel_function, mel_model, mel_treatment};
10use std::sync::RwLock;
11use std::sync::{Arc, Weak};
12use std_mel::data::map::*;
13use std_mel::data::string_map::*;
14use trillium::HeaderName;
15use trillium::HeaderValue;
16use trillium::KnownHeaderName;
17use trillium_client::Url;
18use trillium_client::{Body, Client, Conn};
19
20pub const USER_AGENT: &str = concat!("http-mel/", env!("CARGO_PKG_VERSION"));
21
22/// HTTP client for general use
23///
24/// The HTTP client provides configuration for HTTP requests.
25///
26/// - `base_url`: The base URL for a client. All request URLs will be relative to this URL.
27/// - `tcp_no_delay`: TCP `NO_DELAY` field.
28/// - `headers`: Headers to add in requests made with this client.
29/// - `secret_headers`: Headers to add in requests made with this client, whose values are
30/// `Secret<string>` (or `Option<Secret<string>>`, as given by `std/secret::|locate`), such as
31/// `Authorization`. They are revealed by the treatment making each request.
32///
33/// The default headers are `Accept: */*` and `User-Agent: http-mel/<version>`
34#[mel_model(
35    param base_url Option<string> none
36    param tcp_no_delay bool true
37    param headers StringMap none
38    param secret_headers Option<Map> none
39    initialize initialization
40)]
41#[derive(Debug)]
42pub struct HttpClient {
43    model: Weak<HttpClientModel>,
44    client: RwLock<Option<Arc<Client>>>,
45}
46
47impl HttpClient {
48    fn new(model: Weak<HttpClientModel>) -> Self {
49        Self {
50            model,
51            client: RwLock::new(None),
52        }
53    }
54
55    fn initialization(&self) {
56        #[cfg(feature = "real")]
57        {
58            let model = self.model.upgrade().unwrap();
59
60            let config = trillium_rustls::RustlsConfig::default().with_tcp_config(
61                trillium_smol::ClientConfig::new().with_nodelay(model.get_tcp_no_delay()),
62            );
63
64            let mut client = Client::new(config)
65                .with_default_pool()
66                .with_default_header(KnownHeaderName::UserAgent, USER_AGENT);
67            if let Some(base) = model.get_base_url() {
68                if let Ok(url) = Url::parse(&base) {
69                    client = client.with_base(url);
70                }
71            }
72            for (name, content) in &model.get_headers().map {
73                let header_name = HeaderName::from(name.to_string());
74                let header_content = HeaderValue::from(content.to_string());
75                if header_name.is_valid() && header_content.is_valid() {
76                    client = client.with_default_header(header_name.to_owned(), header_content);
77                }
78            }
79
80            *self.client.write().unwrap() = Some(Arc::new(client));
81        }
82    }
83
84    fn client(&self) -> Option<Arc<Client>> {
85        self.client.read().unwrap().clone()
86    }
87
88    /// Reveals the secret headers of the client, then `runtime_headers`, into `conn`,
89    /// on behalf of `access`.
90    async fn add_secret_headers(
91        &self,
92        conn: &mut Conn,
93        access: &SecretsAccess,
94        runtime_headers: Option<&Map>,
95    ) -> Result<(), String> {
96        let model = self.model.upgrade().unwrap();
97        let client_headers = model.get_secret_headers();
98        for (name, value) in client_headers
99            .as_deref()
100            .into_iter()
101            .chain(runtime_headers)
102            .flat_map(|headers| headers.map.iter())
103        {
104            let header_name = HeaderName::from(name.to_string());
105            if !header_name.is_valid() {
106                return Err(format!("'{name}' is not a valid header name"));
107            }
108            let secret = match value {
109                Value::Secret(secret) => secret,
110                Value::Option(Some(value)) => match value.as_ref() {
111                    Value::Secret(secret) => secret,
112                    _ => return Err(format!("secret header '{name}' is not a Secret<string>")),
113                },
114                _ => return Err(format!("secret header '{name}' is not a Secret<string>")),
115            };
116            access
117                .reveal_str(secret, |content| {
118                    let header_content = HeaderValue::from(content.to_string());
119                    if header_content.is_valid() {
120                        conn.request_headers_mut()
121                            .insert(header_name.to_owned(), header_content);
122                        Ok(())
123                    } else {
124                        Err(format!(
125                            "secret header '{name}' is not a valid header value"
126                        ))
127                    }
128                })
129                .await
130                .map_err(|error| format!("secret header '{name}': {error}"))??;
131        }
132        Ok(())
133    }
134}
135
136/// Performs HTTP operation without data emission.
137///
138/// This treatment process HTTP request to the given `url`.
139/// - `method`: HTTP method used for the request.
140///
141/// - `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.
142/// - `req_headers`: the headers to use for the request (combined with ones defined at client level).
143///
144/// - `status`: HTTP status response.
145/// - `res_headers`: the headers contained in the response.
146/// - `data`: data received as response, corresponding to the HTTP body.
147/// - `completed`: emitted when the incoming request finished successfully.
148/// - `failed`: emitted if the incoming request failed technically.
149/// - `error`: message containing error when request failed technically.
150/// - `finished`: emitted when the incoming request finished, regardless of state.
151#[mel_treatment(
152    model client HttpClient
153    input url Block<string>
154    input req_headers Block<StringMap>
155    output res_headers Block<StringMap>
156    output data Stream<byte>
157    output completed Block<void>
158    output failed Block<void>
159    output finished Block<void>
160    output error Block<string>
161    output status Block<HttpStatus>
162    secrets_access
163)]
164pub async fn request(method: HttpMethod) {
165    if let (Ok(url), Ok(req_headers)) = (
166        url.recv_one_as::<string>().await,
167        req_headers.recv_one_as::<Arc<StringMap>>().await,
168    ) {
169        let model = HttpClientModel::into(client);
170        perform_request(
171            model.inner(),
172            method,
173            url,
174            &req_headers,
175            None,
176            &secrets_access,
177            Responses::new(
178                &**data,
179                &**res_headers,
180                &**completed,
181                &**failed,
182                &**finished,
183                &**error,
184                &**status,
185            ),
186        )
187        .await;
188    }
189}
190
191/// Performs HTTP operation without data emission, with secret headers received at runtime.
192///
193/// Same as `request`, with `secret_headers`, a map built with the treatments of
194/// `std/data/map/block`, whose values are `Secret<string>` (or `Option<Secret<string>>`),
195/// such as given by `vault::get` or derived by `std/secret/block::format`. They are revealed
196/// to make the request, after those of the client, replacing the client ones of the same name.
197#[mel_treatment(
198    model client HttpClient
199    input url Block<string>
200    input req_headers Block<StringMap>
201    input secret_headers Block<Map>
202    output res_headers Block<StringMap>
203    output data Stream<byte>
204    output completed Block<void>
205    output failed Block<void>
206    output finished Block<void>
207    output error Block<string>
208    output status Block<HttpStatus>
209    secrets_access
210)]
211pub async fn request_with_secret_headers(method: HttpMethod) {
212    if let (Ok(url), Ok(req_headers), Ok(runtime_headers)) = (
213        url.recv_one_as::<string>().await,
214        req_headers.recv_one_as::<Arc<StringMap>>().await,
215        secret_headers.recv_one_as::<Arc<Map>>().await,
216    ) {
217        let model = HttpClientModel::into(client);
218        perform_request(
219            model.inner(),
220            method,
221            url,
222            &req_headers,
223            Some(&runtime_headers),
224            &secrets_access,
225            Responses::new(
226                &**data,
227                &**res_headers,
228                &**completed,
229                &**failed,
230                &**finished,
231                &**error,
232                &**status,
233            ),
234        )
235        .await;
236    }
237}
238
239/// Performs HTTP operation with data emission.
240///
241/// This treatment process HTTP request to the given `url`.
242/// - `method`: HTTP method used for the request.
243///
244/// - `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.
245/// - `req_headers`: the headers to use for the request (combined with ones defined at client level).
246/// - `body`: data to send as request body.
247///
248/// - `status`: HTTP status response.
249/// - `res_headers`: the headers contained in the response.
250/// - `data`: data received as response, corresponding to the HTTP body.
251/// - `completed`: emitted when the request finished successfully.
252/// - `failed`: emitted if the request failed technically.
253/// - `error`: message containing error when request failed technically.
254/// - `finished`: emitted when the request finished, regardless of state.
255#[mel_treatment(
256    model client HttpClient
257    input url Block<string>
258    input req_headers Block<StringMap>
259    input body Stream<byte>
260    output data Stream<byte>
261    output res_headers Block<StringMap>
262    output completed Block<void>
263    output failed Block<void>
264    output finished Block<void>
265    output error Block<string>
266    output status Block<HttpStatus>
267    secrets_access
268)]
269pub async fn request_with_body(method: HttpMethod) {
270    if let (Ok(url), Ok(req_headers)) = (
271        url.recv_one_as::<string>().await,
272        req_headers.recv_one_as::<Arc<StringMap>>().await,
273    ) {
274        let model = HttpClientModel::into(client);
275        perform_request_with_body(
276            model.inner(),
277            method,
278            url,
279            &req_headers,
280            &**body,
281            None,
282            &secrets_access,
283            Responses::new(
284                &**data,
285                &**res_headers,
286                &**completed,
287                &**failed,
288                &**finished,
289                &**error,
290                &**status,
291            ),
292        )
293        .await;
294    }
295}
296
297/// Performs HTTP operation with data emission, with secret headers received at runtime.
298///
299/// Same as `request_with_body`, with `secret_headers`, a map built with the treatments of
300/// `std/data/map/block`, whose values are `Secret<string>` (or `Option<Secret<string>>`),
301/// such as given by `vault::get` or derived by `std/secret/block::format`. They are revealed
302/// to make the request, after those of the client, replacing the client ones of the same name.
303#[mel_treatment(
304    model client HttpClient
305    input url Block<string>
306    input req_headers Block<StringMap>
307    input secret_headers Block<Map>
308    input body Stream<byte>
309    output data Stream<byte>
310    output res_headers Block<StringMap>
311    output completed Block<void>
312    output failed Block<void>
313    output finished Block<void>
314    output error Block<string>
315    output status Block<HttpStatus>
316    secrets_access
317)]
318pub async fn request_with_body_and_secret_headers(method: HttpMethod) {
319    if let (Ok(url), Ok(req_headers), Ok(runtime_headers)) = (
320        url.recv_one_as::<string>().await,
321        req_headers.recv_one_as::<Arc<StringMap>>().await,
322        secret_headers.recv_one_as::<Arc<Map>>().await,
323    ) {
324        let model = HttpClientModel::into(client);
325        perform_request_with_body(
326            model.inner(),
327            method,
328            url,
329            &req_headers,
330            &**body,
331            Some(&runtime_headers),
332            &secrets_access,
333            Responses::new(
334                &**data,
335                &**res_headers,
336                &**completed,
337                &**failed,
338                &**finished,
339                &**error,
340                &**status,
341            ),
342        )
343        .await;
344    }
345}
346
347/// Outputs of the request treatments.
348struct Responses<'a> {
349    data: &'a dyn Output,
350    res_headers: &'a dyn Output,
351    completed: &'a dyn Output,
352    failed: &'a dyn Output,
353    finished: &'a dyn Output,
354    error: &'a dyn Output,
355    status: &'a dyn Output,
356}
357
358impl<'a> Responses<'a> {
359    fn new(
360        data: &'a dyn Output,
361        res_headers: &'a dyn Output,
362        completed: &'a dyn Output,
363        failed: &'a dyn Output,
364        finished: &'a dyn Output,
365        error: &'a dyn Output,
366        status: &'a dyn Output,
367    ) -> Self {
368        Self {
369            data,
370            res_headers,
371            completed,
372            failed,
373            finished,
374            error,
375            status,
376        }
377    }
378}
379
380/// Performs a request without body, for `request` and `request_with_secret_headers`.
381async fn perform_request(
382    http_client: &HttpClient,
383    method: Arc<HttpMethod>,
384    url: String,
385    req_headers: &StringMap,
386    secret_headers: Option<&Map>,
387    access: &SecretsAccess,
388    responses: Responses<'_>,
389) {
390    let Responses {
391        data,
392        res_headers,
393        completed,
394        failed,
395        finished,
396        error,
397        status,
398    } = responses;
399    if let Some(client) = http_client.client() {
400        match client
401            .base()
402            .map(|base_url| base_url.join(&url))
403            .unwrap_or_else(|| Url::parse(&url))
404        {
405            Ok(url) => match async {
406                let mut conn = client.build_conn(method.0, url);
407                for (name, content) in &req_headers.map {
408                    let header_name = HeaderName::from(name.to_string());
409                    if header_name.is_valid() {
410                        let header_content = HeaderValue::from(content.clone());
411                        if header_content.is_valid() {
412                            conn.request_headers_mut()
413                                .insert(header_name.to_owned(), header_content);
414                        }
415                    }
416                }
417                http_client
418                    .add_secret_headers(&mut conn, access, secret_headers)
419                    .await?;
420                conn.await.map_err(|err| err.to_string())
421            }
422            .await
423            {
424                Ok(mut conn) => {
425                    if let Some(recv_status) = conn.status() {
426                        let _ = status
427                            .send_one_as(Arc::new(HttpStatus(recv_status)) as Arc<dyn Data>)
428                            .await;
429
430                        let headers = conn
431                            .response_headers()
432                            .iter()
433                            .filter_map(|(name, value)| {
434                                value
435                                    .as_str()
436                                    .map(|value| (name.to_string(), value.to_string()))
437                            })
438                            .collect();
439
440                        let _ = res_headers
441                            .send_one_as(Arc::new(StringMap::new_with(headers)) as Arc<dyn Data>)
442                            .await;
443
444                        status.close().await;
445                        res_headers.close().await;
446
447                        let data_buf = AsyncHeapRb::<u8>::new(2usize.pow(20));
448                        let (prod, mut cons) = data_buf.split();
449
450                        let response_body = conn.response_body();
451                        let _ = futures::join!(
452                            async {
453                                let _ = futures_lite::io::copy(response_body, prod).await;
454                                let _ = completed.send_one_as(()).await;
455                            },
456                            async {
457                                loop {
458                                    let mut size = 2usize.pow(20);
459                                    let mut recv_data = vec![0; size];
460
461                                    match cons.pop_slice(&mut recv_data).await {
462                                        Ok(_) => {}
463                                        Err(written_size) => size = written_size,
464                                    }
465
466                                    recv_data.truncate(size);
467
468                                    check!(
469                                        data.send_many(TransmissionValue::Byte(recv_data.into()))
470                                            .await
471                                    );
472                                    if cons.is_closed() {
473                                        break;
474                                    }
475                                }
476                            }
477                        );
478                    }
479                }
480                Err(err) => {
481                    let _ = failed.send_one_as(()).await;
482                    let _ = error.send_one_as(err.to_string()).await;
483                }
484            },
485            Err(err) => {
486                let _ = failed.send_one_as(()).await;
487                let _ = error.send_one_as(err.to_string()).await;
488            }
489        }
490        let _ = finished.send_one_as(()).await;
491    }
492}
493
494/// Performs a request with body, for `request_with_body` and
495/// `request_with_body_and_secret_headers`.
496async fn perform_request_with_body(
497    http_client: &HttpClient,
498    method: Arc<HttpMethod>,
499    url: String,
500    req_headers: &StringMap,
501    body: &dyn Input,
502    secret_headers: Option<&Map>,
503    access: &SecretsAccess,
504    responses: Responses<'_>,
505) {
506    let Responses {
507        data,
508        res_headers,
509        completed,
510        failed,
511        finished,
512        error,
513        status,
514    } = responses;
515    if let Some(client) = http_client.client() {
516        match client
517            .base()
518            .map(|base_url| base_url.join(&url))
519            .unwrap_or_else(|| Url::parse(&url))
520        {
521            Ok(url) => {
522                let in_body_buf = AsyncHeapRb::<u8>::new(2usize.pow(20));
523                let (mut in_prod, in_cons) = in_body_buf.split();
524
525                let conn_doing = async {
526                    let mut conn = client.build_conn(method.0, url);
527
528                    for (name, content) in &req_headers.map {
529                        let header_name = HeaderName::from(name.to_string());
530                        if header_name.is_valid() {
531                            let header_content = HeaderValue::from(content.to_string());
532                            if header_content.is_valid() {
533                                conn.request_headers_mut()
534                                    .insert(header_name.to_owned(), header_content);
535                            }
536                        }
537                    }
538                    http_client
539                        .add_secret_headers(&mut conn, access, secret_headers)
540                        .await?;
541                    conn.with_body(Body::new_streaming(in_cons, None))
542                        .await
543                        .map_err(|err| err.to_string())
544                };
545                let body_transmission = async {
546                    while let Ok(body_data) = body
547                        .recv_many()
548                        .await
549                        .map(|values| TryInto::<VecDeque<u8>>::try_into(values).unwrap())
550                    {
551                        if let Err(_) = in_prod.push_iter(body_data.into_iter()).await {
552                            break;
553                        }
554                    }
555                    in_prod.close();
556                };
557
558                match futures::join!(body_transmission, conn_doing) {
559                    (_, Ok(mut conn)) => {
560                        if let Some(recv_status) = conn.status() {
561                            let _ = status
562                                .send_one_as(Arc::new(HttpStatus(recv_status)) as Arc<dyn Data>)
563                                .await;
564
565                            let headers = conn
566                                .response_headers()
567                                .iter()
568                                .filter_map(|(name, value)| {
569                                    value
570                                        .as_str()
571                                        .map(|value| (name.to_string(), value.to_string()))
572                                })
573                                .collect();
574                            let _ =
575                                res_headers
576                                    .send_one_as(
577                                        Arc::new(StringMap::new_with(headers)) as Arc<dyn Data>
578                                    )
579                                    .await;
580
581                            status.close().await;
582                            res_headers.close().await;
583
584                            let out_data_buf = AsyncHeapRb::<u8>::new(2usize.pow(20));
585                            let (out_prod, mut out_cons) = out_data_buf.split();
586
587                            let response_body = conn.response_body();
588                            let _ = futures::join!(
589                                async {
590                                    let _ = futures_lite::io::copy(response_body, out_prod).await;
591                                    let _ = completed.send_one_as(()).await;
592                                },
593                                async {
594                                    loop {
595                                        let mut size = 2usize.pow(20);
596                                        let mut recv_data = vec![0; size];
597                                        match out_cons.pop_slice(&mut recv_data).await {
598                                            Ok(_) => {}
599                                            Err(written_size) => size = written_size,
600                                        }
601
602                                        recv_data.truncate(size);
603
604                                        check!(
605                                            data.send_many(TransmissionValue::Byte(
606                                                recv_data.into()
607                                            ))
608                                            .await
609                                        );
610                                        if out_cons.is_closed() {
611                                            break;
612                                        }
613                                    }
614                                }
615                            );
616                        }
617                    }
618                    (_, Err(err)) => {
619                        let _ = failed.send_one_as(()).await;
620                        let _ = error.send_one_as(err.to_string()).await;
621                    }
622                }
623            }
624            Err(err) => {
625                let _ = failed.send_one_as(()).await;
626                let _ = error.send_one_as(err.to_string()).await;
627            }
628        }
629        let _ = finished.send_one_as(()).await;
630    }
631}
632
633/// HTTP request prepared by someone else, such as presigned by object storage: a method, a URL
634/// and headers, made as given.
635///
636/// Prepared requests hold no credential of the program, but their URL often is one, holding a
637/// signature: `Display` and `ToString` give only the method and the host, and treatments
638/// making them never give the URL in errors.
639///
640/// They are read from JSON as `{"method": "PUT", "url": "https://…", "headers": {…}}`, with
641/// `json/value::fromJson<PreparedRequest>`, `headers` being optional, or made with
642/// `|prepared_request`.
643#[mel_data(traits(Serialize Deserialize ToString Display))]
644#[derive(Clone, Serialize, Deserialize)]
645pub struct PreparedRequest {
646    pub method: String,
647    pub url: String,
648    #[serde(default)]
649    pub headers: std::collections::BTreeMap<String, String>,
650}
651
652impl PreparedRequest {
653    /// The method and host of the request, without anything of its URL that could be a
654    /// credential.
655    fn described(&self) -> String {
656        match Url::parse(&self.url)
657            .ok()
658            .and_then(|url| url.host_str().map(|host| host.to_string()))
659        {
660            Some(host) => format!("{} {host}", self.method),
661            None => self.method.clone(),
662        }
663    }
664}
665
666impl core::fmt::Debug for PreparedRequest {
667    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
668        f.debug_struct("PreparedRequest")
669            .field("method", &self.method)
670            .finish_non_exhaustive()
671    }
672}
673
674impl ToString for PreparedRequest {
675    fn to_string(&self) -> string {
676        self.described()
677    }
678}
679
680impl Display for PreparedRequest {
681    fn display(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
682        write!(f, "{}", self.described())
683    }
684}
685
686/// Make a prepared request of `method` to `url`, with `headers`.
687#[mel_function]
688pub fn prepared_request(method: HttpMethod, url: string, headers: StringMap) -> PreparedRequest {
689    PreparedRequest {
690        method: method.0.to_string(),
691        url,
692        headers: headers.map.into_iter().collect(),
693    }
694}
695
696/// Download what a prepared request gives, resuming after cuts.
697///
698/// The body of the answer to `request`, such as a presigned download of object storage, is
699/// streamed through `data`. When the download is cut (connection lost, `5xx`, `429` or `408`
700/// answer), it resumes up to `retries` times, waiting longer each time, from where it was cut
701/// (`Range`), on the same version of the object (`If-Match` with the `ETag` of the first
702/// answer): no byte is given twice.
703///
704/// Once the whole object is given, `completed` is emitted. If the request is refused, the
705/// object changes, it cannot be resumed (no `ETag`), or retries are exhausted, `failed` is
706/// emitted and `error` contains the reason, with the status and the `<Code>` of XML error
707/// bodies, never the URL. What was given before does not make the whole object then.
708/// `finished` is emitted in every case.
709///
710/// The request is made as given, without the headers of any `HttpClient`.
711///
712/// ```mermaid
713/// graph LR
714///     T("download()")
715///     R["〈🟨〉"] -->|request| T
716///
717///     T -->|data| O["… 🟦 🟦 🟦"]
718///     T -->|completed| C["〈🟩〉"]
719///     T -->|failed| F["〈🟥〉"]
720///
721///     style R fill:#ffffff,stroke:#ffffff
722///     style O fill:#ffffff,stroke:#ffffff
723///     style C fill:#ffffff,stroke:#ffffff
724///     style F fill:#ffffff,stroke:#ffffff
725/// ```
726#[mel_treatment(
727    default retries 5
728    input request Block<PreparedRequest>
729    output data Stream<byte>
730    output completed Block<void>
731    output failed Block<void>
732    output finished Block<void>
733    output error Block<string>
734)]
735pub async fn download(retries: u32) {
736    if let Ok(request) = request.recv_one_as::<Arc<PreparedRequest>>().await {
737        #[cfg(feature = "real")]
738        let result =
739            crate::transfer::download(crate::transfer::client(), &request, retries, |bytes| {
740                let data = &data;
741                async move {
742                    data.send_many(TransmissionValue::Byte(bytes.into()))
743                        .await
744                        .is_ok()
745                }
746            })
747            .await;
748        #[cfg(feature = "mock")]
749        let result: Result<bool, String> = {
750            let _ = (&request, retries);
751            Err("downloads are not available in mock mode".to_string())
752        };
753
754        data.close().await;
755        match result {
756            Ok(true) => {
757                let _ = completed.send_one(().into()).await;
758            }
759            Ok(false) => {}
760            Err(reason) => {
761                let _ = failed.send_one(().into()).await;
762                let _ = error.send_one(reason.into()).await;
763            }
764        }
765    }
766    let _ = finished.send_one(().into()).await;
767}