spin_sdk/http/
conversions.rs

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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
use std::collections::HashMap;

use async_trait::async_trait;

use spin_executor::bindings::wasi::io::streams;

use super::{
    Headers, IncomingRequest, IncomingResponse, Json, JsonBodyError, Method, OutgoingRequest,
    OutgoingResponse, RequestBuilder,
};

use super::{responses, NonUtf8BodyError, Request, Response};

impl TryFrom<Response> for OutgoingResponse {
    type Error = anyhow::Error;

    fn try_from(response: Response) -> anyhow::Result<Self> {
        let headers = response
            .headers
            .into_iter()
            .map(|(k, v)| (k, v.into_bytes()))
            .collect::<Vec<_>>();
        let res = OutgoingResponse::new(Headers::from_list(&headers)?);
        res.set_status_code(response.status)
            .map_err(|()| anyhow::anyhow!("error setting status code to {}", response.status))?;
        Ok(res)
    }
}

/// A trait for trying to convert from an `IncomingRequest` to the implementing type
#[async_trait]
pub trait TryFromIncomingRequest {
    /// The error if conversion fails
    type Error;

    /// Try to turn the `IncomingRequest` into the implementing type
    async fn try_from_incoming_request(value: IncomingRequest) -> Result<Self, Self::Error>
    where
        Self: Sized;
}

#[async_trait]
impl TryFromIncomingRequest for IncomingRequest {
    type Error = std::convert::Infallible;
    async fn try_from_incoming_request(request: IncomingRequest) -> Result<Self, Self::Error> {
        Ok(request)
    }
}

#[async_trait]
impl<R> TryFromIncomingRequest for R
where
    R: TryNonRequestFromRequest,
{
    type Error = IncomingRequestError<R::Error>;

    async fn try_from_incoming_request(request: IncomingRequest) -> Result<Self, Self::Error> {
        let req = Request::try_from_incoming_request(request)
            .await
            .map_err(convert_error)?;
        R::try_from_request(req).map_err(IncomingRequestError::ConversionError)
    }
}

#[async_trait]
impl TryFromIncomingRequest for Request {
    type Error = IncomingRequestError;

    async fn try_from_incoming_request(request: IncomingRequest) -> Result<Self, Self::Error> {
        Ok(Request::builder()
            .method(request.method())
            .uri(request.uri())
            .headers(request.headers())
            .body(request.into_body().await.map_err(|e| {
                IncomingRequestError::BodyConversionError(anyhow::anyhow!(
                    "{}",
                    e.to_debug_string()
                ))
            })?)
            .build())
    }
}

#[derive(Debug, thiserror::Error)]
/// An error converting an `IncomingRequest`
pub enum IncomingRequestError<E = std::convert::Infallible> {
    /// There was an error converting the body to an `Option<Vec<u8>>k`
    #[error(transparent)]
    BodyConversionError(anyhow::Error),
    /// There was an error converting the `Request` into the requested type
    #[error(transparent)]
    ConversionError(E),
}

/// Helper for converting `IncomingRequestError`s that cannot fail due to conversion errors
/// into ones that can.
fn convert_error<E>(
    error: IncomingRequestError<std::convert::Infallible>,
) -> IncomingRequestError<E> {
    match error {
        IncomingRequestError::BodyConversionError(e) => {
            IncomingRequestError::BodyConversionError(e)
        }
        IncomingRequestError::ConversionError(_) => unreachable!(),
    }
}

impl<E: IntoResponse> IntoResponse for IncomingRequestError<E> {
    fn into_response(self) -> Response {
        match self {
            IncomingRequestError::BodyConversionError(e) => e.into_response(),
            IncomingRequestError::ConversionError(e) => e.into_response(),
        }
    }
}

/// A trait for any type that can be constructor from a `Request`
pub trait TryFromRequest {
    /// The error if the conversion fails
    type Error;
    /// Try to turn the request into the type
    fn try_from_request(req: Request) -> Result<Self, Self::Error>
    where
        Self: Sized;
}

impl TryFromRequest for Request {
    type Error = std::convert::Infallible;

    fn try_from_request(req: Request) -> Result<Self, Self::Error>
    where
        Self: Sized,
    {
        Ok(req)
    }
}

impl<R: TryNonRequestFromRequest> TryFromRequest for R {
    type Error = R::Error;

