crux_http 0.17.0

HTTP capability for use with crux_core
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
//! The protocol for communicating with the shell
//!
//! Crux capabilities don't interface with the outside world themselves, they carry
//! out all their operations by exchanging messages with the platform specific shell.
//! This module defines the protocol for `crux_http` to communicate with the shell.

use async_trait::async_trait;
use derive_builder::Builder;
use facet_generate_attrs as typegen;
use serde::{Deserialize, Serialize};

use crate::HttpError;

#[derive(facet::Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct HttpHeader {
    pub name: String,
    pub value: String,
}

#[derive(facet::Facet, Serialize, Deserialize, Default, Clone, PartialEq, Eq, Builder)]
#[builder(
    custom_constructor,
    build_fn(private, name = "fallible_build"),
    setter(into)
)]
pub struct HttpRequest {
    pub method: String,
    pub url: String,
    #[builder(setter(custom))]
    pub headers: Vec<HttpHeader>,
    #[serde(with = "serde_bytes")]
    #[facet(typegen::bytes)]
    pub body: Vec<u8>,
}

impl std::fmt::Debug for HttpRequest {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let body_repr = if let Ok(s) = std::str::from_utf8(&self.body) {
            if s.len() < 50 {
                format!("\"{s}\"")
            } else {
                format!("\"{}\"...", s.chars().take(50).collect::<String>())
            }
        } else {
            format!("<binary data - {} bytes>", self.body.len())
        };
        let mut builder = f.debug_struct("HttpRequest");
        builder
            .field("method", &self.method)
            .field("url", &self.url);
        if !self.headers.is_empty() {
            builder.field("headers", &self.headers);
        }
        builder.field("body", &format_args!("{body_repr}")).finish()
    }
}

macro_rules! http_method {
    ($name:ident, $method:expr) => {
        pub fn $name(url: impl Into<String>) -> HttpRequestBuilder {
            HttpRequestBuilder {
                method: Some($method.to_string()),
                url: Some(url.into()),
                headers: Some(vec![]),
                body: Some(vec![]),
            }
        }
    };
}

impl HttpRequest {
    http_method!(get, "GET");
    http_method!(put, "PUT");
    http_method!(delete, "DELETE");
    http_method!(post, "POST");
    http_method!(patch, "PATCH");
    http_method!(head, "HEAD");
    http_method!(options, "OPTIONS");
}

impl HttpRequestBuilder {
    pub fn header(&mut self, name: impl Into<String>, value: impl Into<String>) -> &mut Self {
        self.headers.get_or_insert_with(Vec::new).push(HttpHeader {
            name: name.into(),
            value: value.into(),
        });
        self
    }

    /// Sets the query parameters of the request to the given value.
    ///
    /// # Errors
    /// Returns an [`HttpError`] if the serialization fails.
    pub fn query(&mut self, query: &impl Serialize) -> crate::Result<&mut Self> {
        if let Some(url) = &mut self.url {
            if url.contains('?') {
                url.push('&');
            } else {
                url.push('?');
            }
            url.push_str(&serde_qs::to_string(query)?);
        }

        Ok(self)
    }

    /// Sets the body of the request to the JSON representation of the given value.
    ///
    /// # Panics
    /// Panics if the serialization fails.
    pub fn json(&mut self, body: impl serde::Serialize) -> &mut Self {
        self.body = Some(serde_json::to_vec(&body).unwrap());
        self
    }

    /// Builds the request.
    ///
    /// # Panics
    /// Panics if any required fields are missing.
    #[must_use]
    pub fn build(&self) -> HttpRequest {
        self.fallible_build()
            .expect("All required fields were initialized")
    }
}

#[derive(facet::Facet, Serialize, Deserialize, Default, Clone, Debug, PartialEq, Eq, Builder)]
#[builder(
    custom_constructor,
    build_fn(private, name = "fallible_build"),
    setter(into)
)]
pub struct HttpResponse {
    pub status: u16, // FIXME this probably should be a giant enum instead.
    #[builder(setter(custom))]
    pub headers: Vec<HttpHeader>,
    #[serde(with = "serde_bytes")]
    #[facet(typegen::bytes)]
    pub body: Vec<u8>,
}

impl HttpResponse {
    #[must_use]
    pub fn status(status: u16) -> HttpResponseBuilder {
        HttpResponseBuilder {
            status: Some(status),
            headers: Some(vec![]),
            body: Some(vec![]),
        }
    }
    #[must_use]
    pub fn ok() -> HttpResponseBuilder {
        Self::status(200)
    }
}

