spin-sdk 6.0.0

The Spin Rust SDK makes it easy to build Spin components in Rust.
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
pub use wasip3::http_compat::{IncomingMessage, Request, Response};

use hyperium as http;
pub use hyperium::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode, Uri};
use std::any::Any;
use wasip3::{
    http::types,
    http_compat::{
        http_from_wasi_request, http_from_wasi_response, http_into_wasi_request,
        http_into_wasi_response,
    },
};

pub mod body;
/// gRPC helpers for serving tonic services.
#[cfg(feature = "grpc")]
#[cfg_attr(docsrs, doc(cfg(feature = "grpc")))]
pub mod grpc;

/// A alias for [`std::result::Result`] that uses [`Error`] as the default error type.
///
/// This allows functions throughout the crate to return `Result<T>`
/// instead of writing out `Result<T, Error>` explicitly.
pub type Result<T, E = Error> = ::std::result::Result<T, E>;

type HttpResult<T> = Result<T, types::ErrorCode>;

/// The error type used for HTTP operations within the WASI environment.
///
/// This enum provides a unified representation of all errors that can occur
/// during HTTP request or response handling, whether they originate from
/// WASI-level error codes, dynamic runtime failures, or full HTTP responses
/// returned as error results.
///
/// # See also
/// - [`http::Error`]: Error type originating from the [`http`] crate.
/// - [`wasip3::http::types::ErrorCode`]: Standard WASI HTTP error codes.
/// - [`wasip3::http::types::Response`]: Used when an error represents an HTTP response body.
#[derive(Debug)]
pub enum Error {
    /// A low-level WASI HTTP error code.
    ///
    /// Wraps [`wasip3::http::types::ErrorCode`] to represent
    /// transport-level or protocol-level failures.
    ErrorCode(wasip3::http::types::ErrorCode),
    /// An error originating from the [`http`] crate.
    ///
    /// Covers errors encountered during the construction,
    /// parsing, or validation of [`http`] types (e.g. invalid headers,
    /// malformed URIs, or protocol violations).
    HttpError(http::Error),
    /// A dynamic application or library error.
    ///
    /// Used for any runtime error that implements [`std::error::Error`],
    /// allowing flexibility for different error sources.
    Other(Box<dyn std::error::Error + Send + Sync>),
    /// An HTTP response treated as an error.
    ///
    /// Contains a full [`wasip3::http::types::Response`], such as
    /// a `404 Not Found` or `500 Internal Server Error`, when
    /// the response itself represents an application-level failure.
    Response(wasip3::http::types::Response),
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Error::ErrorCode(e) => write!(f, "{e}"),
            Error::HttpError(e) => write!(f, "{e}"),
            Error::Other(e) => write!(f, "{e}"),
            Error::Response(resp) => match http::StatusCode::from_u16(resp.get_status_code()) {
                Ok(status) => write!(f, "{status}"),
                Err(_) => write!(f, "invalid status code {}", resp.get_status_code()),
            },
        }
    }
}

impl std::error::Error for Error {}

impl From<http::Error> for Error {
    fn from(err: http::Error) -> Error {
        Error::HttpError(err)
    }
}

impl From<anyhow::Error> for Error {
    fn from(err: anyhow::Error) -> Error {
        match err.downcast::<types::ErrorCode>() {
            Ok(code) => Error::ErrorCode(code),
            Err(other) => match other.downcast::<Error>() {
                Ok(err) => err,
                Err(other) => Error::Other(other.into_boxed_dyn_error()),
            },
        }
    }
}

impl From<std::convert::Infallible> for Error {
    fn from(v: std::convert::Infallible) -> Self {
        match v {}
    }
}

impl From<types::ErrorCode> for Error {
    fn from(code: types::ErrorCode) -> Self {
        Error::ErrorCode(code)
    }
}

impl From<types::Response> for Error {
    fn from(resp: types::Response) -> Self {
        Error::Response(resp)
    }
}

impl From<String> for Error {
    fn from(s: String) -> Self {
        Error::other(s)
    }
}

impl From<&'static str> for Error {
    fn from(s: &'static str) -> Self {
        Error::other(s)
    }
}

impl Error {
    /// Creates an [`Error::Other`] from a displayable message.
    ///
    /// This is a convenience constructor for producing errors
    /// without manually wrapping in [`Error::Other`].
    pub fn other(msg: impl Into<String>) -> Self {
        anyhow::Error::msg(msg.into()).into()
    }
}