    fn try_from_request(req: Request) -> Result<Self, Self::Error>
    where
        Self: Sized,
    {
        TryNonRequestFromRequest::try_from_request(req)
    }
}

/// A hack that allows us to do blanket impls for `T where T: TryFromRequest` for all types
/// `T` *except* for `Request`.
///
/// This is useful in `wasi_http` where we want to implement `TryFromIncomingRequest` for all types that impl
/// `TryFromRequest` with the exception of `Request` itself. This allows that implementation to first convert
/// the `IncomingRequest` to a `Request` and then using this trait convert from `Request` to the given type.
pub trait TryNonRequestFromRequest {
    /// The error if the conversion fails
    type Error;
    /// Try to turn the request into the type
    fn try_from_request(req: Request) -> Result<Self, Self::Error>
    where
        Self: Sized;
}

impl<B: TryFromBody> TryNonRequestFromRequest for hyperium::Request<B> {
    type Error = B::Error;
    fn try_from_request(req: Request) -> Result<Self, Self::Error> {
        let mut builder = hyperium::Request::builder()
            .uri(req.uri())
            .method(req.method);
        for (n, v) in req.headers {
            builder = builder.header(n, v.into_bytes());
        }
        Ok(builder.body(B::try_from_body(req.body)?).unwrap())
    }
}

impl From<super::Method> for hyperium::Method {
    fn from(method: super::Method) -> Self {
        match method {
            super::Method::Get => hyperium::Method::GET,
            super::Method::Post => hyperium::Method::POST,
            super::Method::Put => hyperium::Method::PUT,
            super::Method::Delete => hyperium::Method::DELETE,
            super::Method::Patch => hyperium::Method::PATCH,
            super::Method::Head => hyperium::Method::HEAD,
            super::Method::Options => hyperium::Method::OPTIONS,
            super::Method::Connect => hyperium::Method::CONNECT,
            super::Method::Trace => hyperium::Method::TRACE,
            super::Method::Other(o) => hyperium::Method::from_bytes(o.as_bytes()).expect("TODO"),
        }
    }
}
impl From<hyperium::Method> for super::Method {
    fn from(method: hyperium::Method) -> Self {
        match method {
            hyperium::Method::GET => super::Method::Get,
            hyperium::Method::POST => super::Method::Post,
            hyperium::Method::PUT => super::Method::Put,
            hyperium::Method::DELETE => super::Method::Delete,
            hyperium::Method::PATCH => super::Method::Patch,
            hyperium::Method::HEAD => super::Method::Head,
            hyperium::Method::OPTIONS => super::Method::Options,
            hyperium::Method::CONNECT => super::Method::Connect,
            hyperium::Method::TRACE => super::Method::Trace,
            m => super::Method::Other(m.as_str().into()),
        }
    }
}

/// A trait for any type that can be turned into a `Response`
pub trait IntoResponse {
    /// Turn `self` into a `Response`
    fn into_response(self) -> Response;
}

impl IntoResponse for Response {
    fn into_response(self) -> Response {
        self
    }
}

impl<B> IntoResponse for hyperium::Response<B>
where
    B: IntoBody,
{
    fn into_response(self) -> Response {
        Response::builder()
            .status(self.status().as_u16())
            .headers(self.headers())
            .body(self.into_body())
            .build()
    }
}

impl<R: IntoResponse, E: IntoResponse> IntoResponse for std::result::Result<R, E> {
    fn into_response(self) -> Response {
        match self {
            Ok(r) => r.into_response(),
            Err(e) => e.into_response(),
        }
    }
}

impl IntoResponse for anyhow::Error {
    fn into_response(self) -> Response {
        let body = self.to_string();
        eprintln!("Handler returned an error: {}", body);
        let mut source = self.source();
        while let Some(s) = source {
            eprintln!("  caused by: {}", s);
            source = s.source();
        }
        Response {
            status: 500,
            headers: Default::default(),
            body: body.as_bytes().to_vec(),
        }
    }
}

impl IntoResponse for Box<dyn std::error::Error> {
    fn into_response(self) -> Response {
        let body = self.to_string();
        eprintln!("Handler returned an error: {}", body);
        let mut source = self.source();
        while let Some(s) = source {
            eprintln!("  caused by: {}", s);
            source = s.source();
        }
        Response {
            status: 500,
            headers: Default::default(),
            body: body.as_bytes().to_vec(),
        }
    }
}

