http-mel 0.11.0

Mélodium HTTP library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
use crate::method::*;
use crate::status::*;
use async_ringbuf::AsyncHeapRb;
use melodium_core::{
    common::executive::{Input, Output, SecretsAccess},
    *,
};
use melodium_macro::{check, mel_model, mel_treatment};
use std::sync::RwLock;
use std::sync::{Arc, Weak};
use std_mel::data::map::*;
use std_mel::data::string_map::*;
use trillium::HeaderName;
use trillium::HeaderValue;
use trillium::KnownHeaderName;
use trillium_client::Url;
use trillium_client::{Body, Client, Conn};

pub const USER_AGENT: &str = concat!("http-mel/", env!("CARGO_PKG_VERSION"));

/// HTTP client for general use
///
/// The HTTP client provides configuration for HTTP requests.
///
/// - `base_url`: The base URL for a client. All request URLs will be relative to this URL.
/// - `tcp_no_delay`: TCP `NO_DELAY` field.
/// - `headers`: Headers to add in requests made with this client.
/// - `secret_headers`: Headers to add in requests made with this client, whose values are
/// `Secret<string>` (or `Option<Secret<string>>`, as given by `std/secret::|locate`), such as
/// `Authorization`. They are revealed by the treatment making each request.
///
/// The default headers are `Accept: */*` and `User-Agent: http-mel/<version>`
#[mel_model(
    param base_url Option<string> none
    param tcp_no_delay bool true
    param headers StringMap none
    param secret_headers Option<Map> none
    initialize initialization
)]
#[derive(Debug)]
pub struct HttpClient {
    model: Weak<HttpClientModel>,
    client: RwLock<Option<Arc<Client>>>,
}

impl HttpClient {
    fn new(model: Weak<HttpClientModel>) -> Self {
        Self {
            model,
            client: RwLock::new(None),
        }
    }

    fn initialization(&self) {
        #[cfg(feature = "real")]
        {
            let model = self.model.upgrade().unwrap();

            let config = trillium_rustls::RustlsConfig::default().with_tcp_config(
                trillium_smol::ClientConfig::new().with_nodelay(model.get_tcp_no_delay()),
            );

            let mut client = Client::new(config)
                .with_default_pool()
                .with_default_header(KnownHeaderName::UserAgent, USER_AGENT);
            if let Some(base) = model.get_base_url() {
                if let Ok(url) = Url::parse(&base) {
                    client = client.with_base(url);
                }
            }
            for (name, content) in &model.get_headers().map {
                let header_name = HeaderName::from(name.to_string());
                let header_content = HeaderValue::from(content.to_string());
                if header_name.is_valid() && header_content.is_valid() {
                    client = client.with_default_header(header_name.to_owned(), header_content);
                }
            }

            *self.client.write().unwrap() = Some(Arc::new(client));
        }
    }

    fn client(&self) -> Option<Arc<Client>> {
        self.client.read().unwrap().clone()
    }

    /// Reveals the secret headers of the client, then `runtime_headers`, into `conn`,
    /// on behalf of `access`.
    async fn add_secret_headers(
        &self,
        conn: &mut Conn,
        access: &SecretsAccess,
        runtime_headers: Option<&Map>,
    ) -> Result<(), String> {
        let model = self.model.upgrade().unwrap();
        let client_headers = model.get_secret_headers();
        for (name, value) in client_headers
            .as_deref()
            .into_iter()
            .chain(runtime_headers)
            .flat_map(|headers| headers.map.iter())
        {
            let header_name = HeaderName::from(name.to_string());
            if !header_name.is_valid() {
                return Err(format!("'{name}' is not a valid header name"));
            }
            let secret = match value {
                Value::Secret(secret) => secret,
                Value::Option(Some(value)) => match value.as_ref() {
                    Value::Secret(secret) => secret,
                    _ => return Err(format!("secret header '{name}' is not a Secret<string>")),
                },
                _ => return Err(format!("secret header '{name}' is not a Secret<string>")),
            };
            access
                .reveal_str(secret, |content| {
                    let header_content = HeaderValue::from(content.to_string());
                    if header_content.is_valid() {
                        conn.request_headers_mut()
                            .insert(header_name.to_owned(), header_content);
                        Ok(())
                    } else {
                        Err(format!(
                            "secret header '{name}' is not a valid header value"
                        ))
                    }
                })
                .await
                .map_err(|error| format!("secret header '{name}': {error}"))??;
        }
        Ok(())
    }
}