impl<Ok: IntoResponse, Err: Into<Error>> IntoResponse for Result<Ok, Err> {
    fn into_response(self) -> HttpResult<types::Response> {
        match self {
            Ok(ok) => ok.into_response(),
            Err(err) => match err.into() {
                Error::ErrorCode(code) => Err(code),
                Error::Response(resp) => Ok(resp),
                Error::HttpError(err) => match err {
                    err if err.is::<http::method::InvalidMethod>() => {
                        Err(types::ErrorCode::HttpRequestMethodInvalid)
                    }
                    err if err.is::<http::uri::InvalidUri>() => {
                        Err(types::ErrorCode::HttpRequestUriInvalid)
                    }
                    err => Err(types::ErrorCode::InternalError(Some(err.to_string()))),
                },
                Error::Other(other) => {
                    Err(types::ErrorCode::InternalError(Some(other.to_string())))
                }
            },
        }
    }
}

/// Sends an HTTP request and returns the corresponding [`wasip3::http::types::Response`].
///
/// This function converts the provided value into a [`wasip3::http::types::Request`] using the
/// [`IntoRequest`] trait, dispatches it to the WASI HTTP handler, and awaits
/// the resulting response. It provides a convenient high-level interface for
/// issuing HTTP requests within a WASI environment.
pub async fn send(request: impl IntoRequest) -> HttpResult<Response> {
    let request = request.into_request()?;
    let response = wasip3::http::client::send(request).await?;
    Response::from_response(response)
}

/// Sends a GET request to the given URL.
///
/// This is a convenience wrapper around [`send`] that issues a GET request
/// to the provided URL.
///
/// # Examples
///
/// ```ignore
/// let resp = spin_sdk::http::get("https://example.com").await?;
/// ```
pub async fn get(url: impl AsRef<str>) -> HttpResult<Response> {
    let request = http::Request::get(url.as_ref())
        .body(EmptyBody::new())
        .map_err(|_| types::ErrorCode::HttpRequestUriInvalid)?;
    send(request).await
}

/// Sends a POST request with the given body.
///
/// The body can be any type that implements `Into<bytes::Bytes>`, such as
/// `String`, `Vec<u8>`, `&'static str`, or `bytes::Bytes`.
///
/// # Examples
///
/// ```ignore
/// let resp = spin_sdk::http::post("https://example.com/api", "hello").await?;
/// ```
pub async fn post(url: impl AsRef<str>, body: impl Into<bytes::Bytes>) -> HttpResult<Response> {
    let request = http::Request::post(url.as_ref())
        .body(FullBody::new(body.into()))
        .map_err(|_| types::ErrorCode::HttpRequestUriInvalid)?;
    send(request).await
}

/// Sends a PUT request with the given body.
pub async fn put(url: impl AsRef<str>, body: impl Into<bytes::Bytes>) -> HttpResult<Response> {
    let request = http::Request::put(url.as_ref())
        .body(FullBody::new(body.into()))
        .map_err(|_| types::ErrorCode::HttpRequestUriInvalid)?;
    send(request).await
}

/// Sends a PATCH request with the given body.
pub async fn patch(url: impl AsRef<str>, body: impl Into<bytes::Bytes>) -> HttpResult<Response> {
    let request = http::Request::patch(url.as_ref())
        .body(FullBody::new(body.into()))
        .map_err(|_| types::ErrorCode::HttpRequestUriInvalid)?;
    send(request).await
}

/// Sends a DELETE request to the given URL.
pub async fn delete(url: impl AsRef<str>) -> HttpResult<Response> {
    let request = http::Request::delete(url.as_ref())
        .body(EmptyBody::new())
        .map_err(|_| types::ErrorCode::HttpRequestUriInvalid)?;
    send(request).await
}

/// A body type representing an empty payload.
///
/// This is a convenience alias for [`http_body_util::Empty<bytes::Bytes>`],
/// used when constructing HTTP requests or responses with no body.
///
/// # Examples
///
/// ```ignore
/// use spin_sdk::http::EmptyBody;
///
/// let empty = EmptyBody::new();
/// let response = http::Response::builder()
///     .status(204)
///     .body(empty)
///     .unwrap();
/// ```
pub type EmptyBody = http_body_util::Empty<bytes::Bytes>;

/// A body type representing a complete, in-memory payload.
///
/// This is a convenience alias for [`http_body_util::Full<T>`], used when the
/// entire body is already available as a single value of type `T`.
///
/// It is typically used for sending small or pre-buffered request or response
/// bodies without the need for streaming.
///
/// # Examples
///
/// ```ignore
/// use spin_sdk::http::FullBody;
/// use bytes::Bytes;
///
/// let body = FullBody::new(Bytes::from("hello"));
/// let request = http::Request::builder()
///     .method("POST")
///     .uri("https://example.com")
///     .body(body)
///     .unwrap();
/// ```
pub type FullBody<T> = http_body_util::Full<T>;