#[cfg(feature = "json")]
impl IntoResponse for super::JsonBodyError {
    fn into_response(self) -> Response {
        responses::bad_request(Some(format!("invalid JSON body: {}", self.0)))
    }
}

impl IntoResponse for NonUtf8BodyError {
    fn into_response(self) -> Response {
        responses::bad_request(Some(
            "expected body to be a utf8 string but wasn't".to_owned(),
        ))
    }
}

impl IntoResponse for std::convert::Infallible {
    fn into_response(self) -> Response {
        unreachable!()
    }
}

/// A trait for any type that can be turned into a `Response` status code
pub trait IntoStatusCode {
    /// Turn `self` into a status code
    fn into_status_code(self) -> u16;
}

impl IntoStatusCode for u16 {
    fn into_status_code(self) -> u16 {
        self
    }
}

impl IntoStatusCode for hyperium::StatusCode {
    fn into_status_code(self) -> u16 {
        self.as_u16()
    }
}

/// A trait for any type that can be turned into `Response` headers
pub trait IntoHeaders {
    /// Turn `self` into `Response` headers
    fn into_headers(self) -> Vec<(String, Vec<u8>)>;
}

impl IntoHeaders for Vec<(String, String)> {
    fn into_headers(self) -> Vec<(String, Vec<u8>)> {
        self.into_iter().map(|(k, v)| (k, v.into_bytes())).collect()
    }
}

impl IntoHeaders for Vec<(String, Vec<u8>)> {
    fn into_headers(self) -> Vec<(String, Vec<u8>)> {
        self
    }
}

impl IntoHeaders for HashMap<String, Vec<String>> {
    fn into_headers(self) -> Vec<(String, Vec<u8>)> {
        self.into_iter()
            .flat_map(|(k, values)| values.into_iter().map(move |v| (k.clone(), v.into_bytes())))
            .collect()
    }
}

impl IntoHeaders for HashMap<String, String> {
    fn into_headers(self) -> Vec<(String, Vec<u8>)> {
        self.into_iter().map(|(k, v)| (k, v.into_bytes())).collect()
    }
}

impl IntoHeaders for HashMap<String, Vec<u8>> {
    fn into_headers(self) -> Vec<(String, Vec<u8>)> {
        self.into_iter().collect()
    }
}

impl IntoHeaders for &hyperium::HeaderMap {
    fn into_headers(self) -> Vec<(String, Vec<u8>)> {
        self.iter()
            .map(|(k, v)| (k.as_str().to_owned(), v.as_bytes().to_owned()))
            .collect()
    }
}

impl IntoHeaders for Headers {
    fn into_headers(self) -> Vec<(String, Vec<u8>)> {
        self.entries().into_headers()
    }
}

/// A trait for any type that can be turned into a `Response` body
pub trait IntoBody {
    /// Turn `self` into a `Response` body
    fn into_body(self) -> Vec<u8>;
}

impl<T: IntoBody> IntoBody for Option<T> {
    fn into_body(self) -> Vec<u8> {
        self.map(|b| IntoBody::into_body(b)).unwrap_or_default()
    }
}

impl IntoBody for Vec<u8> {
    fn into_body(self) -> Vec<u8> {
        self
    }
}

impl IntoBody for bytes::Bytes {
    fn into_body(self) -> Vec<u8> {
        self.to_vec()
    }
}

impl IntoBody for () {
    fn into_body(self) -> Vec<u8> {
        Default::default()
    }
}

impl IntoBody for &str {
    fn into_body(self) -> Vec<u8> {
        self.to_owned().into_bytes()
    }
}

impl IntoBody for String {
    fn into_body(self) -> Vec<u8> {
        self.to_owned().into_bytes()
    }
}

/// A trait for converting from a body or failing
pub trait TryFromBody {
    /// The error encountered if conversion fails
    type Error: IntoResponse;
    /// Convert from a body to `Self` or fail
    fn try_from_body(body: Vec<u8>) -> Result<Self, Self::Error>
    where
        Self: Sized;
}

impl<T: TryFromBody> TryFromBody for Option<T> {
    type Error = T::Error;

    fn try_from_body(body: Vec<u8>) -> Result<Self, Self::Error>
    where
        Self: Sized,
    {
        Ok(Some(TryFromBody::try_from_body(body)?))
    }
}