/// Performs HTTP operation without data emission.
///
/// This treatment process HTTP request to the given `url`.
/// - `method`: HTTP method used for the request.
///
/// - `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.
/// - `req_headers`: the headers to use for the request (combined with ones defined at client level).
///
/// - `status`: HTTP status response.
/// - `res_headers`: the headers contained in the response.
/// - `data`: data received as response, corresponding to the HTTP body.
/// - `completed`: emitted when the incoming request finished successfully.
/// - `failed`: emitted if the incoming request failed technically.
/// - `error`: message containing error when request failed technically.
/// - `finished`: emitted when the incoming request finished, regardless of state.
#[mel_treatment(
    model client HttpClient
    input url Block<string>
    input req_headers Block<StringMap>
    output res_headers Block<StringMap>
    output data Stream<byte>
    output completed Block<void>
    output failed Block<void>
    output finished Block<void>
    output error Block<string>
    output status Block<HttpStatus>
    secrets_access
)]
pub async fn request(method: HttpMethod) {
    if let (Ok(url), Ok(req_headers)) = (
        url.recv_one_as::<string>().await,
        req_headers.recv_one_as::<Arc<StringMap>>().await,
    ) {
        let model = HttpClientModel::into(client);
        perform_request(
            model.inner(),
            method,
            url,
            &req_headers,
            None,
            &secrets_access,
            Responses::new(
                &**data,
                &**res_headers,
                &**completed,
                &**failed,
                &**finished,
                &**error,
                &**status,
            ),
        )
        .await;
    }
}

/// Performs HTTP operation without data emission, with secret headers received at runtime.
///
/// Same as `request`, with `secret_headers`, a map built with the treatments of
/// `std/data/map/block`, whose values are `Secret<string>` (or `Option<Secret<string>>`),
/// such as given by `vault::get` or derived by `std/secret/block::format`. They are revealed
/// to make the request, after those of the client, replacing the client ones of the same name.
#[mel_treatment(
    model client HttpClient
    input url Block<string>
    input req_headers Block<StringMap>
    input secret_headers Block<Map>
    output res_headers Block<StringMap>
    output data Stream<byte>
    output completed Block<void>
    output failed Block<void>
    output finished Block<void>
    output error Block<string>
    output status Block<HttpStatus>
    secrets_access
)]
pub async fn request_with_secret_headers(method: HttpMethod) {
    if let (Ok(url), Ok(req_headers), Ok(runtime_headers)) = (
        url.recv_one_as::<string>().await,
        req_headers.recv_one_as::<Arc<StringMap>>().await,
        secret_headers.recv_one_as::<Arc<Map>>().await,
    ) {
        let model = HttpClientModel::into(client);
        perform_request(
            model.inner(),
            method,
            url,
            &req_headers,
            Some(&runtime_headers),
            &secrets_access,
            Responses::new(
                &**data,
                &**res_headers,
                &**completed,
                &**failed,
                &**finished,
                &**error,
                &**status,
            ),
        )
        .await;
    }
}

/// Performs HTTP operation with data emission.
///
/// This treatment process HTTP request to the given `url`.
/// - `method`: HTTP method used for the request.
///
/// - `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.
/// - `req_headers`: the headers to use for the request (combined with ones defined at client level).
/// - `body`: data to send as request body.
///
/// - `status`: HTTP status response.
/// - `res_headers`: the headers contained in the response.
/// - `data`: data received as response, corresponding to the HTTP body.
/// - `completed`: emitted when the request finished successfully.
/// - `failed`: emitted if the request failed technically.
/// - `error`: message containing error when request failed technically.
/// - `finished`: emitted when the request finished, regardless of state.
#[mel_treatment(
    model client HttpClient
    input url Block<string>
    input req_headers Block<StringMap>
    input body Stream<byte>
    output data Stream<byte>
    output res_headers Block<StringMap>
    output completed Block<void>
    output failed Block<void>
    output finished Block<void>
    output error Block<string>
    output status Block<HttpStatus>
    secrets_access
)]
pub async fn request_with_body(method: HttpMethod) {
    if let (Ok(url), Ok(req_headers)) = (
        url.recv_one_as::<string>().await,
        req_headers.recv_one_as::<Arc<StringMap>>().await,
    ) {
        let model = HttpClientModel::into(client);
        perform_request_with_body(
            model.inner(),
            method,
            url,
            &req_headers,
            &**body,
            None,
            &secrets_access,
            Responses::new(
                &**data,
                &**res_headers,
                &**completed,
                &**failed,
                &**finished,
                &**error,
                &**status,
            ),
        )
        .await;
    }
}