/// A body type representing an optional payload.
///
/// This is a convenience alias for [`http_body_util::Either<FullBody<T>, EmptyBody>`],
/// used when an HTTP request or response may or may not carry a body.
///
/// The `Left` variant holds a [`FullBody<T>`] for when a payload is present,
/// while the `Right` variant holds an [`EmptyBody`] for when it is absent.
///
/// # Examples
///
/// ```ignore
/// use spin_sdk::http::{OptionalBody, FullBody, EmptyBody};
/// use bytes::Bytes;
///
/// // With a body
/// let with_body: OptionalBody<Bytes> =
///     http_body_util::Either::Left(FullBody::new(Bytes::from("hello")));
///
/// // Without a body
/// let without_body: OptionalBody<Bytes> =
///     http_body_util::Either::Right(EmptyBody::new());
/// ```
pub type OptionalBody<T> = http_body_util::Either<FullBody<T>, EmptyBody>;

/// A trait for constructing a value from a [`wasip3::http::types::Request`].
///
/// This is the inverse of [`IntoRequest`], allowing higher-level request
/// types to be built from standardized WASI HTTP requests—for example,
/// to parse structured payloads, extract query parameters, or perform
/// request validation.
///
/// # See also
/// - [`IntoRequest`]: Converts a type into a [`wasip3::http::types::Request`].
pub trait FromRequest {
    /// Attempts to construct `Self` from a [`wasip3::http::types::Request`].
    fn from_request(req: wasip3::http::types::Request) -> HttpResult<Self>
    where
        Self: Sized;
}

impl FromRequest for types::Request {
    fn from_request(req: types::Request) -> HttpResult<Self> {
        Ok(req)
    }
}

impl FromRequest for Request {
    fn from_request(req: types::Request) -> HttpResult<Self> {
        http_from_wasi_request(req)
    }
}

/// A trait for any type that can be converted into a [`wasip3::http::types::Request`].
///
/// This trait provides a unified interface for adapting user-defined request
/// types into the lower-level [`wasip3::http::types::Request`] format used by
/// the WASI HTTP subsystem.
///
/// Implementing `IntoRequest` allows custom builders or wrapper types to
/// interoperate seamlessly with APIs that expect standardized WASI HTTP
/// request objects.
///
/// # See also
/// - [`FromRequest`]: The inverse conversion trait.
pub trait IntoRequest {
    /// Converts `self` into a [`wasip3::http::types::Request`].
    fn into_request(self) -> HttpResult<wasip3::http::types::Request>;
}

impl<T> IntoRequest for http::Request<T>
where
    T: http_body::Body + Any,
    T::Data: Into<Vec<u8>>,
    T::Error: Into<Box<dyn std::error::Error + Send + Sync + 'static>>,
{
    fn into_request(self) -> HttpResult<types::Request> {
        http_into_wasi_request(self)
    }
}

/// A trait for constructing a value from a [`wasip3::http::types::Response`].
///
/// This is the inverse of [`IntoResponse`], allowing higher-level response
/// types to be derived from standardized WASI HTTP responses—for example,
/// to deserialize JSON payloads or map responses to domain-specific types.
///
/// # See also
/// - [`IntoResponse`]: Converts a type into a [`wasip3::http::types::Response`].
pub trait FromResponse {
    /// Attempts to construct `Self` from a [`wasip3::http::types::Response`].
    fn from_response(response: wasip3::http::types::Response) -> HttpResult<Self>
    where
        Self: Sized;
}

impl FromResponse for Response {
    fn from_response(resp: types::Response) -> HttpResult<Self> {
        http_from_wasi_response(resp)
    }
}

/// A trait for any type that can be converted into a [`wasip3::http::types::Response`].
///
/// This trait provides a unified interface for adapting user-defined response
/// types into the lower-level [`wasip3::http::types::Response`] format used by
/// the WASI HTTP subsystem.
///
/// Implementing `IntoResponse` enables ergonomic conversion from domain-level
/// response types or builders into standardized WASI HTTP responses.
///
/// # See also
/// - [`FromResponse`]: The inverse conversion trait.
pub trait IntoResponse {
    /// Converts `self` into a [`wasip3::http::types::Response`].
    fn into_response(self) -> HttpResult<wasip3::http::types::Response>;
}