impl HttpResponseBuilder {
    pub fn header(&mut self, name: impl Into<String>, value: impl Into<String>) -> &mut Self {
        self.headers.get_or_insert_with(Vec::new).push(HttpHeader {
            name: name.into(),
            value: value.into(),
        });
        self
    }

    /// Sets the body of the response to the given JSON.
    ///
    /// # Panics
    /// If the JSON serialization fails.
    pub fn json(&mut self, body: impl serde::Serialize) -> &mut Self {
        self.body = Some(serde_json::to_vec(&body).unwrap());
        self
    }

    /// Builds the response.
    ///
    /// # Panics
    /// If a required field has not been initialized.
    #[must_use]
    pub fn build(&self) -> HttpResponse {
        self.fallible_build()
            .expect("All required fields were initialized")
    }
}

#[derive(facet::Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
#[repr(C)]
pub enum HttpResult {
    Ok(HttpResponse),
    Err(HttpError),
}

impl From<crate::Result<HttpResponse>> for HttpResult {
    fn from(result: Result<HttpResponse, HttpError>) -> Self {
        match result {
            Ok(response) => HttpResult::Ok(response),
            Err(err) => HttpResult::Err(err),
        }
    }
}

impl crux_core::capability::Operation for HttpRequest {
    type Output = HttpResult;

    #[cfg(feature = "typegen")]
    fn register_types(
        generator: &mut crux_core::type_generation::serde::TypeGen,
    ) -> crux_core::type_generation::serde::Result {
        generator.register_type::<HttpError>()?;
        generator.register_type::<Self>()?;
        generator.register_type::<Self::Output>()?;
        Ok(())
    }
}

#[async_trait]
pub(crate) trait EffectSender {
    async fn send(&self, effect: HttpRequest) -> HttpResult;
}

#[async_trait]
pub(crate) trait ProtocolRequestBuilder {
    async fn into_protocol_request(mut self) -> crate::Result<HttpRequest>;
}

#[async_trait]
impl ProtocolRequestBuilder for crate::Request {
    async fn into_protocol_request(mut self) -> crate::Result<HttpRequest> {
        let body = if self.is_empty() == Some(false) {
            self.take_body().into_bytes().await?
        } else {
            vec![]
        };

        Ok(HttpRequest {
            method: self.method().to_string(),
            url: self.url().to_string(),
            headers: self
                .iter()
                .flat_map(|(name, values)| {
                    values.iter().map(|value| HttpHeader {
                        name: name.to_string(),
                        value: value.to_string(),
                    })
                })
                .collect(),
            body,
        })
    }
}