/// Performs HTTP operation with data emission, with secret headers received at runtime.
///
/// Same as `request_with_body`, with `secret_headers`, a map built with the treatments of
/// `std/data/map/block`, whose values are `Secret<string>` (or `Option<Secret<string>>`),
/// such as given by `vault::get` or derived by `std/secret/block::format`. They are revealed
/// to make the request, after those of the client, replacing the client ones of the same name.
#[mel_treatment(
    model client HttpClient
    input url Block<string>
    input req_headers Block<StringMap>
    input secret_headers Block<Map>
    input body Stream<byte>
    output data Stream<byte>
    output res_headers Block<StringMap>
    output completed Block<void>
    output failed Block<void>
    output finished Block<void>
    output error Block<string>
    output status Block<HttpStatus>
    secrets_access
)]
pub async fn request_with_body_and_secret_headers(method: HttpMethod) {
    if let (Ok(url), Ok(req_headers), Ok(runtime_headers)) = (
        url.recv_one_as::<string>().await,
        req_headers.recv_one_as::<Arc<StringMap>>().await,
        secret_headers.recv_one_as::<Arc<Map>>().await,
    ) {
        let model = HttpClientModel::into(client);
        perform_request_with_body(
            model.inner(),
            method,
            url,
            &req_headers,
            &**body,
            Some(&runtime_headers),
            &secrets_access,
            Responses::new(
                &**data,
                &**res_headers,
                &**completed,
                &**failed,
                &**finished,
                &**error,
                &**status,
            ),
        )
        .await;
    }
}

/// Outputs of the request treatments.
struct Responses<'a> {
    data: &'a dyn Output,
    res_headers: &'a dyn Output,
    completed: &'a dyn Output,
    failed: &'a dyn Output,
    finished: &'a dyn Output,
    error: &'a dyn Output,
    status: &'a dyn Output,
}

impl<'a> Responses<'a> {
    fn new(
        data: &'a dyn Output,
        res_headers: &'a dyn Output,
        completed: &'a dyn Output,
        failed: &'a dyn Output,
        finished: &'a dyn Output,
        error: &'a dyn Output,
        status: &'a dyn Output,
    ) -> Self {
        Self {
            data,
            res_headers,
            completed,
            failed,
            finished,
            error,
            status,
        }
    }
}

/// Performs a request without body, for `request` and `request_with_secret_headers`.
async fn perform_request(
    http_client: &HttpClient,
    method: Arc<HttpMethod>,
    url: String,
    req_headers: &StringMap,
    secret_headers: Option<&Map>,
    access: &SecretsAccess,
    responses: Responses<'_>,
) {
    let Responses {
        data,
        res_headers,
        completed,
        failed,
        finished,
        error,
        status,
    } = responses;
    if let Some(client) = http_client.client() {
        match client
            .base()
            .map(|base_url| base_url.join(&url))
            .unwrap_or_else(|| Url::parse(&url))
        {
            Ok(url) => match async {
                let mut conn = client.build_conn(method.0, url);
                for (name, content) in &req_headers.map {
                    let header_name = HeaderName::from(name.to_string());
                    if header_name.is_valid() {
                        let header_content = HeaderValue::from(content.clone());
                        if header_content.is_valid() {
                            conn.request_headers_mut()
                                .insert(header_name.to_owned(), header_content);
                        }
                    }
                }
                http_client
                    .add_secret_headers(&mut conn, access, secret_headers)
                    .await?;
                conn.await.map_err(|err| err.to_string())
            }
            .await
            {
                Ok(mut conn) => {
                    if let Some(recv_status) = conn.status() {
                        let _ = status
                            .send_one_as(Arc::new(HttpStatus(recv_status)) as Arc<dyn Data>)
                            .await;

                        let headers = conn
                            .response_headers()
                            .iter()
                            .filter_map(|(name, value)| {
                                value
                                    .as_str()
                                    .map(|value| (name.to_string(), value.to_string()))
                            })
                            .collect();

                        let _ = res_headers
                            .send_one_as(Arc::new(StringMap::new_with(headers)) as Arc<dyn Data>)
                            .await;

                        status.close().await;
                        res_headers.close().await;

                        let data_buf = AsyncHeapRb::<u8>::new(2usize.pow(20));
                        let (prod, mut cons) = data_buf.split();

                        let response_body = conn.response_body();
                        let _ = futures::join!(
                            async {
                                let _ = futures_lite::io::copy(response_body, prod).await;
                                let _ = completed.send_one_as(()).await;
                            },
                            async {
                                loop {
                                    let mut size = 2usize.pow(20);
                                    let mut recv_data = vec![0; size];

                                    match cons.pop_slice(&mut recv_data).await {
                                        Ok(_) => {}
                                        Err(written_size) => size = written_size,
                                    }

                                    recv_data.truncate(size);

                                    check!(
                                        data.send_many(TransmissionValue::Byte(recv_data.into()))
                                            .await
                                    );
                                    if cons.is_closed() {
                                        break;
                                    }
                                }
                            }
                        );
                    }
                }
                Err(err) => {
                    let _ = failed.send_one_as(()).await;
                    let _ = error.send_one_as(err.to_string()).await;
                }
            },
            Err(err) => {
                let _ = failed.send_one_as(()).await;
                let _ = error.send_one_as(err.to_string()).await;
            }
        }
        let _ = finished.send_one_as(()).await;
    }
}