impl IntoResponse for types::Response {
    fn into_response(self) -> HttpResult<types::Response> {
        Ok(self)
    }
}

impl<T> IntoResponse for (http::StatusCode, T)
where
    T: http_body::Body + Any,
    T::Data: Into<Vec<u8>>,
    T::Error: Into<Box<dyn std::error::Error + Send + Sync + 'static>>,
{
    fn into_response(self) -> HttpResult<types::Response> {
        http_into_wasi_response(
            http::Response::builder()
                .status(self.0)
                .body(self.1)
                .unwrap(),
        )
    }
}

impl IntoResponse for http::StatusCode {
    fn into_response(self) -> HttpResult<types::Response> {
        (self, EmptyBody::new()).into_response()
    }
}

impl IntoResponse for &'static str {
    fn into_response(self) -> HttpResult<types::Response> {
        http::Response::new(http_body_util::Full::new(self.as_bytes())).into_response()
    }
}

impl IntoResponse for String {
    fn into_response(self) -> HttpResult<types::Response> {
        http::Response::new(self).into_response()
    }
}

impl<T> IntoResponse for http::Response<T>
where
    T: http_body::Body + Any,
    T::Data: Into<Vec<u8>>,
    T::Error: Into<Box<dyn std::error::Error + Send + Sync + 'static>>,
{
    fn into_response(self) -> HttpResult<types::Response> {
        http_into_wasi_response(self)
    }
}

impl IntoResponse for () {
    fn into_response(self) -> HttpResult<types::Response> {
        http::StatusCode::OK.into_response()
    }
}

impl IntoResponse for &[u8] {
    fn into_response(self) -> HttpResult<types::Response> {
        self.to_vec().into_response()
    }
}

impl IntoResponse for Vec<u8> {
    fn into_response(self) -> HttpResult<types::Response> {
        http::Response::new(FullBody::new(bytes::Bytes::from(self))).into_response()
    }
}

impl IntoResponse for bytes::Bytes {
    fn into_response(self) -> HttpResult<types::Response> {
        http::Response::new(FullBody::new(self)).into_response()
    }
}

impl<T> IntoResponse for (http::StatusCode, http::HeaderMap, T)
where
    T: http_body::Body + Any,
    T::Data: Into<Vec<u8>>,
    T::Error: Into<Box<dyn std::error::Error + Send + Sync + 'static>>,
{
    fn into_response(self) -> HttpResult<types::Response> {
        let (status, headers, body) = self;
        let mut resp = http::Response::builder().status(status).body(body).unwrap();
        *resp.headers_mut() = headers;
        resp.into_response()
    }
}

/// A JSON wrapper for request and response bodies.
///
/// Wraps a value of type `T` and serializes it as JSON when used as a response,
/// automatically setting the `Content-Type: application/json` header.
///
/// # Examples
///
/// ```ignore
/// use spin_sdk::http::{Json, Request};
/// use spin_sdk::http_service;
/// use serde::Serialize;
///
/// #[derive(Serialize)]
/// struct User { name: String }
///
/// #[http_service]
/// async fn handler(_req: Request) -> impl IntoResponse {
///     Json(User { name: "Alice".into() })
/// }
/// ```
#[cfg(feature = "json")]
#[cfg_attr(docsrs, doc(cfg(feature = "json")))]
pub struct Json<T>(pub T);

#[cfg(feature = "json")]
impl<T: serde::Serialize> IntoResponse for Json<T> {
    fn into_response(self) -> HttpResult<types::Response> {
        let body = serde_json::to_vec(&self.0)
            .map_err(|e| types::ErrorCode::InternalError(Some(e.to_string())))?;
        let mut resp = http::Response::builder()
            .status(http::StatusCode::OK)
            .body(FullBody::new(bytes::Bytes::from(body)))
            .unwrap();
        resp.headers_mut().insert(
            http::header::CONTENT_TYPE,
            http::HeaderValue::from_static("application/json"),
        );
        resp.into_response()
    }
}

#[cfg(feature = "json")]
impl<T: serde::Serialize> IntoResponse for (http::StatusCode, Json<T>) {
    fn into_response(self) -> HttpResult<types::Response> {
        let body = serde_json::to_vec(&self.1 .0)
            .map_err(|e| types::ErrorCode::InternalError(Some(e.to_string())))?;
        let mut resp = http::Response::builder()
            .status(self.0)
            .body(FullBody::new(bytes::Bytes::from(body)))
            .unwrap();
        resp.headers_mut().insert(
            http::header::CONTENT_TYPE,
            http::HeaderValue::from_static("application/json"),
        );
        resp.into_response()
    }
}