impl From<HttpResponse> for crate::ResponseAsync {
    fn from(effect_response: HttpResponse) -> Self {
        let mut res = http_types::Response::new(effect_response.status);
        res.set_body(effect_response.body);
        for header in effect_response.headers {
            res.append_header(header.name.as_str(), header.value);
        }

        crate::ResponseAsync::new(res)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde::{Deserialize, Serialize};

    #[test]
    fn test_http_request_get() {
        let req = HttpRequest::get("https://example.com").build();

        insta::assert_debug_snapshot!(req, @r#"
        HttpRequest {
            method: "GET",
            url: "https://example.com",
            body: "",
        }
        "#);
    }

    #[test]
    fn test_http_request_get_with_fields() {
        let req = HttpRequest::get("https://example.com")
            .header("foo", "bar")
            .body("123")
            .build();

        insta::assert_debug_snapshot!(req, @r#"
        HttpRequest {
            method: "GET",
            url: "https://example.com",
            headers: [
                HttpHeader {
                    name: "foo",
                    value: "bar",
                },
            ],
            body: "123",
        }
        "#);
    }

    #[test]
    fn test_http_response_status() {
        let req = HttpResponse::status(302).build();

        insta::assert_debug_snapshot!(req, @"
        HttpResponse {
            status: 302,
            headers: [],
            body: [],
        }
        ");
    }

    #[test]
    fn test_http_response_status_with_fields() {
        let req = HttpResponse::status(302)
            .header("foo", "bar")
            .body("hey")
            .build();

        insta::assert_debug_snapshot!(req, @r#"
        HttpResponse {
            status: 302,
            headers: [
                HttpHeader {
                    name: "foo",
                    value: "bar",
                },
            ],
            body: [
                104,
                101,
                121,
            ],
        }
        "#);
    }

    #[test]
    fn test_http_request_debug_repr() {
        {
            // small
            let req = HttpRequest::post("http://example.com")
                .header("foo", "bar")
                .body("hello world!")
                .build();
            let repr = format!("{req:?}");
            assert_eq!(
                repr,
                r#"HttpRequest { method: "POST", url: "http://example.com", headers: [HttpHeader { name: "foo", value: "bar" }], body: "hello world!" }"#
            );
        }

        {
            // big
            let req = HttpRequest::post("http://example.com")
                // we check that we handle unicode boundaries correctly
                .body("abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstu😀😀😀😀😀😀")
                .build();
            let repr = format!("{req:?}");
            assert_eq!(
                repr,
                r#"HttpRequest { method: "POST", url: "http://example.com", body: "abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstu😀😀"... }"#
            );
        }

        {
            // binary
            let req = HttpRequest::post("http://example.com")
                .body(vec![255, 254, 253, 252])
                .build();
            let repr = format!("{req:?}");
            assert_eq!(
                repr,
                r#"HttpRequest { method: "POST", url: "http://example.com", body: <binary data - 4 bytes> }"#
            );
        }
    }

    #[test]
    fn test_http_request_query() {
        #[derive(Serialize, Deserialize)]
        struct QueryParams {
            page: u32,
            limit: u32,
            search: String,
        }

        let query = QueryParams {
            page: 2,
            limit: 10,
            search: "test".to_string(),
        };

        let mut builder = HttpRequestBuilder {
            method: Some("GET".to_string()),
            url: Some("https://example.com".to_string()),
            headers: Some(vec![HttpHeader {
                name: "foo".to_string(),
                value: "bar".to_string(),
            }]),
            body: Some(vec![]),
        };

        builder
            .query(&query)
            .expect("should serialize query params");
        let req = builder.build();

        insta::assert_debug_snapshot!(req, @r#"
        HttpRequest {
            method: "GET",
            url: "https://example.com?page=2&limit=10&search=test",
            headers: [
                HttpHeader {
                    name: "foo",
                    value: "bar",
                },
            ],
            body: "",
        }
        "#);
    }

    #[test]
    fn test_http_request_query_with_special_chars() {
        #[derive(Serialize, Deserialize)]
        struct QueryParams {
            allowed: String,
            disallowed: String,
            delimiters: String,
            alpha_numeric_and_space: String,
        }

        let query = QueryParams {
            // allowed chars (RFC 3986)
            allowed: ";/?:@$,-.!~*'()".to_string(),
            // disallowed chars (RFC 3986)
            disallowed: "#".to_string(),
            // delimiters in key value pairs, need encoding
            delimiters: "&=+".to_string(),
            // not RFC 3986 Compliant (space should be %20 not +)
            // but "+" is very common so we allow it
            alpha_numeric_and_space: "ABC abc 123".to_string(),
        };

        let mut builder = HttpRequestBuilder {
            method: Some("GET".to_string()),
            url: Some("https://example.com".to_string()),
            headers: Some(vec![]),
            body: Some(vec![]),
        };

        builder
            .query(&query)
            .expect("should serialize query params with special chars");
        let req = builder.build();

        insta::assert_debug_snapshot!(req, @r#"
        HttpRequest {
            method: "GET",
            url: "https://example.com?allowed=;/?:@$,-.!~*'()&disallowed=%23&delimiters=%26%3D%2B&alpha_numeric_and_space=ABC+abc+123",
            body: "",
        }
        "#);
    }

    #[test]
    fn test_http_request_query_with_empty_values() {
        #[derive(Serialize, Deserialize)]
        struct QueryParams {
            empty: String,
            none: Option<String>,
        }

        let query = QueryParams {
            empty: String::new(),
            none: None,
        };

        let mut builder = HttpRequestBuilder {
            method: Some("GET".to_string()),
            url: Some("https://example.com".to_string()),
            headers: Some(vec![]),
            body: Some(vec![]),
        };

        builder
            .query(&query)
            .expect("should serialize query params with empty values");
        let req = builder.build();

        insta::assert_debug_snapshot!(req, @r#"
        HttpRequest {
            method: "GET",
            url: "https://example.com?empty=&none",
            body: "",
        }
        "#);
    }

    #[test]
    fn test_http_request_query_with_url_with_existing_query_params() {
        #[derive(Serialize, Deserialize)]
        struct QueryParams {
            name: String,
            email: String,
        }

        let query = QueryParams {
            name: "John Doe".to_string(),
            email: "john@example.com".to_string(),
        };

        let mut builder = HttpRequestBuilder {
            method: Some("GET".to_string()),
            url: Some("https://example.com?foo=bar".to_string()),
            headers: Some(vec![]),
            body: Some(vec![]),
        };

        builder
            .query(&query)
            .expect("should serialize query params");
        let req = builder.build();

        insta::assert_debug_snapshot!(req, @r#"
        HttpRequest {
            method: "GET",
            url: "https://example.com?foo=bar&name=John+Doe&email=john@example.com",
            body: "",
        }
        "#);
    }
}