impl<T: FromBody> TryFromBody for T {
    type Error = std::convert::Infallible;

    fn try_from_body(body: Vec<u8>) -> Result<Self, Self::Error>
    where
        Self: Sized,
    {
        Ok(FromBody::from_body(body))
    }
}

impl TryFromBody for String {
    type Error = NonUtf8BodyError;

    fn try_from_body(body: Vec<u8>) -> Result<Self, Self::Error>
    where
        Self: Sized,
    {
        String::from_utf8(body).map_err(|_| NonUtf8BodyError)
    }
}

#[cfg(feature = "json")]
impl<T: serde::de::DeserializeOwned> TryFromBody for Json<T> {
    type Error = JsonBodyError;
    fn try_from_body(body: Vec<u8>) -> Result<Self, Self::Error> {
        Ok(Json(serde_json::from_slice(&body).map_err(JsonBodyError)?))
    }
}

/// A trait from converting from a body
pub trait FromBody {
    /// Convert from a body into the type
    fn from_body(body: Vec<u8>) -> Self;
}

impl FromBody for Vec<u8> {
    fn from_body(body: Vec<u8>) -> Self {
        body
    }
}

impl FromBody for () {
    fn from_body(_body: Vec<u8>) -> Self {}
}

impl FromBody for bytes::Bytes {
    fn from_body(body: Vec<u8>) -> Self {
        Into::into(body)
    }
}

/// A trait for any type that can be turned into a `Response` body or fail
pub trait TryIntoBody {
    /// The type of error if the conversion fails
    type Error;
    /// Turn `self` into an Error
    fn try_into_body(self) -> Result<Vec<u8>, Self::Error>;
}

impl<B> TryIntoBody for B
where
    B: IntoBody,
{
    type Error = std::convert::Infallible;

    fn try_into_body(self) -> Result<Vec<u8>, Self::Error> {
        Ok(self.into_body())
    }
}

#[cfg(feature = "json")]
impl<T: serde::Serialize> TryIntoBody for Json<T> {
    type Error = JsonBodyError;

    fn try_into_body(self) -> Result<Vec<u8>, Self::Error> {
        serde_json::to_vec(&self.0).map_err(JsonBodyError)
    }
}

/// A trait for converting a type into an `OutgoingRequest`
pub trait TryIntoOutgoingRequest {
    /// The error if the conversion fails
    type Error;

    /// Turn the type into an `OutgoingRequest`
    ///
    /// If the implementor can be sure that the `OutgoingRequest::write` has not been called they
    /// can return a buffer as the second element of the returned tuple and `send` will send
    /// that as the request body.
    fn try_into_outgoing_request(self) -> Result<(OutgoingRequest, Option<Vec<u8>>), Self::Error>;
}

impl TryIntoOutgoingRequest for OutgoingRequest {
    type Error = std::convert::Infallible;

    fn try_into_outgoing_request(self) -> Result<(OutgoingRequest, Option<Vec<u8>>), Self::Error> {
        Ok((self, None))
    }
}

impl TryIntoOutgoingRequest for Request {
    type Error = anyhow::Error;

    fn try_into_outgoing_request(self) -> Result<(OutgoingRequest, Option<Vec<u8>>), Self::Error> {
        let headers = self
            .headers()
            .map(|(k, v)| (k.to_owned(), v.as_bytes().to_owned()))
            .collect::<Vec<_>>();
        let request = OutgoingRequest::new(Headers::from_list(&headers)?);
        request
            .set_method(self.method())
            .map_err(|()| anyhow::anyhow!("error setting method to {}", self.method()))?;
        request
            .set_path_with_query(self.path_and_query())
            .map_err(|()| anyhow::anyhow!("error setting path to {:?}", self.path_and_query()))?;
        request
            .set_scheme(Some(if self.is_https() {
                &super::Scheme::Https
            } else {
                &super::Scheme::Http
            }))
            // According to the documentation, `Request::set_scheme` can only fail due to a malformed
            // `Scheme::Other` payload, but we never pass `Scheme::Other` above, hence the `unwrap`.
            .unwrap();
        let authority = self
            .authority()
            // `wasi-http` requires an authority for outgoing requests, so we always supply one:
            .or_else(|| Some(if self.is_https() { ":443" } else { ":80" }));
        request
            .set_authority(authority)
            .map_err(|()| anyhow::anyhow!("error setting authority to {authority:?}"))?;
        Ok((request, Some(self.into_body())))
    }
}