/// Performs a request with body, for `request_with_body` and
/// `request_with_body_and_secret_headers`.
async fn perform_request_with_body(
    http_client: &HttpClient,
    method: Arc<HttpMethod>,
    url: String,
    req_headers: &StringMap,
    body: &dyn Input,
    secret_headers: Option<&Map>,
    access: &SecretsAccess,
    responses: Responses<'_>,
) {
    let Responses {
        data,
        res_headers,
        completed,
        failed,
        finished,
        error,
        status,
    } = responses;
    if let Some(client) = http_client.client() {
        match client
            .base()
            .map(|base_url| base_url.join(&url))
            .unwrap_or_else(|| Url::parse(&url))
        {
            Ok(url) => {
                let in_body_buf = AsyncHeapRb::<u8>::new(2usize.pow(20));
                let (mut in_prod, in_cons) = in_body_buf.split();

                let conn_doing = async {
                    let mut conn = client.build_conn(method.0, url);

                    for (name, content) in &req_headers.map {
                        let header_name = HeaderName::from(name.to_string());
                        if header_name.is_valid() {
                            let header_content = HeaderValue::from(content.to_string());
                            if header_content.is_valid() {
                                conn.request_headers_mut()
                                    .insert(header_name.to_owned(), header_content);
                            }
                        }
                    }
                    http_client
                        .add_secret_headers(&mut conn, access, secret_headers)
                        .await?;
                    conn.with_body(Body::new_streaming(in_cons, None))
                        .await
                        .map_err(|err| err.to_string())
                };
                let body_transmission = async {
                    while let Ok(body_data) = body
                        .recv_many()
                        .await
                        .map(|values| TryInto::<VecDeque<u8>>::try_into(values).unwrap())
                    {
                        if let Err(_) = in_prod.push_iter(body_data.into_iter()).await {
                            break;
                        }
                    }
                    in_prod.close();
                };

                match futures::join!(body_transmission, conn_doing) {
                    (_, Ok(mut conn)) => {
                        if let Some(recv_status) = conn.status() {
                            let _ = status
                                .send_one_as(Arc::new(HttpStatus(recv_status)) as Arc<dyn Data>)
                                .await;

                            let headers = conn
                                .response_headers()
                                .iter()
                                .filter_map(|(name, value)| {
                                    value
                                        .as_str()
                                        .map(|value| (name.to_string(), value.to_string()))
                                })
                                .collect();
                            let _ =
                                res_headers
                                    .send_one_as(
                                        Arc::new(StringMap::new_with(headers)) as Arc<dyn Data>
                                    )
                                    .await;

                            status.close().await;
                            res_headers.close().await;

                            let out_data_buf = AsyncHeapRb::<u8>::new(2usize.pow(20));
                            let (out_prod, mut out_cons) = out_data_buf.split();

                            let response_body = conn.response_body();
                            let _ = futures::join!(
                                async {
                                    let _ = futures_lite::io::copy(response_body, out_prod).await;
                                    let _ = completed.send_one_as(()).await;
                                },
                                async {
                                    loop {
                                        let mut size = 2usize.pow(20);
                                        let mut recv_data = vec![0; size];
                                        match out_cons.pop_slice(&mut recv_data).await {
                                            Ok(_) => {}
                                            Err(written_size) => size = written_size,
                                        }

                                        recv_data.truncate(size);

                                        check!(
                                            data.send_many(TransmissionValue::Byte(
                                                recv_data.into()
                                            ))
                                            .await
                                        );
                                        if out_cons.is_closed() {
                                            break;
                                        }
                                    }
                                }
                            );
                        }
                    }
                    (_, Err(err)) => {
                        let _ = failed.send_one_as(()).await;
                        let _ = error.send_one_as(err.to_string()).await;
                    }
                }
            }
            Err(err) => {
                let _ = failed.send_one_as(()).await;
                let _ = error.send_one_as(err.to_string()).await;
            }
        }
        let _ = finished.send_one_as(()).await;
    }
}