wasmtime_wasi_http/p2/
http_impl.rs1use crate::p2::{
4 HttpResult,
5 bindings::http::{
6 outgoing_handler,
7 types::{self, Scheme},
8 },
9 error::internal_error,
10 http_request_error,
11 types::{HostFutureIncomingResponse, HostOutgoingRequest},
12};
13use crate::{WasiHttpCtxView, get_content_length};
14use bytes::Bytes;
15use http_body_util::{BodyExt, Empty};
16use hyper::Method;
17use std::pin::Pin;
18use wasmtime::component::Resource;
19
20impl outgoing_handler::Host for WasiHttpCtxView<'_> {
21 fn handle(
22 &mut self,
23 request_id: Resource<HostOutgoingRequest>,
24 options: Option<Resource<types::RequestOptions>>,
25 ) -> HttpResult<Resource<HostFutureIncomingResponse>> {
26 let opts = match options {
29 Some(id) => Some(self.table.delete(id)?),
30 None => None,
31 };
32
33 let req = self.table.delete(request_id)?;
34
35 let content_length =
40 get_content_length(&req.headers).map_err(|err| internal_error(format!("{err:#}")))?;
41 if req.body.is_none() && content_length.is_some_and(|n| n != 0) {
42 return Err(types::ErrorCode::HttpRequestBodySize(Some(0)).into());
43 }
44
45 let mut builder = hyper::Request::builder();
46
47 builder = builder.method(match req.method {
48 types::Method::Get => Method::GET,
49 types::Method::Head => Method::HEAD,
50 types::Method::Post => Method::POST,
51 types::Method::Put => Method::PUT,
52 types::Method::Delete => Method::DELETE,
53 types::Method::Connect => Method::CONNECT,
54 types::Method::Options => Method::OPTIONS,
55 types::Method::Trace => Method::TRACE,
56 types::Method::Patch => Method::PATCH,
57 types::Method::Other(m) => match hyper::Method::from_bytes(m.as_bytes()) {
58 Ok(method) => method,
59 Err(_) => return Err(types::ErrorCode::HttpRequestMethodInvalid.into()),
60 },
61 });
62
63 let scheme = match req.scheme {
64 Some(scheme) => {
65 let scheme = match scheme {
66 Scheme::Http => http::uri::Scheme::HTTP,
67 Scheme::Https => http::uri::Scheme::HTTPS,
68 Scheme::Other(scheme) => http::uri::Scheme::try_from(scheme.as_str())
69 .map_err(|_| types::ErrorCode::HttpProtocolError)?,
70 };
71 if !self.hooks.is_supported_scheme(&scheme) {
72 return Err(types::ErrorCode::HttpProtocolError.into());
73 }
74 scheme
75 }
76 None => self
79 .hooks
80 .default_scheme()
81 .ok_or(types::ErrorCode::HttpProtocolError)?,
82 };
83
84 let authority = req.authority.unwrap_or_else(String::new);
85
86 let mut uri = http::Uri::builder()
87 .scheme(scheme)
88 .authority(authority.clone());
89
90 if let Some(path) = req.path_with_query {
91 uri = uri.path_and_query(path);
92 }
93
94 builder = builder.uri(uri.build().map_err(http_request_error)?);
95
96 if self.hooks.set_host_header() {
97 builder = builder.header(http::header::HOST, authority.as_str());
98 }
99
100 for (k, v) in req.headers.iter() {
101 builder = builder.header(k, v);
102 }
103
104 let body = req.body.unwrap_or_else(|| {
105 Empty::<Bytes>::new()
106 .map_err(|_| unreachable!("Infallible error"))
107 .boxed_unsync()
108 });
109 let body = body.map_err(Into::into).boxed_unsync();
110
111 let request = builder
112 .body(body)
113 .map_err(|err| internal_error(err.to_string()))?;
114
115 let future = self
116 .hooks
117 .send_request(request, opts, Box::new(async { Ok(()) }));
118 let future = wasmtime_wasi::runtime::spawn(async move {
119 let (res, io) = Pin::from(future).await?;
120 let io = wasmtime_wasi::runtime::spawn(async move {
121 match Pin::from(io).await {
122 Ok(()) => {}
123 Err(e) => tracing::warn!("dropping error {e}"),
126 }
127 });
128 let res = res.map(|b| b.boxed_unsync());
129 Ok((res, io))
130 });
131
132 Ok(self
133 .table
134 .push(HostFutureIncomingResponse::Pending(future))?)
135 }
136}
137
138mod named {
139 use crate::WasiHttpNamedView;
140 use crate::p2::bindings::http::types;
141 use crate::p2::bindings::named_imports::wasi::http::outgoing_handler;
142 use crate::p2::types::{HostFutureIncomingResponse, HostOutgoingRequest};
143 use crate::p2::{HttpError, HttpResult};
144 use wasmtime::component::Resource;
145 use wasmtime_wasi::{NamedId, WasiCtxNamedView};
146
147 impl<T> outgoing_handler::Host for WasiCtxNamedView<'_, T>
148 where
149 T: WasiHttpNamedView,
150 {
151 fn handle(
152 &mut self,
153 id: NamedId,
154 request_id: Resource<HostOutgoingRequest>,
155 options: Option<Resource<types::RequestOptions>>,
156 ) -> HttpResult<Resource<HostFutureIncomingResponse>> {
157 super::outgoing_handler::Host::handle(&mut self.0.http(id), request_id, options)
158 }
159
160 fn convert_error_code(&mut self, err: HttpError) -> wasmtime::Result<types::ErrorCode> {
161 err.downcast()
162 }
163 }
164}