impl TryIntoOutgoingRequest for RequestBuilder {
    type Error = anyhow::Error;

    fn try_into_outgoing_request(
        mut self,
    ) -> Result<(OutgoingRequest, Option<Vec<u8>>), Self::Error> {
        self.build().try_into_outgoing_request()
    }
}

impl<B> TryIntoOutgoingRequest for hyperium::Request<B>
where
    B: TryIntoBody,
    B::Error: std::error::Error + Send + Sync + 'static,
{
    type Error = anyhow::Error;
    fn try_into_outgoing_request(self) -> Result<(OutgoingRequest, Option<Vec<u8>>), Self::Error> {
        let headers = self
            .headers()
            .into_iter()
            .map(|(n, v)| (n.as_str().to_owned(), v.as_bytes().to_owned()))
            .collect::<Vec<_>>();
        let request = OutgoingRequest::new(Headers::from_list(&headers)?);
        request
            .set_method(&self.method().clone().into())
            .map_err(|()| {
                anyhow::anyhow!(
                    "error setting method to {}",
                    Method::from(self.method().clone())
                )
            })?;
        request
            .set_path_with_query(self.uri().path_and_query().map(|p| p.as_str()))
            .map_err(|()| {
                anyhow::anyhow!("error setting path to {:?}", self.uri().path_and_query())
            })?;
        let scheme = self.uri().scheme().map(|s| match s.as_str() {
            "http" => super::Scheme::Http,
            "https" => super::Scheme::Https,
            s => super::Scheme::Other(s.to_owned()),
        });
        request
            .set_scheme(scheme.as_ref())
            .map_err(|()| anyhow::anyhow!("error setting scheme to {scheme:?}"))?;
        request
            .set_authority(self.uri().authority().map(|a| a.as_str()))
            .map_err(|()| {
                anyhow::anyhow!("error setting authority to {:?}", self.uri().authority())
            })?;
        let buffer = TryIntoBody::try_into_body(self.into_body())?;
        Ok((request, Some(buffer)))
    }
}

/// A trait for converting from an `IncomingRequest`
#[async_trait]
pub trait TryFromIncomingResponse {
    /// The error if conversion fails
    type Error;
    /// Turn the `IncomingResponse` into the type
    async fn try_from_incoming_response(resp: IncomingResponse) -> Result<Self, Self::Error>
    where
        Self: Sized;
}

#[async_trait]
impl TryFromIncomingResponse for IncomingResponse {
    type Error = std::convert::Infallible;
    async fn try_from_incoming_response(resp: IncomingResponse) -> Result<Self, Self::Error> {
        Ok(resp)
    }
}

#[async_trait]
impl TryFromIncomingResponse for Response {
    type Error = streams::Error;
    async fn try_from_incoming_response(resp: IncomingResponse) -> Result<Self, Self::Error> {
        Ok(Response::builder()
            .status(resp.status())
            .headers(resp.headers())
            .body(resp.into_body().await?)
            .build())
    }
}

#[async_trait]
impl<B: TryFromBody> TryFromIncomingResponse for hyperium::Response<B> {
    type Error = B::Error;
    async fn try_from_incoming_response(resp: IncomingResponse) -> Result<Self, Self::Error> {
        let mut builder = hyperium::Response::builder().status(resp.status());
        for (n, v) in resp.headers().entries() {
            builder = builder.header(n, v);
        }
        let body = resp.into_body().await.expect("TODO");
        Ok(builder.body(B::try_from_body(body)?).unwrap())
    }
}

/// Turn a type into a `Request`
pub trait TryIntoRequest {
    /// The error if the conversion fails
    type Error;

    /// Turn `self` into a `Request`
    fn try_into_request(self) -> Result<Request, Self::Error>;
}

impl TryIntoRequest for Request {
    type Error = std::convert::Infallible;

    fn try_into_request(self) -> Result<Request, Self::Error> {
        Ok(self)
    }
}

impl<B: TryIntoBody> TryIntoRequest for hyperium::Request<B> {
    type Error = B::Error;
    fn try_into_request(self) -> Result<Request, Self::Error> {
        Ok(Request::builder()
            .method(self.method().clone().into())
            .uri(self.uri().to_string())
            .headers(self.headers())
            .body(B::try_into_body(self.into_body())?)
            .build())
    }
}